@terreno/syncdb 58.0.0-beta.1 → 58.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ import {DateTime} from "luxon";
2
+
3
+ import {generateMutationId} from "./outbox";
4
+
5
+ /**
6
+ * How the client mints ids for a collection's creates. `uuid` (the default) suits a String
7
+ * `_id`. `objectId` mints 24-hex ObjectIds for a collection whose Mongoose model keeps the
8
+ * default ObjectId `_id`, so an existing model can sync without migrating its ids.
9
+ */
10
+ export type SyncIdFormat = "uuid" | "objectId";
11
+
12
+ const OBJECT_ID_HEX = /^[0-9a-fA-F]{24}$/;
13
+
14
+ /** True for a 24-character hex string, the only id an ObjectId-keyed collection accepts. */
15
+ export const isObjectIdHex = (id: string): boolean => OBJECT_ID_HEX.test(id);
16
+
17
+ const randomBytes = (length: number, random: () => number): Uint8Array => {
18
+ const bytes = new Uint8Array(length);
19
+ if (typeof globalThis.crypto?.getRandomValues === "function") {
20
+ return globalThis.crypto.getRandomValues(bytes);
21
+ }
22
+ for (let index = 0; index < length; index += 1) {
23
+ bytes[index] = Math.floor(random() * 256);
24
+ }
25
+ return bytes;
26
+ };
27
+
28
+ /**
29
+ * Mint an ObjectId hex string: 4 bytes of Unix seconds, then 8 random bytes. MongoDB's own
30
+ * layout uses 5 random bytes plus a 3-byte counter; a client has no shared counter, so the
31
+ * counter's bytes are random too. That leaves 64 random bits per second, so two clients
32
+ * colliding is not a practical concern, and the server's unique `_id` index rejects one if
33
+ * it ever happens (`id_collision` nack). The timestamp comes from the device clock: sort and
34
+ * display by `created`, never by the id.
35
+ */
36
+ export const generateObjectId = ({
37
+ nowSeconds = Math.floor(DateTime.now().toSeconds()),
38
+ random = Math.random,
39
+ }: {
40
+ nowSeconds?: number;
41
+ random?: () => number;
42
+ } = {}): string => {
43
+ const timestamp = (nowSeconds >>> 0).toString(16).padStart(8, "0");
44
+ const tail = Array.from(randomBytes(8, random), (byte) => byte.toString(16).padStart(2, "0"));
45
+ return `${timestamp}${tail.join("")}`;
46
+ };
47
+
48
+ /** Mint a create's entity id in the collection's configured format. */
49
+ export const generateEntityId = (format: SyncIdFormat | undefined): string =>
50
+ format === "objectId" ? generateObjectId() : generateMutationId();
@@ -701,8 +701,9 @@ export const createReplayCoordinator = ({
701
701
  return {authPaused: false, haltDrain: haltQueueOnConflict, progressed: false};
702
702
  };
703
703
 
704
- const applyValidation = (mutation: OutboxMutation): OutcomeDecision => {
705
- handleTerminalFailure(mutation, "validation");
704
+ const applyValidation = (mutation: OutboxMutation, nack: SyncNack): OutcomeDecision => {
705
+ // An id-caused rejection (`id_collision`, `invalid_id`) names itself in the debug log.
706
+ handleTerminalFailure(mutation, nack.reason ?? "validation");
706
707
  // B4: the entity's queued successors are skipped-and-surfaced until the
707
708
  // user calls retryFailed({entityId}) or resolves the underlying issue —
708
709
  // other entities keep draining.
@@ -818,7 +819,7 @@ export const createReplayCoordinator = ({
818
819
  return applyUnauthorized(mutation);
819
820
  }
820
821
  if (nack.code === "validation") {
821
- return applyValidation(mutation);
822
+ return applyValidation(mutation, nack);
822
823
  }
823
824
  if (nack.code === "rate_limited") {
824
825
  return applyRateLimited(mutation, nack);
package/src/types.ts CHANGED
@@ -89,6 +89,13 @@ export interface SyncAck {
89
89
 
90
90
  export type SyncNackCode = "conflict" | "unauthorized" | "validation" | "error" | "rate_limited";
91
91
 
92
+ /**
93
+ * Why a `validation` nack rejected a mutation, when the cause is the entity id itself.
94
+ * `id_collision`: a create named an `_id` that already exists. `invalid_id`: the id is not a
95
+ * 24-character hex ObjectId for an ObjectId-keyed collection.
96
+ */
97
+ export type SyncNackReason = "id_collision" | "invalid_id";
98
+
92
99
  /** Rejected mutation. Conflict nacks carry the canonical server document. */
93
100
  export interface SyncNack {
94
101
  mutationId: string;
@@ -106,6 +113,8 @@ export interface SyncNack {
106
113
  */
107
114
  serverDeleted?: boolean;
108
115
  message?: string;
116
+ /** Set on `validation` nacks caused by the entity id (see {@link SyncNackReason}). */
117
+ reason?: SyncNackReason;
109
118
  /**
110
119
  * Minimum time (ms) the client should wait before retrying, filled by the
111
120
  * server with the remaining rate-limit window (`rate_limited` nacks only).