@tearleads/client-sdk 0.1.238 → 0.1.240

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.
Files changed (31) hide show
  1. package/data/documents/shared/types.d.ts +5 -1
  2. package/data/documents/shared/types.js.map +1 -1
  3. package/data/persistence/documents/documentAttachmentPresence.js +44 -0
  4. package/data/persistence/documents/documentAttachmentPresence.js.map +1 -0
  5. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +0 -2
  6. package/data/persistence/documents/records/documentSyncFailurePersistence.js +0 -2
  7. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  8. package/data/sqlite/migrations/localSchemaMigrations.js +14 -0
  9. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  10. package/data/sqlite/schema/documentRecordSchema.js +4 -6
  11. package/data/sqlite/schema/documentRecordSchema.js.map +1 -1
  12. package/data/sqlite/schema/index.d.ts +0 -17
  13. package/internal/validators/operation/containerMutations.d.ts +16 -16
  14. package/internal/validators/operation/documentMutations.d.ts +20 -20
  15. package/internal/validators/response/containerMutationError.d.ts +2 -2
  16. package/internal/validators/response/documentMutationError.d.ts +3 -2
  17. package/internal/validators/response/documentMutationError.js +5 -0
  18. package/internal/validators/response/documentMutationError.js.map +1 -1
  19. package/package.json +1 -1
  20. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +0 -1
  21. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  22. package/stores/documents/documentStore/sync/syncShared.js +0 -1
  23. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  24. package/workflows/documents/linkSet/linkSetBlobRewraps.d.ts +10 -4
  25. package/workflows/documents/linkSet/linkSetBlobRewraps.js +23 -11
  26. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -1
  27. package/workflows/documents/linkSet/linkSetLegMachine.js +74 -0
  28. package/workflows/documents/linkSet/linkSetLegMachine.js.map +1 -0
  29. package/workflows/documents/linkSet/linkSetRemote.d.ts +4 -4
  30. package/workflows/documents/linkSet/linkSetRemote.js +96 -52
  31. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
