Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better aid #2470

Draft
wants to merge 3 commits into
base: mei-v11
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/misc/id/aidd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// AIDD
// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの] + 長さ1の個体ID + 長さ1のカウンタ
// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの]の下1文字を削ったもの + 長さ2の個体ID + 長さ1のカウンタ
const TIME_OFFSET = 946684800000;

let nodeId: string;

let counter = 0;

const borrow = 1; // TODO: 変更可能にする
const nodeIdLength = 1 + borrow;

function getNodeId() {
if (!nodeId) {
const nodeCounter = Math.floor(Math.random() * 1234567) // TODO: Redisとかで採番
nodeId = nodeCounter.toString(36).padStart(nodeIdLength, '0').slice(-nodeIdLength);
}
return nodeId;
}

function getTime(time: number) {
time = time - TIME_OFFSET;
if (time < 0) time = 0;

return time.toString(36).padStart(8, '0').slice(-8, (borrow ? -borrow : undefined));
}

function getNoise() {
return counter.toString(36).padStart(1, '0').slice(-1);
}

export function genAidd(date: Date): string {
const t = date.getTime();
if (isNaN(t)) throw 'Failed to create AIDD: Invalid Date';

counter++;
return getTime(date.getTime()) + getNodeId() + getNoise();
}
30 changes: 30 additions & 0 deletions src/misc/id/aidx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// AIDX
// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの] + 長さ4の個体ID + 長さ4のカウンタ
import { customAlphabet } from 'nanoid'

const TIME_OFFSET = 946684800000;
const TIME_LENGTH = 8;
const NODE_LENGTH = 4;
const NOISE_LENGTH = 4;

const nodeId = customAlphabet('0123456789abcdefghjkmnpqrstvwxyz', NODE_LENGTH)();
let counter = 0;

function getTime(time: number) {
time = time - TIME_OFFSET;
if (time < 0) time = 0;

return time.toString(36).padStart(TIME_LENGTH, '0').slice(-TIME_LENGTH);
}

function getNoise() {
return counter.toString(36).padStart(NOISE_LENGTH, '0').slice(-NOISE_LENGTH);
}

export function genAidx(date: Date): string {
const t = date.getTime();
if (isNaN(t)) throw 'Failed to create AIDX: Invalid Date';

counter++;
return getTime(date.getTime()) + nodeId + getNoise();
}