From 766fd8ea7da3d342635b15be806d3cd59cfc94fc Mon Sep 17 00:00:00 2001 From: Natty Date: Tue, 12 Nov 2024 22:20:57 +0100 Subject: [PATCH] Added a service for generating IDs --- Cargo.toml | 3 +++ src/service/gen_id.rs | 29 +++++++++++++++++++++++++++++ src/service/mod.rs | 12 +++++++++++- 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/service/gen_id.rs diff --git a/Cargo.toml b/Cargo.toml index 6e0b46b..e14158d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,6 +79,7 @@ tower-http = "0.5" tracing = "0.1" tracing-subscriber = "0.3" ts-rs = "7" +ulid = "1" unicode-segmentation = "1.10" url = "2.3" walkdir = "2.3" @@ -108,6 +109,7 @@ tokio = { workspace = true, features = ["full"] } tokio-stream = { workspace = true } tower = { workspace = true } tower-http = { workspace = true, features = ["cors", "trace", "fs"] } +ulid = { workspace = true } url = { workspace = true } idna = { workspace = true } @@ -118,6 +120,7 @@ tracing = { workspace = true } cfg-if = { workspace = true } +bytes = { workspace = true } compact_str = { workspace = true } either = { workspace = true } futures = { workspace = true } diff --git a/src/service/gen_id.rs b/src/service/gen_id.rs new file mode 100644 index 0000000..e7620a8 --- /dev/null +++ b/src/service/gen_id.rs @@ -0,0 +1,29 @@ +use std::{sync::Arc, time::SystemTime}; + +use super::MagnetarService; + +pub struct GenIdService; + +impl GenIdService { + pub fn new_id(&self) -> ulid::Ulid { + ulid::Ulid::new() + } + + pub fn new_id_str(&self) -> String { + self.new_id().to_string() + } + + pub fn new_for_time(&self, time: impl Into) -> ulid::Ulid { + ulid::Ulid::from_datetime(time.into()) + } + + pub fn new_str_for_time(&self, time: impl Into) -> String { + self.new_for_time(time).to_string() + } +} + +impl AsRef for Arc { + fn as_ref(&self) -> &GenIdService { + &self.gen_id + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 0ff5683..11036c9 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,3 +1,4 @@ +use gen_id::GenIdService; use magnetar_common::config::MagnetarConfig; use magnetar_model::{ck, CalckeyCache, CalckeyModel}; use std::fmt::{Debug, Formatter}; @@ -5,15 +6,16 @@ use std::time::Duration; use thiserror::Error; pub mod emoji_cache; +pub mod gen_id; pub mod generic_id_cache; pub mod instance_cache; pub mod instance_meta_cache; pub mod local_user_cache; #[non_exhaustive] - pub struct MagnetarService { pub db: CalckeyModel, + pub gen_id: GenIdService, pub cache: CalckeyCache, pub config: &'static MagnetarConfig, pub local_user_cache: local_user_cache::LocalUserCacheService, @@ -67,6 +69,14 @@ impl MagnetarService { remote_instance_cache, emoji_cache, drive_file_cache, + gen_id: GenIdService, }) } + + pub fn service(&self) -> &T + where + Self: AsRef, + { + self.as_ref() + } }