@@ -0,0 +1,74 @@
1
+ import { DOCUMENT_MUTATION_ERROR_CODES } from "../../../internal/validators/response/index.js";
2
+ export const INITIAL_LINK_SET_LEG_STATE = {
3
+ status: "speculative",
4
+ };
5
+ export function startLinkSetLegAttempt(state) {
6
+ return { listing: state.status, status: "unprepared" };
7
+ }
8
+ /**
9
+ * Record what an attempt signed, replacing an earlier preparation; a fresh
10
+ * attempt can only have listed.
11
+ */
12
+ export function recordLinkSetLegRewraps(attempt, prepared) {
13
+ if (attempt.listing === "speculative")
14
+ return { ...prepared, listing: "speculative", status: "prepared" };
15
+ if (prepared.source !== "listed")
16
+ throw new Error("A fresh link-set attempt must list its attachments");
17
+ return { ...prepared, listing: "fresh", status: "prepared" };
18
+ }
19
+ function attemptSource(attempt) {
20
+ return attempt.status === "prepared" ? attempt.source : null;
21
+ }
22
+ /** Whether a refusal of this attempt is held back until the leg decides. */
23
+ export function holdsLinkSetRefusals(attempt) {
24
+ return isSpeculativeRewrapSource(attemptSource(attempt));
25
+ }
26
+ /** The event an attempt's result raises. */
27
+ export function linkSetAttemptEvent(input) {
28
+ const rewraps = input.attempt.status === "prepared" ? input.attempt.rewraps : null;
29
+ return input.committed
30
+ ? { rewraps, type: "attemptCommitted" }
31
+ : {
32
+ heldFailures: input.heldFailures,
33
+ source: attemptSource(input.attempt),
34
+ stillCurrent: input.stillCurrent,
35
+ type: "attemptFailed",
36
+ };
37
+ }
38
+ function isSpeculativeRewrapSource(source) {
39
+ return source === "reused" || source === "skipped";
40
+ }
41
+ /**
42
+ * The server's binding check refused rewraps cited without listing: the coded
43
+ * attachment-set refusal (`lockDocumentLinkBlobRewraps`), or for re-cited
44
+ * envelopes the uncoded content-key epoch refusal the current server returns
45
+ * per cited blob (`rewrapDocumentBlobContentKeyInTransaction`). A skipped
46
+ * attempt cites no blob, so only the coded refusal can answer it.
47
+ */
48
+ function refusedSpeculativeRewraps(source, failure) {
49
+ if (failure.status !== 409 || !isSpeculativeRewrapSource(source))
50
+ return false;
51
+ if (failure.code === DOCUMENT_MUTATION_ERROR_CODES.linkAttachmentsChanged)
52
+ return true;
53
+ return source === "reused" && failure.code === undefined;
54
+ }
55
+ /**
56
+ * Only a speculative attempt the binding check refused retries, and only
57
+ * once: the fresh attempt lists, so it cannot be refused for the same stale
58
+ * view again. Any other refusal keeps its own recovery path.
59
+ */
60
+ export function transitionLinkSetLeg(state, event) {
61
+ if (state.status !== "speculative" && state.status !== "fresh")
62
+ return state;
63
+ if (event.type === "attemptCommitted")
64
+ return { rewraps: event.rewraps, status: "committed" };
65
+ // Nothing an ended operation held back is retried or reported.
66
+ if (!event.stillCurrent)
67
+ return { status: "abandoned" };
68
+ const retryable = state.status === "speculative" &&
69
+ event.heldFailures.some((failure) => refusedSpeculativeRewraps(event.source, failure));
70
+ return retryable
71
+ ? { status: "fresh" }
72
+ : { status: "failed", unreported: event.heldFailures };
73
+ }
74
+ //# sourceMappingURL=linkSetLegMachine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"linkSetLegMachine.js","sourceRoot":"","sources":["linkSetLegMachine.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AA2C/E,MAAM,CAAC,MAAM,0BAA0B,GAAoB;IACzD,MAAM,EAAE,aAAa;CACtB,CAAC;AAgCF,MAAM,UAAU,sBAAsB,CACpC,KAAoE;IAEpE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;AACzD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,OAA0B,EAC1B,QAAgC;IAEhC,IAAI,OAAO,CAAC,OAAO,KAAK,aAAa;QACnC,OAAO,EAAE,GAAG,QAAQ,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,UA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C9D,OAAO,KAAK,CAAC;IACf,IAAI,OAAO,CAAC,IAAI,KAAK,6BAA6B,CAAC,sBAAsB;QACvE,OAAO,IAAI,CAAC;IACd,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,CAAC;AAC3D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAClC,KAAsB,EACtB,KAAsB;IAEtB,IAAI,KAAK,CAAC,MAAM,KAAK,aAAa,IAAI,KAAK,CAAC,MAAM,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAC7E,IAAI,KAAK,CAAC,IAAI,KAAK,kBAAkB;QACnC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IACzD,+DAA+D;IAC/D,IAAI,CAAC,KAAK,CAAC,YAAY;QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IACxD,MAAM,SAAS,GACb,KAAK,CAAC,MAAM,KAAK,aAAa;QAC9B,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAClC,yBAAyB,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CACjD,CAAC;IACJ,OAAO,SAAS;QACd,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE;QACrB,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import type { DocumentLinkAccessEventBody } from \"@tearleads/crypto\";\nimport { DOCUMENT_MUTATION_ERROR_CODES } from \"@tearleads/validators/response\";\nimport type { DocumentLinkSetMutationFailure } from \"../../../data/documents/shared/types\";\n\ntype BlobRewraps = DocumentLinkAccessEventBody[\"blobRewraps\"];\n\n/**\n * Where an attempt's signed rewraps came from. `reused` re-cites the previous\n * leg's envelopes and `skipped` cites none because the local view holds no\n * attachment; neither listed, so the server's binding check may refuse them.\n */\nexport type LinkSetRewrapSource = \"listed\" | \"reused\" | \"skipped\";\n\n/** A submit refusal, with the deferred host report the API client withheld. */\nexport interface LinkSetSubmitFailure extends DocumentLinkSetMutationFailure {\n readonly report?: (() => void) | undefined;\n}\n\n/**\n * One link or unlink leg. The first attempt (`speculative`) may cite rewraps\n * without listing; a refusal of those starts one `fresh` attempt, which lists.\n * A leg ends `committed`, `failed` with the refusals still to report, or\n * `abandoned` when the operation stopped being current, dropping what it held.\n */\nexport type LinkSetLegState =\n | { readonly status: \"speculative\" }\n | { readonly status: \"fresh\" }\n | { readonly status: \"committed\"; readonly rewraps: BlobRewraps | null }\n | {\n readonly status: \"failed\";\n readonly unreported: readonly LinkSetSubmitFailure[];\n }\n | { readonly status: \"abandoned\" };\n\nexport type LinkSetLegEvent =\n | { readonly type: \"attemptCommitted\"; readonly rewraps: BlobRewraps | null }\n | {\n readonly type: \"attemptFailed\";\n /** Refusals of a speculative attempt, held back from the caller. */\n readonly heldFailures: readonly LinkSetSubmitFailure[];\n readonly source: LinkSetRewrapSource | null;\n readonly stillCurrent: boolean;\n };\n\nexport const INITIAL_LINK_SET_LEG_STATE: LinkSetLegState = {\n status: \"speculative\",\n};\n\n/**\n * One attempt of a leg: what it may cite before it prepares, then the source\n * and rewraps it signed. Only a speculative attempt can skip or reuse; a fresh\n * one always lists.\n */\nexport type LinkSetLegAttempt =\n | {\n readonly listing: \"speculative\" | \"fresh\";\n readonly status: \"unprepared\";\n }\n | {\n readonly listing: \"speculative\";\n readonly rewraps: BlobRewraps;\n readonly source: LinkSetRewrapSource;\n readonly status: \"prepared\";\n }\n | {\n readonly listing: \"fresh\";\n readonly rewraps: BlobRewraps;\n readonly source: \"listed\";\n readonly status: \"prepared\";\n };\n\nexport type PreparedLinkSetRewraps =\n | { readonly rewraps: BlobRewraps; readonly source: \"listed\" }\n | {\n readonly rewraps: BlobRewraps;\n readonly source: \"reused\" | \"skipped\";\n };\n\nexport function startLinkSetLegAttempt(\n state: Extract<LinkSetLegState, { status: \"speculative\" | \"fresh\" }>,\n): LinkSetLegAttempt {\n return { listing: state.status, status: \"unprepared\" };\n}\n\n/**\n * Record what an attempt signed, replacing an earlier preparation; a fresh\n * attempt can only have listed.\n */\nexport function recordLinkSetLegRewraps(\n attempt: LinkSetLegAttempt,\n prepared: PreparedLinkSetRewraps,\n): LinkSetLegAttempt {\n if (attempt.listing === \"speculative\")\n return { ...prepared, listing: \"speculative\", status: \"prepared\" };\n if (prepared.source !== \"listed\")\n throw new Error(\"A fresh link-set attempt must list its attachments\");\n return { ...prepared, listing: \"fresh\", status: \"prepared\" };\n}\n\nfunction attemptSource(attempt: LinkSetLegAttempt): LinkSetRewrapSource | null {\n return attempt.status === \"prepared\" ? attempt.source : null;\n}\n\n/** Whether a refusal of this attempt is held back until the leg decides. */\nexport function holdsLinkSetRefusals(attempt: LinkSetLegAttempt): boolean {\n return isSpeculativeRewrapSource(attemptSource(attempt));\n}\n\n/** The event an attempt's result raises. */\nexport function linkSetAttemptEvent(input: {\n readonly attempt: LinkSetLegAttempt;\n readonly committed: boolean;\n readonly heldFailures: readonly LinkSetSubmitFailure[];\n readonly stillCurrent: boolean;\n}): LinkSetLegEvent {\n const rewraps =\n input.attempt.status === \"prepared\" ? input.attempt.rewraps : null;\n return input.committed\n ? { rewraps, type: \"attemptCommitted\" }\n : {\n heldFailures: input.heldFailures,\n source: attemptSource(input.attempt),\n stillCurrent: input.stillCurrent,\n type: \"attemptFailed\",\n };\n}\n\nfunction isSpeculativeRewrapSource(\n source: LinkSetRewrapSource | null,\n): boolean {\n return source === \"reused\" || source === \"skipped\";\n}\n\n/**\n * The server's binding check refused rewraps cited without listing: the coded\n * attachment-set refusal (`lockDocumentLinkBlobRewraps`), or for re-cited\n * envelopes the uncoded content-key epoch refusal the current server returns\n * per cited blob (`rewrapDocumentBlobContentKeyInTransaction`). A skipped\n * attempt cites no blob, so only the coded refusal can answer it.\n */\nfunction refusedSpeculativeRewraps(\n source: LinkSetRewrapSource | null,\n failure: DocumentLinkSetMutationFailure,\n): boolean {\n if (failure.status !== 409 || !isSpeculativeRewrapSource(source))\n return false;\n if (failure.code === DOCUMENT_MUTATION_ERROR_CODES.linkAttachmentsChanged)\n return true;\n return source === \"reused\" && failure.code === undefined;\n}\n\n/**\n * Only a speculative attempt the binding check refused retries, and only\n * once: the fresh attempt lists, so it cannot be refused for the same stale\n * view again. Any other refusal keeps its own recovery path.\n */\nexport function transitionLinkSetLeg(\n state: LinkSetLegState,\n event: LinkSetLegEvent,\n): LinkSetLegState {\n if (state.status !== \"speculative\" && state.status !== \"fresh\") return state;\n if (event.type === \"attemptCommitted\")\n return { rewraps: event.rewraps, status: \"committed\" };\n // Nothing an ended operation held back is retried or reported.\n if (!event.stillCurrent) return { status: \"abandoned\" };\n const retryable =\n state.status === \"speculative\" &&\n event.heldFailures.some((failure) =>\n refusedSpeculativeRewraps(event.source, failure),\n );\n return retryable\n ? { status: \"fresh\" }\n : { status: \"failed\", unreported: event.heldFailures };\n}\n"]}
@@ -23,9 +23,9 @@ export interface RelinkRemoteDocumentRequest {
23
23
  warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
24
24
  }
