Skip to content

Commit c70ff8e

Browse files
committed
feat(core): add ULID identifiers and the org/location/register/device model
Phase 1 foundations for multi-device, offline and eventual synchronisation. All three migrations are strictly additive — no existing table, column or row is modified, so no current hospitality workflow is affected. ## main/core/ids.ts — collision-safe identifiers orders/order_items/bills use INTEGER PRIMARY KEY AUTOINCREMENT. Two tills trading offline both allocate from 1, and when they converge two different sales claim one identity — nothing downstream can tell them apart. ULID over UUIDv4 because both are collision-safe without coordination, but ULID also sorts lexicographically by time: SQLite indexes stay dense instead of scattering inserts, "recent sales" and future sync cursors become range scans on the key itself, and logs are readable. Implemented in-repo rather than adding a dependency — the spec is short and stable, it is financial identity code a commercial product should own, and it keeps the licence-clean dependency tree we just achieved. Randomness is crypto.randomBytes, never Math.random. ## Migration v68 — Organization > Location > Register > Device A till's local database holds exactly ONE organization, location and register: single-tenant by construction, because a shop-floor machine must be physically incapable of holding another merchant's data. Multi-tenancy proper (many organizations in one database) is a CLOUD concern and is not modelled here. Seeded from existing settings, with settings pointers so "which register am I" is one cheap read. ## Migration v69 — uid columns, not a primary-key conversion Converting the primary keys outright would break every foreign key, join, report and the KDS WebSocket contract in a single commit. Instead each row gains a ULID `uid` beside its existing key: current code is untouched, new distributed code keys on uid. The backfill seeds each ULID's timestamp from the row's own created_at, so generated ids sort in true historical order rather than clustering at migration time. The unique index is PARTIAL (WHERE uid IS NOT NULL) on purpose: unique because a duplicate would silently merge two distinct sales during a future sync, partial so insert paths not yet taught to populate uid keep working. ## Migration v70 — audit_events One narrow append-only table, not an audit framework: who did what, when, where. The inherited codebase only has fragments (tax_config_audit, print_logs, payment_transaction_ref_conflicts) with no common shape, and a commercial EPOS must be able to answer "who authorised this refund". ## Verification New: tests/plemmo-identifiers.test.ts (55 checks) — format, 100k-ID uniqueness, two independent offline generators producing zero collisions, monotonic ordering, a backwards clock step still yielding increasing ids, the seeded hierarchy with a clean foreign_key_check, and the partial unique index actually rejecting a duplicate while still allowing NULLs. Extended tests/upgrade-path.test.ts to assert the backfill against the REAL v1.5.0-era fixture database — every legacy row gets a distinct well-formed ULID that sorts in created_at order — which is where a backfill normally breaks. schema-health still reports zero drift between a migrated old install and a fresh one, so both paths converge on an identical schema. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011HjBK8R8ArAjzGRLS7gjUj
1 parent fe54969 commit c70ff8e

5 files changed

Lines changed: 609 additions & 1 deletion

File tree

