From 9db729d7344fb7fe4df21343f353a510ac14f37f Mon Sep 17 00:00:00 2001 From: naskya Date: Wed, 24 Apr 2024 07:02:06 +0900 Subject: [PATCH] refactor (backend-rs): separate gen_id and gen_id_at --- Cargo.lock | 1 - Cargo.toml | 1 - packages/backend-rs/Cargo.toml | 1 - packages/backend-rs/index.d.ts | 4 ++- packages/backend-rs/index.js | 3 +- packages/backend-rs/src/util/id.rs | 31 ++++++++++---------- packages/backend/src/services/note/create.ts | 3 +- 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 07e2738cd4..2959ad5bf6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -150,7 +150,6 @@ dependencies = [ "argon2", "basen", "bcrypt", - "cfg-if", "chrono", "cuid2", "emojis", diff --git a/Cargo.toml b/Cargo.toml index a5dbad8687..42de97a220 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,6 @@ napi-build = "2.1.3" argon2 = "0.5.3" basen = "0.1.0" bcrypt = "0.15.1" -cfg-if = "1.0.0" chrono = "0.4.37" convert_case = "0.6.0" cuid2 = "0.1.2" diff --git a/packages/backend-rs/Cargo.toml b/packages/backend-rs/Cargo.toml index 865e263fed..3a222cd4a5 100644 --- a/packages/backend-rs/Cargo.toml +++ b/packages/backend-rs/Cargo.toml @@ -20,7 +20,6 @@ napi-derive = { workspace = true, optional = true } argon2 = { workspace = true, features = ["std"] } basen = { workspace = true } bcrypt = { workspace = true } -cfg-if = { workspace = true } chrono = { workspace = true } cuid2 = { workspace = true } emojis = { workspace = true } diff --git a/packages/backend-rs/index.d.ts b/packages/backend-rs/index.d.ts index 8d61f9ccd9..016932a092 100644 --- a/packages/backend-rs/index.d.ts +++ b/packages/backend-rs/index.d.ts @@ -1140,5 +1140,7 @@ export function getTimestamp(id: string): number * * Ref: https://github.com/paralleldrive/cuid2#parameterized-length */ -export function genId(date?: Date | undefined | null): string +export function genId(): string +/** Generate an ID using a specific datetime */ +export function genIdAt(date: Date): string export function secureRndstr(length?: number | undefined | null): string diff --git a/packages/backend-rs/index.js b/packages/backend-rs/index.js index d4ae11b676..9e15fa3658 100644 --- a/packages/backend-rs/index.js +++ b/packages/backend-rs/index.js @@ -310,7 +310,7 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { loadEnv, loadConfig, stringToAcct, acctToString, addNoteToAntenna, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getNoteSummary, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, ChatEvent, publishToChatStream, initIdGenerator, getTimestamp, genId, secureRndstr } = nativeBinding +const { loadEnv, loadConfig, stringToAcct, acctToString, addNoteToAntenna, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getNoteSummary, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, ChatEvent, publishToChatStream, initIdGenerator, getTimestamp, genId, genIdAt, secureRndstr } = nativeBinding module.exports.loadEnv = loadEnv module.exports.loadConfig = loadConfig @@ -359,4 +359,5 @@ module.exports.publishToChatStream = publishToChatStream module.exports.initIdGenerator = initIdGenerator module.exports.getTimestamp = getTimestamp module.exports.genId = genId +module.exports.genIdAt = genIdAt module.exports.secureRndstr = secureRndstr diff --git a/packages/backend-rs/src/util/id.rs b/packages/backend-rs/src/util/id.rs index 20b2f2b74c..515c020ece 100644 --- a/packages/backend-rs/src/util/id.rs +++ b/packages/backend-rs/src/util/id.rs @@ -1,8 +1,7 @@ //! ID generation utility based on [cuid2] use basen::BASE36; -use cfg_if::cfg_if; -use chrono::NaiveDateTime; +use chrono::{DateTime, NaiveDateTime, Utc}; use once_cell::sync::OnceCell; use std::cmp; @@ -53,21 +52,21 @@ pub fn get_timestamp(id: &str) -> i64 { } } -cfg_if! { - if #[cfg(feature = "napi")] { - use chrono::{DateTime, Utc}; +/// The generated ID results in the form of `[8 chars timestamp] + [cuid2]`. +/// The minimum and maximum lengths are 16 and 24, respectively. +/// With the length of 16, namely 8 for cuid2, roughly 1427399 IDs are needed +/// in the same millisecond to reach 50% chance of collision. +/// +/// Ref: https://github.com/paralleldrive/cuid2#parameterized-length +#[crate::export] +pub fn gen_id() -> String { + create_id(&Utc::now().naive_utc()).unwrap() +} - /// The generated ID results in the form of `[8 chars timestamp] + [cuid2]`. - /// The minimum and maximum lengths are 16 and 24, respectively. - /// With the length of 16, namely 8 for cuid2, roughly 1427399 IDs are needed - /// in the same millisecond to reach 50% chance of collision. - /// - /// Ref: https://github.com/paralleldrive/cuid2#parameterized-length - #[napi_derive::napi] - pub fn gen_id(date: Option>) -> String { - create_id(&date.unwrap_or_else(Utc::now).naive_utc()).unwrap() - } - } +/// Generate an ID using a specific datetime +#[crate::export] +pub fn gen_id_at(date: DateTime) -> String { + create_id(&date.naive_utc()).unwrap() } #[cfg(test)] diff --git a/packages/backend/src/services/note/create.ts b/packages/backend/src/services/note/create.ts index 2135847a17..679a2f886e 100644 --- a/packages/backend/src/services/note/create.ts +++ b/packages/backend/src/services/note/create.ts @@ -47,6 +47,7 @@ import { addNoteToAntenna, checkWordMute, genId, + genIdAt, isSilencedServer, } from "backend-rs"; import { countSameRenotes } from "@/misc/count-same-renotes.js"; @@ -711,7 +712,7 @@ async function insertNote( data.createdAt = new Date(); } const insert = new Note({ - id: genId(data.createdAt), + id: genIdAt(data.createdAt), createdAt: data.createdAt, fileIds: data.files ? data.files.map((file) => file.id) : [], replyId: data.reply ? data.reply.id : null,