Use oneshot functions instead of File handle

main
mat ess 2023-03-03 14:53:33 -05:00
parent 410740ea21
commit 7ea944cb0a
4 changed files with 64 additions and 90 deletions

100
Cargo.lock generated
View File

@ -17,15 +17,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "ansi_term"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.69" version = "1.0.69"
@ -59,6 +50,17 @@ dependencies = [
"webpki-roots", "webpki-roots",
] ]
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi 0.1.19",
"libc",
"winapi",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.1.0" version = "1.1.0"
@ -109,8 +111,8 @@ dependencies = [
"serde", "serde",
"tokio", "tokio",
"tracing", "tracing",
"tracing-forest",
"tracing-subscriber", "tracing-subscriber",
"tracing-tree",
] ]
[[package]] [[package]]
@ -144,12 +146,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f"
dependencies = [ dependencies = [
"iana-time-zone", "iana-time-zone",
"js-sys",
"num-integer", "num-integer",
"num-traits", "num-traits",
"serde", "serde",
"time 0.1.45",
"wasm-bindgen",
"winapi", "winapi",
] ]
@ -440,7 +439,7 @@ checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"libc", "libc",
"wasi 0.11.0+wasi-snapshot-preview1", "wasi",
] ]
[[package]] [[package]]
@ -468,6 +467,15 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hermit-abi"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.2.6" version = "0.2.6"
@ -707,7 +715,7 @@ checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9"
dependencies = [ dependencies = [
"libc", "libc",
"log", "log",
"wasi 0.11.0+wasi-snapshot-preview1", "wasi",
"windows-sys 0.45.0", "windows-sys 0.45.0",
] ]
@ -746,7 +754,7 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
dependencies = [ dependencies = [
"hermit-abi", "hermit-abi 0.2.6",
"libc", "libc",
] ]
@ -1131,7 +1139,7 @@ dependencies = [
"serde", "serde",
"serde-value", "serde-value",
"serde_json", "serde_json",
"time 0.3.20", "time",
"tokio", "tokio",
"tracing", "tracing",
"typemap_rev", "typemap_rev",
@ -1254,17 +1262,6 @@ dependencies = [
"once_cell", "once_cell",
] ]
[[package]]
name = "time"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi",
]
[[package]] [[package]]
name = "time" name = "time"
version = "0.3.20" version = "0.3.20"
@ -1403,23 +1400,6 @@ dependencies = [
"valuable", "valuable",
] ]
[[package]]
name = "tracing-forest"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "119324027fc01804d9f83aefb7d80fda2e8fbe7c28e0acc59187cbd751a12915"
dependencies = [
"ansi_term",
"chrono",
"serde",
"smallvec",
"thiserror",
"tokio",
"tracing",
"tracing-subscriber",
"uuid",
]
[[package]] [[package]]
name = "tracing-log" name = "tracing-log"
version = "0.1.3" version = "0.1.3"
@ -1438,15 +1418,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70" checksum = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70"
dependencies = [ dependencies = [
"matchers", "matchers",
"nu-ansi-term",
"once_cell", "once_cell",
"regex", "regex",
"sharded-slab", "sharded-slab",
"smallvec",
"thread_local", "thread_local",
"tracing", "tracing",
"tracing-core", "tracing-core",
]
[[package]]
name = "tracing-tree"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "758e983ab7c54fee18403994507e7f212b9005e957ce7984996fac8d11facedb"
dependencies = [
"atty",
"nu-ansi-term",
"tracing-core",
"tracing-log", "tracing-log",
"tracing-subscriber",
] ]
[[package]] [[package]]
@ -1548,16 +1538,6 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1674845326ee10d37ca60470760d4288a6f80f304007d92e5c53bab78c9cfd79"
dependencies = [
"getrandom",
"serde",
]
[[package]] [[package]]
name = "valuable" name = "valuable"
version = "0.1.0" version = "0.1.0"
@ -1580,12 +1560,6 @@ dependencies = [
"try-lock", "try-lock",
] ]
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.11.0+wasi-snapshot-preview1" version = "0.11.0+wasi-snapshot-preview1"

View File

@ -13,5 +13,5 @@ ron = "0.8.0"
serde = { version = "1.0.152", features = ["derive"] } serde = { version = "1.0.152", features = ["derive"] }
tokio = { version = "1.25.0", features = ["full"] } tokio = { version = "1.25.0", features = ["full"] }
tracing = "0.1.37" tracing = "0.1.37"
tracing-forest = { version = "0.1.5", features = ["full"] } tracing-subscriber = { version = "0.3.16", default-features = false, features = ["std", "env-filter", "registry"] }
tracing-subscriber = "0.3.16" tracing-tree = "0.2.2"

View File