‎main/core/ids.ts‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
/**
2+
* Plemmo Core — collision-safe distributed identifiers (ULID).
3+
*
4+
* ## The problem this solves
5+
*
6+
* FloCafe gives `orders`, `order_items` and `bills` an
7+
* `INTEGER PRIMARY KEY AUTOINCREMENT`. That is fine for one till and fatal for
8+
* several: two tills trading offline both mint order id 41, and when they
9+
* later converge those two different sales claim the same identity. Nothing
10+
* downstream can tell them apart — not the sync engine, not a report, not a
11+
* refund looking up its original sale.
12+
*
13+
* ## Why ULID rather than UUIDv4
14+
*
15+
* Both are collision-safe without coordination, which is the hard requirement.
16+
* ULID additionally sorts lexicographically by creation time, which matters
17+
* here for three practical reasons:
18+
*
19+
* - SQLite indexes on a time-ordered TEXT key stay dense instead of
20+
* scattering inserts across the B-tree, which is the difference between a
21+
* till staying quick and slowly degrading over a year of trading.
22+
* - "Most recent sales" and sync cursors become ordinary range scans on the
23+
* primary key, with no secondary index on a timestamp.
24+
* - Reading a log, an ID that sorts by time is far easier to reason about
25+
* than a random one.
26+
*
27+
* The `uuid` package is already a dependency and stays where it is used. This
28+
* module is implemented in-repo rather than adding a `ulid` dependency: the
29+
* spec is short and stable, this is financial-identity code that a commercial
30+
* product should own outright, and it avoids another supply-chain edge in a
31+
* codebase we are deliberately keeping licence-clean.
32+
*
33+
* ## Format (per the ULID spec)
34+
*
35+
* 26 characters, Crockford Base32, no padding
36+
* ┌───────────────┬──────────────────────┐
37+
* │ 10 chars │ 16 chars │
38+
* │ 48-bit ms │ 80 bits randomness │
39+
* └───────────────┴──────────────────────┘
40+
*
41+
* Randomness comes from `crypto.randomBytes`, never `Math.random` — this is
42+
* an identifier for financial records.
43+
*
44+
* ## Monotonicity
45+
*
46+
* Within a single millisecond the random component is incremented rather than
47+
* re-drawn, so IDs minted in a tight loop (an order and its twenty lines) stay
48+
* strictly increasing and therefore stay in insertion order. This is the
49+
* behaviour the spec calls "monotonic".
50+
*
51+
* ## Status in Phase 1
52+
*
53+
* This module is the foundation only. Existing integer primary keys are NOT
54+
* being converted yet — that is a wide, breaking change across every join,
55+
* report and the KDS protocol. Phase 1 instead attaches a ULID `uid` column
56+
* alongside the existing keys so every sale, line and bill already carries a
57+
* globally unique identity that a future sync engine can key on. See
58+
* docs/PLEMMO_ARCHITECTURE.md § Identifiers for the staged plan.
59+
*/
60+
61+
import * as crypto from 'crypto';
62+
63+
/** Crockford Base32: excludes I, L, O and U to avoid transcription errors. */
64+
const ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
65+
const ENCODING_LEN = 32;
66+
const TIME_LEN = 10;
67+
const RANDOM_LEN = 16;
68+
export const ULID_LENGTH = TIME_LEN + RANDOM_LEN;
69+
70+
/** Largest timestamp a 48-bit millisecond field can hold (year 10889). */
71+
const MAX_TIME = 281474976710655;
72+
73+
const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/;
74+
75+
let lastTime = -1;
76+
let lastRandom: number[] = [];
77+
78+
function encodeTime(now: number): string {
79+
if (!Number.isInteger(now) || now < 0 || now > MAX_TIME) {
80+
throw new RangeError(`Timestamp out of ULID range: ${now}`);
81+
}
82+
let out = '';
83+
let remaining = now;
84+
for (let i = TIME_LEN - 1; i >= 0; i--) {
85+
const mod = remaining % ENCODING_LEN;
86+
out = ENCODING[mod] + out;
87+
remaining = (remaining - mod) / ENCODING_LEN;
88+
}
89+
return out;
90+
}
91+
92+
/** 16 Crockford symbols = 80 bits, drawn from the CSPRNG. */
93+
function drawRandom(): number[] {
94+
const bytes = crypto.randomBytes(RANDOM_LEN);
95+
const out = new Array<number>(RANDOM_LEN);
96+
for (let i = 0; i < RANDOM_LEN; i++) {
97+
// Take the low 5 bits of each byte. Uniform over 0..31 because 32 divides
98+
// 256 exactly, so there is no modulo bias to correct for.
99+
out[i] = bytes[i] & 0x1f;
100+
}
101+
return out;
102+
}
103+
104+
/**
105+
* Increment the random component by one, with carry, for monotonic IDs inside
106+
* the same millisecond. Overflowing all 80 bits is not reachable in practice
107+
* (it needs 2^80 IDs in one millisecond) but is handled rather than silently
108+
* wrapping to a smaller value, which would break ordering.
109+
*/
110+
function incrementRandom(values: number[]): number[] {
111+
const out = values.slice();
112+
for (let i = RANDOM_LEN - 1; i >= 0; i--) {
113+
if (out[i] < ENCODING_LEN - 1) {
114+
out[i]++;
115+
return out;
116+
}
117+
out[i] = 0;
118+
}
119+
throw new Error('ULID random component overflowed within a single millisecond');
120+
}
121+
122+
/**
123+
* Generate a ULID.
124+
*
125+
* @param seedTime Optional millisecond timestamp, for tests and for stamping a
126+
* record with a known time. Omit in production code.
127+
*/
128+
export function ulid(seedTime?: number): string {
129+
const now = seedTime === undefined ? Date.now() : seedTime;
130+
if (!Number.isInteger(now)) throw new TypeError(`ULID seed time must be an integer, got ${now}`);
131+
132+
if (now === lastTime) {
133+
lastRandom = incrementRandom(lastRandom);
134+
} else {
135+
// A clock that steps backwards (NTP correction, a manual change on a till)
136+
// must not produce IDs that collide with ones already issued. Holding the
137+
// last timestamp and continuing to increment keeps them unique and ordered
138+
// until the wall clock catches up.
139+
if (now < lastTime) {
140+
lastRandom = incrementRandom(lastRandom);
141+
} else {
142+
lastTime = now;
143+
lastRandom = drawRandom();
144+
}
145+
}
146+
147+
const timePart = encodeTime(now > lastTime ? now : lastTime);
148+
let randomPart = '';
149+
for (let i = 0; i < RANDOM_LEN; i++) randomPart += ENCODING[lastRandom[i]];
150+
return timePart + randomPart;
151+
}
152+
153+
/** True when `value` is a syntactically valid 26-character Crockford ULID. */
154+
export function isUlid(value: unknown): value is string {
155+
return typeof value === 'string' && ULID_PATTERN.test(value);
156+
}
157+
158+
/** Extract the creation timestamp (ms since epoch) encoded in a ULID. */
159+
export function ulidTime(value: string): number {
160+
if (!isUlid(value)) throw new TypeError(`Not a valid ULID: ${JSON.stringify(value)}`);
161+
let time = 0;
162+
for (let i = 0; i < TIME_LEN; i++) {
163+
const index = ENCODING.indexOf(value[i]);
164+
if (index === -1) throw new TypeError(`Invalid ULID character: ${value[i]}`);
165+
time = time * ENCODING_LEN + index;
166+
}
167+
return time;
168+
}
169+
170+
/**
171+
* Reset the monotonic state. Tests only — production code must never call
172+
* this, because it removes the guarantee that two IDs minted in the same
173+
* millisecond are ordered.
174+
*/
175+
export function __resetUlidStateForTests(): void {
176+
lastTime = -1;
177+
lastRandom = [];
178+
}

0 commit comments

Comments
 (0)