25
25
  /**
26
- * A leg that re-cited the previous leg's envelopes and was refused with an
27
- * uncoded 409 (the attachment set or its key epoch moved) lists and retries
28
- * once, as a leg without reuse would have; that first failure is not
29
- * reported.
26
+ * A leg that cited rewraps without listing and was refused because the
27
+ * attachment set (or a re-cited key epoch) moved lists and retries once, as a
28
+ * leg that listed would have; that first refusal is neither reported nor
29
+ * retried once the operation is no longer current (`transitionLinkSetLeg`).
30
30
  */
31
31
  export declare function relinkRemoteDocument(remote: RemoteDocumentCollaborators, request: RelinkRemoteDocumentRequest): Promise<RelinkRemoteDocumentResult | null>;
@@ -1,32 +1,50 @@
1
1
  import { acknowledgedDocumentLinkSetMutation, persistedDocumentStateFromAcknowledgement, } from "../../../data/documents/shared/responses.js";
2
2
  import { acknowledgeDocumentMutation } from "../../../data/documents/shared/sync/mutationAcknowledgement.js";
3
3
  import { nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../../data/keyingProjectionVerification/index.js";
4
+ import { documentMayHaveAttachments } from "../../../data/persistence/documents/documentAttachmentPresence.js";
4
5
  import { recordDocumentAuthorAccessFailure } from "../authorAccessFailure.js";
5
6
  import { completeLinkSetMutationRequest } from "../rotationBaseline.js";
6
7
  import { buildMaterializedDocumentLinkSetMutationPlan } from "./index.js";
7
8
  import { prepareDocumentLinkBlobRewraps, reuseCommittedBlobRewraps, } from "./linkSetBlobRewraps.js";
9
+ import { holdsLinkSetRefusals, INITIAL_LINK_SET_LEG_STATE, linkSetAttemptEvent, recordLinkSetLegRewraps, startLinkSetLegAttempt, transitionLinkSetLeg, } from "./linkSetLegMachine.js";
8
10
  import { seedLinkSetWriterProjection } from "./linkSetProjectionSeed.js";
9
11
  async function submitLinkSetMutation(input) {
10
12
  if (input.stillCurrent?.() === false)
11
13
  return null;
12
14
  const { apiClient } = input;
13
- // Preserve the HTTP failure for the durable move-intent queue.
15
+ // Preserve the HTTP failure for the durable move-intent queue. Its host
16
+ // report waits until the leg knows the refusal is not one it recovers from.
14
17
  const resultFn = input.operation === "link"
15
18
  ? apiClient.linkDocumentResult.bind(apiClient)
16
19
  : apiClient.unlinkDocumentResult.bind(apiClient);
17
20
  const result = await resultFn(input.documentId, input.request, {
18
21
  expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,
22
+ reportErrors: false,
19
23
  });
20
24
  if (result.ok) {
21
25
  return result.data;
22
26
  }
23
- input.onFailure?.({
27
+ // A refusal the operation no longer waits for is neither retried nor
28
+ // reported.
29
+ if (input.stillCurrent?.() === false)
30
+ return null;
31
+ input.onFailure({
24
32
  code: result.code,
25
33
  message: result.message,
34
+ report: result.report,
26
35
  status: result.status,
27
36
  });
28
37
  return null;
29
38
  }
39
+ /** Hand a refusal the leg does not recover from to its host and caller. */
40
+ function reportLinkSetFailure(input, failure) {
41
+ failure.report?.();
42
+ input.onFailure?.({
43
+ code: failure.code,
44
+ message: failure.message,
45
+ status: failure.status,
46
+ });
47
+ }
30
48
  // Cold-cache projection fetches must keep their HTTP status: collapsing a
31
49
  // 403 to null would leave an access-denied link/unlink routinely retriable
32
50
  // instead of parking its move for the access-restored signal (row 7).
@@ -35,11 +53,11 @@ async function fetchLinkSetProjection(input) {
35
53
  if (result.ok) {
36
54
  return { failure: null, projection: result.data };
37
55
  }
38
- result.report();
39
56
  return {
40
57
  failure: {
41
58
  code: result.code,
42
59
  message: result.message,
60
+ report: result.report,
43
61
  status: result.status,
44
62
  },
45
63
  projection: null,
@@ -88,10 +106,10 @@ async function completeRemoteDocumentLinkSet(input) {
88
106
  };
89
107
  }
90
108
  /**
91
- * A leg that re-cited the previous leg's envelopes and was refused with an
92
- * uncoded 409 (the attachment set or its key epoch moved) lists and retries
93
- * once, as a leg without reuse would have; that first failure is not
94
- * reported.
109
+ * A leg that cited rewraps without listing and was refused because the
110
+ * attachment set (or a re-cited key epoch) moved lists and retries once, as a
111
+ * leg that listed would have; that first refusal is neither reported nor
112
+ * retried once the operation is no longer current (`transitionLinkSetLeg`).
95
113
  */
96
114
  export async function relinkRemoteDocument(remote, request) {
97
115
  if (!remote.encapsulationSecretKey) {
@@ -104,35 +122,38 @@ export async function relinkRemoteDocument(remote, request) {
104
122
  targetSecretKey: remote.encapsulationSecretKey,
105
123
  };
106
124
  const reuse = input.attachmentReuse;
107
- const failures = [];
108
- const attempt = { reused: false, rewraps: null };
109
- const result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {
110
- if (attempt.reused)
111
- failures.push(failure);
112
- else
113
- input.onFailure?.(failure);
114
- }).catch((error) => {
115
- // A leg that threw may have committed before failing: list again next.
125
+ let leg = INITIAL_LINK_SET_LEG_STATE;
126
+ let result = null;
127
+ while (leg.status === "speculative" || leg.status === "fresh") {
128
+ const attempt = { current: startLinkSetLegAttempt(leg) };
129
+ const heldFailures = [];
130
+ result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {
131
+ if (holdsLinkSetRefusals(attempt.current))
132
+ heldFailures.push(failure);
133
+ else
134
+ reportLinkSetFailure(input, failure);
135
+ }).catch((error) => {
136
+ // A leg that threw may have committed before failing: list again next.
137
+ if (reuse)
138
+ reuse.committed = null;
139
+ throw error;
140
+ });
141
+ const event = linkSetAttemptEvent({
142
+ attempt: attempt.current,
143
+ committed: result !== null,
144
+ heldFailures,
145
+ stillCurrent: input.stillCurrent?.() !== false,
146
+ });
116
147
  if (reuse)
117
- reuse.committed = null;
118
- throw error;
119
- });
120
- if (reuse)
121
- reuse.committed = result ? attempt.rewraps : null;
122
- if (result || !attempt.reused)
123
- return result;
124
- // The attachment-set and key-epoch refusals are uncoded 409s; a coded one
125
- // (stale state, an unavailable container) keeps its own recovery path.
126
- if (!failures.some((failure) => failure.status === 409 && failure.code === undefined)) {
127
- for (const failure of failures)
128
- input.onFailure?.(failure);
129
- return null;
148
+ reuse.committed =
149
+ event.type === "attemptCommitted" ? event.rewraps : null;
150
+ leg = transitionLinkSetLeg(leg, event);
151
+ }
152
+ if (leg.status === "failed") {
153
+ for (const failure of leg.unreported)
154
+ reportLinkSetFailure(input, failure);
130
155
  }
131
- const retry = { reused: false, rewraps: null };
132
- const retried = await relinkRemoteDocumentOnce(input, retry, (failure) => input.onFailure?.(failure));
133
- if (reuse)
134
- reuse.committed = retried ? retry.rewraps : null;
135
- return retried;
156
+ return result;
136
157
  }
137
158
  async function relinkRemoteDocumentOnce(input, attempt, onSubmitFailure) {
138
159
  if (input.operation === "unlink" && !input.rotationSnapshot) {
@@ -144,11 +165,14 @@ async function relinkRemoteDocumentOnce(input, attempt, onSubmitFailure) {
144
165
  fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),
145
166
  ]);
146
167
  if (!writerFetch.projection || !targetContainerFetch.projection) {
168
+ // A failure the operation no longer waits for is not reported.
169
+ if (input.stillCurrent?.() === false)
170
+ return null;
147
171
  for (const failure of orderedProjectionFailures([
148
172
  writerFetch.failure,
149
173
  targetContainerFetch.failure,
150
174
  ])) {
151
- input.onFailure?.(failure);
175
+ reportLinkSetFailure(input, failure);
152
176
  }
153
177
  return null;
154
178
  }
@@ -209,26 +233,46 @@ function orderedProjectionFailures(failures) {
209
233
  ...present.filter((failure) => failure.status === 403),
210
234
  ];
211
235
  }
236
+ /**
237
+ * Rewraps a first attempt may sign without listing: the previous leg's
238
+ * envelopes, or none when the local view holds no attachment for the
239
+ * document. The server's binding check at commit refuses either if stale.
240
+ */
241
+ async function speculativeBlobRewraps(input, writerProjection, targets) {
242
+ const committed = input.attachmentReuse?.committed;
243
+ if (committed) {
244
+ const reused = reuseCommittedBlobRewraps({
245
+ committed,
246
+ documentId: writerProjection.documentId,
247
+ targets,
248
+ });
249
+ if (reused)
250
+ return { rewraps: reused, source: "reused" };
251
+ // The previous leg cited attachments this leg cannot re-cite: list them.
252
+ if (committed.length > 0)
253
+ return null;
254
+ }
255
+ if (await documentMayHaveAttachments(input.execSql, writerProjection.documentId))
256
+ return null;
257
+ return { rewraps: [], source: "skipped" };
258
+ }
212
259
  function prepareRemoteLinkSetMutation(input, writerProjection, targetContainerProjection, attempt) {
213
260
  const prepareBlobRewraps = async (targets) => {
214
- const committed = input.attachmentReuse?.committed;
215
- const reused = committed
216
- ? reuseCommittedBlobRewraps({
217
- committed,
218
- documentId: writerProjection.documentId,
261
+ const prepared = (attempt.current.listing ===
262
+ "speculative"
263
+ ? await speculativeBlobRewraps(input, writerProjection, targets)
264
+ : null) ?? {
265
+ rewraps: await prepareDocumentLinkBlobRewraps({
266
+ ...input,
267
+ refreshListing: attempt.current.listing === "fresh",
219
268
  targets,
220
- })
221
- : null;
222
- attempt.reused = reused !== null;
223
- attempt.rewraps =
224
- reused ??
225
- (await prepareDocumentLinkBlobRewraps({
226
- ...input,
227
- targets,
228
- targetContainerProjection,
229
- writerProjection,
230
- }));
231
- return attempt.rewraps;
269
+ targetContainerProjection,
270
+ writerProjection,
271
+ }),
272
+ source: "listed",
273
+ };
274
+ attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);
275
+ return prepared.rewraps;
232
276
  };
233
277
  return recordDocumentAuthorAccessFailure(() => nullOnProjectionVerificationCancellation(() => buildMaterializedDocumentLinkSetMutationPlan({
234
278
  author: input.author,
@@ -1 +1 @@
1
- {"version":3,"file":"linkSetRemote.js","sourceRoot":"","sources":["linkSetRemote.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,mCAAmC,EACnC,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAU1G,OAAO,EACL,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAG3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,4CAA4C,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAEL,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAEtE,KAAK,UAAU,qBAAqB,CAAC,KAQpC;IACC,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,+DAA+D;IAC/D,MAAM,QAAQ,GACZ,KAAK,CAAC,SAAS,KAAK,MAAM;QACxB,CAAC,CAAC,SAAS,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC;QAC9C,CAAC,CAAC,SAAS,CAAC,oBAAoB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,OAAO,EAAE;QAC7D,qCAAqC,EAAE,KAAK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,MAAM,GAAG,SAAS;YACtB,CAAC,CAAC,yBAAyB,CAAC;gBACxB,SAAS;gBACT,UAAU,EAAE,gBAAgB,CAAC,UAAU;gBACvC,OAAO;aACR,CAAC;YACJ,CAAC,CAAC,IAAI,CAAC;QACT,OAAO,CAAC,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;QACjC,OAAO,CAAC,OAAO;YACb,MAAM;gBACN,CAAC,MAAM,8BAA8B,CAAC;oBACpC,GAAG,KAAK;oBACR,OAAO;oBACP,yBAAyB;oBACzB,gBAAgB;iBACjB,CAAC,CAAC,CAAC;QACN,OAAO,OAAO,CAAC,OAAO,CAAC;IACzB,CAAC,CAAC;IACF,OAAO,iCAAiC,CACtC,GAAG,EAAE,CACH,wCAAwC,CAAC,GAAG,EAAE,CAC5C,4CAA4C,CAAC;QAC3C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB;QAClB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationFailure,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n });\n if (result.ok) {\n return result.data;\n }\n input.onFailure?.({\n code: result.code,\n message: result.message,\n status: result.status,\n });\n return null;\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: DocumentLinkSetMutationFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n result.report();\n return {\n failure: {\n code: result.code,\n message: result.message,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/** What one leg signed, so the workflow can reuse or retry it. */\ninterface LinkSetLegAttempt {\n rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"] | null;\n reused: boolean;\n}\n\n/**\n * A leg that re-cited the previous leg's envelopes and was refused with an\n * uncoded 409 (the attachment set or its key epoch moved) lists and retries\n * once, as a leg without reuse would have; that first failure is not\n * reported.\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n const failures: DocumentLinkSetMutationFailure[] = [];\n const attempt: LinkSetLegAttempt = { reused: false, rewraps: null };\n const result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (attempt.reused) failures.push(failure);\n else input.onFailure?.(failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n if (reuse) reuse.committed = result ? attempt.rewraps : null;\n if (result || !attempt.reused) return result;\n // The attachment-set and key-epoch refusals are uncoded 409s; a coded one\n // (stale state, an unavailable container) keeps its own recovery path.\n if (\n !failures.some(\n (failure) => failure.status === 409 && failure.code === undefined,\n )\n ) {\n for (const failure of failures) input.onFailure?.(failure);\n return null;\n }\n const retry: LinkSetLegAttempt = { reused: false, rewraps: null };\n const retried = await relinkRemoteDocumentOnce(input, retry, (failure) =>\n input.onFailure?.(failure),\n );\n if (reuse) reuse.committed = retried ? retry.rewraps : null;\n return retried;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetLegAttempt,\n onSubmitFailure: DocumentLinkSetFailureHandler,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n input.onFailure?.(failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (DocumentLinkSetMutationFailure | null)[],\n): DocumentLinkSetMutationFailure[] {\n const present = failures.filter(\n (failure): failure is DocumentLinkSetMutationFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetLegAttempt,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const committed = input.attachmentReuse?.committed;\n const reused = committed\n ? reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n })\n : null;\n attempt.reused = reused !== null;\n attempt.rewraps =\n reused ??\n (await prepareDocumentLinkBlobRewraps({\n ...input,\n targets,\n targetContainerProjection,\n writerProjection,\n }));\n return attempt.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}
1
+ {"version":3,"file":"linkSetRemote.js","sourceRoot":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ACR,cAAc,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO,KAAK,OAAO;gBACnD,OAAO;gBACP,yBAAyB;gBACzB,gBAAgB;aACjB,CAAC;YACF,MAAM,EAAE,QAAQ;SACjB,CAAC;QACF,OAAO,CAAC,OAAO,GAAG,uBAAuB,CAAC,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACrE,OAAO,QAAQ,CAAC,OAAO,CAAC;IAC1B,CAAC,CAAC;IACF,OAAO,iCAAiC,CACtC,GAAG,EAAE,CACH,wCAAwC,CAAC,GAAG,EAAE,CAC5C,4CAA4C,CAAC;QAC3C,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,kBAAkB;QAClB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,yBAAyB;QACzB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,+BAA+B,EAC7B,KAAK,CAAC,+BAA+B;QACvC,gBAAgB;KACjB,CAAC,CACH,EACH,KAAK,CAAC,SAAS,CAChB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type { DocumentLinkSetMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n acknowledgedDocumentLinkSetMutation,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type { DocumentSyncSubmitFailure } from \"../../../data/documents/shared/sync/syncSubmitFailure\";\nimport type {\n DocumentCreateAuthor,\n DocumentLinkSetFailureHandler,\n DocumentLinkSetMutationApi,\n DocumentLinkSetMutationOperation,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentMayHaveAttachments } from \"../../../data/persistence/documents/documentAttachmentPresence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { SubtreePurgeRoot } from \"../purge/subtreePurgeScope\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport { completeLinkSetMutationRequest } from \"../rotationBaseline\";\nimport { buildMaterializedDocumentLinkSetMutationPlan } from \"./index\";\nimport {\n type LinkSetAttachmentReuse,\n prepareDocumentLinkBlobRewraps,\n reuseCommittedBlobRewraps,\n} from \"./linkSetBlobRewraps\";\nimport {\n holdsLinkSetRefusals,\n INITIAL_LINK_SET_LEG_STATE,\n type LinkSetLegAttempt,\n type LinkSetSubmitFailure,\n linkSetAttemptEvent,\n type PreparedLinkSetRewraps,\n recordLinkSetLegRewraps,\n startLinkSetLegAttempt,\n transitionLinkSetLeg,\n} from \"./linkSetLegMachine\";\nimport { seedLinkSetWriterProjection } from \"./linkSetProjectionSeed\";\n\nasync function submitLinkSetMutation(input: {\n apiClient: DocumentLinkSetMutationApi;\n documentId: string;\n expectedOrganizationId: string;\n onFailure: (failure: LinkSetSubmitFailure) => void;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<DocumentLinkSetMutationResponse | null> {\n if (input.stillCurrent?.() === false) return null;\n const { apiClient } = input;\n // Preserve the HTTP failure for the durable move-intent queue. Its host\n // report waits until the leg knows the refusal is not one it recovers from.\n const resultFn =\n input.operation === \"link\"\n ? apiClient.linkDocumentResult.bind(apiClient)\n : apiClient.unlinkDocumentResult.bind(apiClient);\n const result = await resultFn(input.documentId, input.request, {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n reportErrors: false,\n });\n if (result.ok) {\n return result.data;\n }\n // A refusal the operation no longer waits for is neither retried nor\n // reported.\n if (input.stillCurrent?.() === false) return null;\n input.onFailure({\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n });\n return null;\n}\n\n/** Hand a refusal the leg does not recover from to its host and caller. */\nfunction reportLinkSetFailure(\n input: Pick<RelinkRemoteDocumentInput, \"onFailure\">,\n failure: LinkSetSubmitFailure,\n): void {\n failure.report?.();\n input.onFailure?.({\n code: failure.code,\n message: failure.message,\n status: failure.status,\n });\n}\n\ninterface LinkSetProjectionFetch<TProjection> {\n failure: LinkSetSubmitFailure | null;\n projection: TProjection | null;\n}\n\n// Cold-cache projection fetches must keep their HTTP status: collapsing a\n// 403 to null would leave an access-denied link/unlink routinely retriable\n// instead of parking its move for the access-restored signal (row 7).\nasync function fetchLinkSetProjection<TProjection>(input: {\n fetchProjectionResult: () => Promise<\n | { readonly data: TProjection; readonly ok: true }\n | DocumentSyncSubmitFailure\n >;\n}): Promise<LinkSetProjectionFetch<TProjection>> {\n const result = await input.fetchProjectionResult();\n if (result.ok) {\n return { failure: null, projection: result.data };\n }\n return {\n failure: {\n code: result.code,\n message: result.message,\n report: result.report,\n status: result.status,\n },\n projection: null,\n };\n}\n\nfunction fetchLinkSetDocumentProjection(\n apiClient: DocumentLinkSetMutationApi,\n documentId: string,\n): Promise<LinkSetProjectionFetch<DocumentWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getDocumentWriterProjectionResult.bind(\n apiClient,\n documentId,\n { reportErrors: false },\n ),\n });\n}\n\nfunction fetchLinkSetContainerProjection(\n apiClient: DocumentLinkSetMutationApi,\n containerId: string,\n): Promise<LinkSetProjectionFetch<ContainerWriterProjectionResponse>> {\n return fetchLinkSetProjection({\n fetchProjectionResult: apiClient.getContainerWriterProjectionResult.bind(\n apiClient,\n containerId,\n { reportErrors: false },\n ),\n });\n}\n\nasync function completeRemoteDocumentLinkSet(input: {\n completedPlan: Parameters<typeof acknowledgedDocumentLinkSetMutation>[0];\n execSql: ExecSql;\n materializedPlan: Awaited<\n ReturnType<typeof buildMaterializedDocumentLinkSetMutationPlan>\n >;\n operation: DocumentLinkSetMutationOperation;\n response: DocumentLinkSetMutationResponse;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n targetContainerProjection: ContainerWriterProjectionResponse;\n writerProjection: DocumentWriterProjectionResponse;\n apiClient: DocumentLinkSetMutationApi;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const acknowledged = acknowledgedDocumentLinkSetMutation(\n input.completedPlan,\n input.response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n execSql: input.execSql,\n plan: input.completedPlan,\n stillCurrent: input.stillCurrent,\n });\n await seedLinkSetWriterProjection({\n apiClient: input.apiClient,\n execSql: input.execSql,\n operation: input.operation,\n priorProjection: input.writerProjection,\n response: acknowledged,\n targetContainerId: input.targetContainerId,\n targetContainerProjection: input.targetContainerProjection,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n return {\n contentKey: input.materializedPlan.contentKey,\n contentKeyRotated: input.materializedPlan.contentKeyRotated,\n documentId: input.response.id,\n linkedContainerIds: [\n ...input.materializedPlan.plan.state.linkedContainerIds,\n ],\n persistedState,\n plan: input.completedPlan,\n response: input.response,\n };\n}\n\n/** What varies per link or unlink leg; the collaborators bind the rest. */\nexport interface RelinkRemoteDocumentRequest {\n /** Shared by the legs of one move or trash workflow. */\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n author: DocumentCreateAuthor;\n contentKey?: Uint8Array | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n eventId?: string | undefined;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: DocumentLinkSetMutationOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetContainerId: string;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RelinkRemoteDocumentInput extends RelinkRemoteDocumentRequest {\n apiClient: DocumentLinkSetMutationApi;\n execSql: ExecSql;\n targetSecretKey: Uint8Array;\n}\n\n/**\n * A leg that cited rewraps without listing and was refused because the\n * attachment set (or a re-cited key epoch) moved lists and retries once, as a\n * leg that listed would have; that first refusal is neither reported nor\n * retried once the operation is no longer current (`transitionLinkSetLeg`).\n */\nexport async function relinkRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: RelinkRemoteDocumentRequest,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\n \"Remote document link-set mutation requires an encapsulation key\",\n );\n }\n const input: RelinkRemoteDocumentInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n const reuse = input.attachmentReuse;\n let leg = INITIAL_LINK_SET_LEG_STATE;\n let result: RelinkRemoteDocumentResult | null = null;\n while (leg.status === \"speculative\" || leg.status === \"fresh\") {\n const attempt = { current: startLinkSetLegAttempt(leg) };\n const heldFailures: LinkSetSubmitFailure[] = [];\n result = await relinkRemoteDocumentOnce(input, attempt, (failure) => {\n if (holdsLinkSetRefusals(attempt.current)) heldFailures.push(failure);\n else reportLinkSetFailure(input, failure);\n }).catch((error: unknown) => {\n // A leg that threw may have committed before failing: list again next.\n if (reuse) reuse.committed = null;\n throw error;\n });\n const event = linkSetAttemptEvent({\n attempt: attempt.current,\n committed: result !== null,\n heldFailures,\n stillCurrent: input.stillCurrent?.() !== false,\n });\n if (reuse)\n reuse.committed =\n event.type === \"attemptCommitted\" ? event.rewraps : null;\n leg = transitionLinkSetLeg(leg, event);\n }\n if (leg.status === \"failed\") {\n for (const failure of leg.unreported) reportLinkSetFailure(input, failure);\n }\n return result;\n}\n\n/** The attempt in flight; preparation replaces it with what it signed. */\ninterface LinkSetAttemptSlot {\n current: LinkSetLegAttempt;\n}\n\nasync function relinkRemoteDocumentOnce(\n input: RelinkRemoteDocumentInput,\n attempt: LinkSetAttemptSlot,\n onSubmitFailure: (failure: LinkSetSubmitFailure) => void,\n): Promise<RelinkRemoteDocumentResult | null> {\n if (input.operation === \"unlink\" && !input.rotationSnapshot) {\n throw new Error(\n \"Document unlink requires a proven full-history rotation snapshot\",\n );\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document link-set mutation\",\n );\n const [writerFetch, targetContainerFetch] = await Promise.all([\n fetchLinkSetDocumentProjection(input.apiClient, input.documentId),\n fetchLinkSetContainerProjection(input.apiClient, input.targetContainerId),\n ]);\n if (!writerFetch.projection || !targetContainerFetch.projection) {\n // A failure the operation no longer waits for is not reported.\n if (input.stillCurrent?.() === false) return null;\n for (const failure of orderedProjectionFailures([\n writerFetch.failure,\n targetContainerFetch.failure,\n ])) {\n reportLinkSetFailure(input, failure);\n }\n return null;\n }\n const writerProjection = writerFetch.projection;\n const targetContainerProjection = targetContainerFetch.projection;\n if (input.stillCurrent?.() === false) return null;\n\n const signedAt = input.signedAt ?? new Date().toISOString();\n const materializedPlan = await prepareRemoteLinkSetMutation(\n { ...input, resolveProjectionUserKey, signedAt },\n writerProjection,\n targetContainerProjection,\n attempt,\n );\n if (!materializedPlan) return null;\n const request = await completeLinkSetMutationRequest({\n author: input.author,\n materializedPlan,\n operation: input.operation,\n rotationSnapshot: input.rotationSnapshot,\n signedAt,\n });\n const completedPlan = { ...materializedPlan.plan, request };\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n const response = await submitLinkSetMutation({\n apiClient: input.apiClient,\n documentId: completedPlan.documentId,\n expectedOrganizationId: completedPlan.state.organizationId,\n onFailure: onSubmitFailure,\n operation: input.operation,\n request: completedPlan.request,\n stillCurrent: input.stillCurrent,\n });\n if (!response) {\n return null;\n }\n if (input.stillCurrent?.() === false) return null;\n return completeRemoteDocumentLinkSet({\n apiClient: input.apiClient,\n completedPlan,\n execSql: input.execSql,\n materializedPlan,\n operation: input.operation,\n response,\n stillCurrent: input.stillCurrent,\n targetContainerId: input.targetContainerId,\n targetContainerProjection,\n writerProjection,\n });\n}\n\n// Every projection failure reaches the handler: the queued-move accumulator\n// classifies a vanished container from ANY coded container 404, so a document\n// fetch failure must not hide a container one (or vice versa). A 403 is\n// delivered last, so a single-slot consumer keeps the denial that parks the\n// move (row 7) while the accumulator still sees both.\nfunction orderedProjectionFailures(\n failures: readonly (LinkSetSubmitFailure | null)[],\n): LinkSetSubmitFailure[] {\n const present = failures.filter(\n (failure): failure is LinkSetSubmitFailure => failure !== null,\n );\n return [\n ...present.filter((failure) => failure.status !== 403),\n ...present.filter((failure) => failure.status === 403),\n ];\n}\n\n/**\n * Rewraps a first attempt may sign without listing: the previous leg's\n * envelopes, or none when the local view holds no attachment for the\n * document. The server's binding check at commit refuses either if stale.\n */\nasync function speculativeBlobRewraps(\n input: RelinkRemoteDocumentInput,\n writerProjection: DocumentWriterProjectionResponse,\n targets: readonly DocumentContentKeyTarget[],\n): Promise<{\n readonly rewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n readonly source: \"reused\" | \"skipped\";\n} | null> {\n const committed = input.attachmentReuse?.committed;\n if (committed) {\n const reused = reuseCommittedBlobRewraps({\n committed,\n documentId: writerProjection.documentId,\n targets,\n });\n if (reused) return { rewraps: reused, source: \"reused\" };\n // The previous leg cited attachments this leg cannot re-cite: list them.\n if (committed.length > 0) return null;\n }\n if (\n await documentMayHaveAttachments(input.execSql, writerProjection.documentId)\n )\n return null;\n return { rewraps: [], source: \"skipped\" };\n}\n\nfunction prepareRemoteLinkSetMutation(\n input: RelinkRemoteDocumentInput & {\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt: string;\n },\n writerProjection: DocumentWriterProjectionResponse,\n targetContainerProjection: ContainerWriterProjectionResponse,\n attempt: LinkSetAttemptSlot,\n) {\n const prepareBlobRewraps = async (\n targets: readonly DocumentContentKeyTarget[],\n ) => {\n const prepared: PreparedLinkSetRewraps = (attempt.current.listing ===\n \"speculative\"\n ? await speculativeBlobRewraps(input, writerProjection, targets)\n : null) ?? {\n rewraps: await prepareDocumentLinkBlobRewraps({\n ...input,\n refreshListing: attempt.current.listing === \"fresh\",\n targets,\n targetContainerProjection,\n writerProjection,\n }),\n source: \"listed\",\n };\n attempt.current = recordLinkSetLegRewraps(attempt.current, prepared);\n return prepared.rewraps;\n };\n return recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n buildMaterializedDocumentLinkSetMutationPlan({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n prepareBlobRewraps,\n contentKey: input.contentKey,\n eventId: input.eventId,\n execSql: input.execSql,\n operation: input.operation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetContainerProjection,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n writerProjection,\n }),\n ),\n input.onFailure,\n );\n}\n"]}