refactor (backend-rs): separate gen_id and gen_id_at

This commit is contained in:
naskya 2024-04-24 07:02:06 +09:00
parent a2958f6da8
commit 9db729d734
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
7 changed files with 22 additions and 22 deletions

1
Cargo.lock generated
View file

@ -150,7 +150,6 @@ dependencies = [
"argon2",
"basen",
"bcrypt",
"cfg-if",
"chrono",
"cuid2",
"emojis",

View file

@ -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"

View file

@ -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 }

View file

@ -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

View file

@ -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

View file

@ -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<DateTime<Utc>>) -> 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<Utc>) -> String {
create_id(&date.naive_utc()).unwrap()
}
#[cfg(test)]

View file

@ -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,