@ -1,16 +1,14 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::path::Path; use std::path::{Path, PathBuf};
use anyhow::{Error, Result}; use anyhow::{Error, Result};
use poise::serenity_prelude as serenity; use poise::serenity_prelude as serenity;
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::fs::{File, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::Mutex; use tokio::sync::Mutex;
/// a brain stores data for a single guild /// a brain stores data for a single guild
#[derive(Debug, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Brain { pub struct Brain {
facts: HashMap<String, String>, facts: HashMap<String, String>,
} }
@ -18,21 +16,14 @@ pub struct Brain {
/// top level data /// top level data
#[derive(Debug)] #[derive(Debug)]
pub struct Data { pub struct Data {
file: Mutex<File>, path: PathBuf,
brain: Mutex<HashMap<serenity::GuildId, Brain>>, brain: Mutex<HashMap<serenity::GuildId, Brain>>,
} }
impl Data { impl Data {
#[tracing::instrument(fields(path = %path.as_ref().display()))] #[tracing::instrument(fields(path = %path.as_ref().display()))]
pub async fn from_path(path: impl AsRef<Path>) -> Result<Data> { pub async fn from_path(path: impl AsRef<Path>) -> Result<Data> {
let mut file = OpenOptions::new() let contents = tokio::fs::read_to_string(&path).await?;
.read(true)
.write(true)
.create(true)
.open(&path)
.await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
tracing::debug!("loaded brain contents: {contents}"); tracing::debug!("loaded brain contents: {contents}");
let brain = if contents.is_empty() { let brain = if contents.is_empty() {
tracing::info!("initializing brain at {}", path.as_ref().display()); tracing::info!("initializing brain at {}", path.as_ref().display());
@ -42,8 +33,8 @@ impl Data {
tracing::info!("loaded brain from {}", path.as_ref().display()); tracing::info!("loaded brain from {}", path.as_ref().display());
Mutex::new(brain) Mutex::new(brain)
}; };
let file = Mutex::new(file); let path = path.as_ref().to_path_buf();
Ok(Data { file, brain }) Ok(Data { path, brain })
} }
#[tracing::instrument] #[tracing::instrument]
@ -56,9 +47,11 @@ impl Data {
&mut contents, &mut contents,
Some(Default::default()), Some(Default::default()),
)?)?; )?)?;
let mut file = self.file.lock().await; tracing::debug!(
file.set_len(0).await?; "committing brain contents: {}",
file.write_all(&contents).await?; String::from_utf8_lossy(&contents)
);
tokio::fs::write(&self.path, &contents).await?;
tracing::info!("committed brain to disk"); tracing::info!("committed brain to disk");
Ok(()) Ok(())
} }

View File

@ -2,8 +2,10 @@ mod commands;
use anyhow::{Error, Result}; use anyhow::{Error, Result};
use poise::serenity_prelude as serenity; use poise::serenity_prelude as serenity;
use tracing_forest::{util::EnvFilter, ForestLayer}; use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Registry}; use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Registry};
use tracing_tree::HierarchicalLayer;
const DISCORD_TOKEN: &str = "DISCORD_TOKEN"; const DISCORD_TOKEN: &str = "DISCORD_TOKEN";
const BUSCEMI_DATA: &str = "BUSCEMI_DATA"; const BUSCEMI_DATA: &str = "BUSCEMI_DATA";
@ -21,7 +23,7 @@ async fn main() -> Result<()> {
fn init_tracing() { fn init_tracing() {
Registry::default() Registry::default()
.with(EnvFilter::from_default_env()) .with(EnvFilter::from_default_env())
.with(ForestLayer::default()) .with(HierarchicalLayer::default())
.init() .init()
} }
@ -60,11 +62,16 @@ fn init_discord() -> poise::FrameworkBuilder<commands::Data, Error> {
.setup(|ctx, ready, framework| { .setup(|ctx, ready, framework| {
Box::pin(async move { Box::pin(async move {
for guild in &ready.guilds { for guild in &ready.guilds {
poise::builtins::register_in_guild(ctx, &framework.options().commands, guild.id) poise::builtins::register_in_guild(
.await ctx,
.unwrap_or_else(|e| tracing::error!("failed to register commands: {e}")) &framework.options().commands,
guild.id,
)
.await
.unwrap_or_else(|e| tracing::error!("failed to register commands: {e}"));
tracing::debug!("registered commands on {guild:?}")
} }
tracing::debug!("registered commands"); tracing::info!("registered commands");
let data_path = let data_path =
std::env::var(BUSCEMI_DATA).unwrap_or_else(|_| String::from(BUSCEMI_DATA_PATH)); std::env::var(BUSCEMI_DATA).unwrap_or_else(|_| String::from(BUSCEMI_DATA_PATH));
commands::Data::from_path(data_path).await commands::Data::from_path(data_path).await