@gusto/baerly-storage 0.5.0 → 0.7.0

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 (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore-U6Im8V1V.js","names":[],"sources":["../packages/protocol/src/code-resolution.ts","../packages/protocol/src/document-input.ts","../packages/protocol/src/document-size.ts","../packages/protocol/src/json.ts","../packages/server/src/doc-id.ts","../packages/server/src/key-limit.ts","../packages/server/src/log-conflict-adoption.ts","../packages/server/src/post-image-identity.ts","../packages/server/src/writer.ts","../packages/cli/src/admin/restore.ts"],"sourcesContent":["import type { BaerlyErrorCode } from \"./errors.ts\";\n\n/** Canonical per-code corrective action; `errorEnvelope` falls back to this and it crosses the wire as `resolution`. Actionable codes only. One canonical action per actionable code; a throw site may pass a more specific resolution (CLI `restore`), never a different retry meaning. */\nexport const CODE_RESOLUTIONS: Partial<Record<BaerlyErrorCode, string>> = {\n WriteConflict:\n \"Another write changed this data first and this commit did not land. Re-read, then retry.\",\n AlreadyExists:\n \"Do not retry. A row with this _id is already committed: insert with a different _id or omit _id to auto-generate one, or use update or replace to change the existing row. If this insert omitted _id or followed an AmbiguousCommit, the row may be this insert's own earlier attempt: re-read it, and do not re-mint by inserting again without an _id.\",\n AmbiguousCommit:\n \"Do not retry automatically. Re-read the row named by the error's _id; absence does not prove the write failed. A deliberate retry may repeat logical work; retry an insert with the same _id, and treat AlreadyExists on that retry as a committed row to re-read.\",\n CapacityExceeded:\n \"Do not retry unchanged. Delete or shrink rows to make room; if every write is refused, the collection has outgrown this host: export it with baerly admin dump, or move it to a larger host.\",\n MaintenancePending:\n \"Retry after the delay in retryAfter (Retry-After header, seconds): maintenance is catching up on this collection and this write was not committed.\",\n CursorExpired:\n 'Do not retry this cursor. The changes after it are no longer retained: re-read the rows you need, then resume /v1/since with cursor: \"\".',\n PayloadTooLarge: \"Reduce the request body below the server's body-size cap (1 MiB default).\",\n UnsupportedMediaType:\n \"Send the request body as JSON with a Content-Type: application/json header.\",\n Unauthorized: \"Send a valid Authorization header for the server's configured auth method.\",\n AccessDenied: \"These credentials are denied for this tenant prefix or bucket policy.\",\n NotFound: \"No row matches this id; create it first or treat this as a miss.\",\n};\n\n/** Resolution for a malformed `?where=` / `?order=` query value. */\nexport const WHERE_ORDER_JSON_RESOLUTION: string =\n \"Pass a URL-encoded JSON object as the ?where= / ?order= value.\";\n\n/** Resolution for an empty / malformed / unwrapped write body. */\nexport const WRITE_BODY_SHAPE_RESOLUTION: string =\n 'Send a JSON body shaped { \"doc\": { ... } } for POST/PUT, or { \"patch\": { ... } } for PATCH.';\n","import {\n DOCUMENT_ERROR_PATH_EDGE_SEGMENTS,\n DOCUMENT_ERROR_PATH_KEY_CHARS,\n MAX_DOCUMENT_DEPTH,\n} from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\n\nconst INSERT_ID_RESOLUTION =\n \"Pass _id as a non-empty string (for example String(value)), or omit it to have one generated.\";\n\n/**\n * Reject a present, non-string `_id` on an insert. `undefined` is absent and\n * `\"\"` is a string, so both still get a generated id; `null`, numbers\n * (`-0` and `NaN` included), booleans, objects and arrays throw. Checks the\n * caller's own value, before anything replaces it with a generated id.\n * Shared by the server's insert and the HTTP client's, so the two agree on\n * which ids are generated.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `id` is present and not a string.\n */\nexport const assertInsertIdType = (id: unknown): void => {\n if (id !== undefined && typeof id !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `insert: _id must be a string, got ${id === null ? \"null\" : typeof id}`,\n { resolution: INSERT_ID_RESOLUTION },\n );\n }\n};\n\nconst NON_FINITE_RESOLUTION =\n \"JSON cannot represent NaN or Infinity. Store a finite number or null there, or omit the field.\";\nconst UNDEFINED_MEMBER_RESOLUTION =\n \"JSON drops a member whose value is undefined. Omit the field, or store null.\";\nconst UNDEFINED_ELEMENT_RESOLUTION =\n \"JSON turns an undefined or missing array element into null. Store null there, or remove the element.\";\nconst NON_PLAIN_RESOLUTION =\n \"Store plain JSON: convert a Date with date.toISOString(), a Map with Object.fromEntries(map), a Set or typed array with Array.from(value), a boxed primitive with value.valueOf(), and copy a class instance's fields into a plain object.\";\nconst NON_JSON_TYPE_RESOLUTION =\n \"Store a string, finite number, boolean, null, plain object or array there. Convert a bigint with String(value); remove functions and symbols.\";\nconst TO_JSON_RESOLUTION =\n \"Remove the toJSON hook and pass its intended JSON data explicitly. Documents and patches must not customize JSON serialization.\";\nconst CIRCULAR_RESOLUTION =\n \"Remove the circular reference: a document is a tree of plain objects and arrays.\";\nconst DEPTH_RESOLUTION = `Keep each document at most ${MAX_DOCUMENT_DEPTH} levels deep (each object or array is a level, the document itself included): flatten nested data into compound keys or arrays of records, or move a deep subtree into rows of its own.`;\n\n/** Inspect descriptors so even a toJSON getter is refused without running it. */\nconst hasJsonHook = (value: object): boolean => {\n for (\n let at: object | null = value;\n at !== null;\n at = Object.getPrototypeOf(at) as object | null\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(at, \"toJSON\");\n if (descriptor !== undefined) {\n // JSON looks up the first property in the chain. A non-callable\n // data value shadows any inherited hook and is ordinary JSON data.\n return !(\"value\" in descriptor) || typeof descriptor.value === \"function\";\n }\n }\n return false;\n};\n\n/** One value awaiting a check, with the link back to its parent for the error path. */\ntype Pending = {\n readonly value: unknown;\n readonly parent: Pending | undefined;\n readonly key: string | number | undefined;\n /** Levels from the root, which is level 1 (see {@link MAX_DOCUMENT_DEPTH}). */\n readonly depth: number;\n};\n\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/;\n\nconst renderSegment = (key: string | number): string => {\n if (typeof key === \"number\") {\n return `[${key}]`;\n }\n if (key.length > DOCUMENT_ERROR_PATH_KEY_CHARS) {\n return `[${JSON.stringify(key.slice(0, DOCUMENT_ERROR_PATH_KEY_CHARS))}…]`;\n }\n return IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n};\n\n/** The keys from the root to `at`. */\nconst keysOf = (at: Pending): Array<string | number> => {\n const keys: Array<string | number> = [];\n for (let step: Pending | undefined = at; step?.key !== undefined; step = step.parent) {\n keys.push(step.key);\n }\n keys.reverse();\n return keys;\n};\n\n/**\n * The path from the root to `at`, as `a.b[2][\"c d\"]`. A deep path keeps\n * its first and last {@link DOCUMENT_ERROR_PATH_EDGE_SEGMENTS} segments\n * around a `.…` marker, so the message stays bounded.\n */\nconst pathOf = (at: Pending): string => {\n const keys = keysOf(at);\n const edge = DOCUMENT_ERROR_PATH_EDGE_SEGMENTS;\n const path =\n keys.length > 2 * edge\n ? `${keys.slice(0, edge).map(renderSegment).join(\"\")}.…${keys\n .slice(-edge)\n .map(renderSegment)\n .join(\"\")}`\n : keys.map(renderSegment).join(\"\");\n return path.startsWith(\".\") ? path.slice(1) : path;\n};\n\nconst refuse = (verb: string, at: Pending, what: string, resolution: string): never => {\n const path = pathOf(at);\n throw new BaerlyError(\n \"InvalidConfig\",\n path === \"\"\n ? `${verb}: the document is ${what}`\n : `${verb}: document value at ${path} is ${what}`,\n { resolution },\n );\n};\n\n/**\n * The first container past {@link MAX_DOCUMENT_DEPTH}. `SchemaError`, not\n * `InvalidConfig`: the value is valid JSON, but its shape is outside what\n * a document may be. `issues` carries the full path.\n */\nconst refuseDepth = (verb: string, at: Pending): never => {\n const message = `nests deeper than the ${MAX_DOCUMENT_DEPTH}-level document limit`;\n throw new BaerlyError(\"SchemaError\", `${verb}: document value at ${pathOf(at)} ${message}`, {\n resolution: DEPTH_RESOLUTION,\n issues: [{ path: keysOf(at), message }],\n });\n};\n\n/** Options for {@link assertDocumentValues}. */\nexport interface DocumentValuesOptions {\n /**\n * Treat an `undefined` object member as absent rather than refusing it,\n * as an update patch does: `JSON.stringify` drops the member, which is\n * the same patch as omitting it. `undefined` array elements are still\n * refused (JSON turns them into `null`).\n */\n readonly undefinedMembersAbsent?: boolean;\n}\n\n/**\n * Reject a document (or update patch) holding a value JSON cannot store\n * as written. `JSON.stringify` would silently turn `NaN` and `±Infinity`\n * into `null`, drop `undefined` members, turn `undefined` or missing array\n * elements into `null`, and reduce a `Date`, `Map`, typed array, boxed\n * primitive or class instance to a different shape; a function, symbol or\n * bigint would be dropped or throw. Each of those throws here instead,\n * naming the path of the first offending value (capped, see\n * {@link DOCUMENT_ERROR_PATH_EDGE_SEGMENTS}), as do circular references.\n * Callable or accessor `toJSON` properties (own or inherited) are refused\n * without invoking them, including on the root and on arrays. A value\n * nested deeper than {@link MAX_DOCUMENT_DEPTH} levels is refused too, as\n * `SchemaError`.\n *\n * Allowed: strings, finite numbers (`-0` included), booleans, `null` (at\n * any depth), arrays, and plain objects (prototype `Object.prototype` or\n * `null`). The root itself may be any object; its own\n * enumerable fields are checked. A top-level `_id: undefined` counts as\n * absent, as on `insert`; with `undefinedMembersAbsent`, every\n * `undefined` object member does. No `null` limits are applied.\n * Size is checked separately, on the whole post-image a write commits\n * (`assertDocumentSize`).\n *\n * The input graph must remain stable until the write completes. Ordinary\n * field getters are read during traversal; changing getters, proxies and\n * concurrent mutation are not supported as a way to supply document data.\n * This check does not snapshot the graph or execute serialization hooks.\n *\n * I/O-free. `insert` and `replace` call it on the caller's\n * document before any storage call, and `update` on each merged\n * post-image before any write; the HTTP client calls it before\n * serializing (on the patch, for `update`), because the coercions above\n * happen in `JSON.stringify` and a server only ever sees their result.\n *\n * @param verb the calling verb, used as the message prefix\n * (`\"insert\"`, `\"replace\"`, `\"update\"`, …).\n * @throws BaerlyError code=\"InvalidConfig\" — `value` holds a value outside\n * the JSON document domain. The message names its path.\n * @throws BaerlyError code=\"SchemaError\" — `value` nests an object or\n * array deeper than {@link MAX_DOCUMENT_DEPTH} levels. The message names\n * the limit and the (capped) path; `issues` holds the full path.\n */\nexport const assertDocumentValues = (\n value: unknown,\n verb: string,\n options?: DocumentValuesOptions,\n): void => {\n const undefinedMembersAbsent = options?.undefinedMembersAbsent === true;\n // Explicit work stack, so a deep document does not consume the call\n // stack. `ancestors` holds the containers on the current root-to-node\n // path; a container reached again through its own subtree is a cycle\n // (a container shared by two branches is fine, as in JSON.stringify).\n const pending: Array<Pending | { readonly exit: object }> = [\n { value, parent: undefined, key: undefined, depth: 1 },\n ];\n const ancestors = new Set<object>();\n while (pending.length > 0) {\n const next = pending.pop()!;\n if (\"exit\" in next) {\n ancestors.delete(next.exit);\n continue;\n }\n const current = next.value;\n if (typeof current === \"string\" || typeof current === \"boolean\" || current === null) {\n continue;\n }\n if (typeof current === \"number\") {\n if (Number.isFinite(current)) {\n continue;\n }\n return refuse(verb, next, String(current), NON_FINITE_RESOLUTION);\n }\n if (current === undefined) {\n // A missing array element (a hole) reads as `undefined` too.\n const elementOrMember = typeof next.key === \"number\";\n return refuse(\n verb,\n next,\n \"undefined\",\n elementOrMember ? UNDEFINED_ELEMENT_RESOLUTION : UNDEFINED_MEMBER_RESOLUTION,\n );\n }\n if (typeof current !== \"object\") {\n return refuse(verb, next, `a ${typeof current}`, NON_JSON_TYPE_RESOLUTION);\n }\n if (ancestors.has(current)) {\n return refuse(verb, next, \"a circular reference\", CIRCULAR_RESOLUTION);\n }\n if (next.depth > MAX_DOCUMENT_DEPTH) {\n return refuseDepth(verb, next);\n }\n if (hasJsonHook(current)) {\n return refuse(verb, next, \"an object with a toJSON hook\", TO_JSON_RESOLUTION);\n }\n if (Array.isArray(current)) {\n ancestors.add(current);\n pending.push({ exit: current });\n // Pushed in reverse so the first offending element is reported first.\n for (let i = current.length - 1; i >= 0; i--) {\n pending.push({ value: current[i], parent: next, key: i, depth: next.depth + 1 });\n }\n continue;\n }\n // The root may be any object: a write copies its own enumerable fields\n // (`{ ...doc }`), so only nested values must be plain. An object from\n // another realm (a `vm` context, an iframe) fails this check too.\n const prototype: unknown = Object.getPrototypeOf(current);\n if (next.parent !== undefined && prototype !== Object.prototype && prototype !== null) {\n const name = (current as { constructor?: { name?: unknown } }).constructor?.name;\n return refuse(\n verb,\n next,\n typeof name === \"string\" && name !== \"\"\n ? `a ${name}, not a plain object`\n : \"not a plain object\",\n NON_PLAIN_RESOLUTION,\n );\n }\n ancestors.add(current);\n pending.push({ exit: current });\n const keys = Object.keys(current);\n for (let i = keys.length - 1; i >= 0; i--) {\n const key = keys[i]!;\n const member = (current as Record<string, unknown>)[key];\n if (\n member === undefined &&\n (undefinedMembersAbsent || (key === \"_id\" && next.parent === undefined))\n ) {\n continue;\n }\n pending.push({ value: member, parent: next, key, depth: next.depth + 1 });\n }\n }\n};\n","import { MAX_DOCUMENT_BYTES } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\n\nconst utf8Encoder = new TextEncoder();\n\n// Kept apart from `document-input.ts`: the HTTP client bundles that module\n// for its pre-send value check, and the size cap is the server's to enforce.\nconst DOCUMENT_SIZE_RESOLUTION = `Keep each document at or under ${MAX_DOCUMENT_BYTES} bytes (1 MiB) of JSON: move large or growing data (attachments, long histories, arrays that keep growing) into rows of their own, or store blobs outside the database and keep a reference.`;\n\n/**\n * UTF-8 byte length of `json` when it is over `limit`, else `undefined`.\n * Skips the encode when the string is short enough to decide it: a UTF-16\n * code unit encodes to at most 3 bytes.\n */\nconst jsonByteLengthAbove = (json: string, limit: number): number | undefined => {\n if (json.length * 3 <= limit) {\n return undefined;\n }\n const bytes = utf8Encoder.encode(json).byteLength;\n return bytes > limit ? bytes : undefined;\n};\n\n/**\n * Refuse a post-image larger than {@link MAX_DOCUMENT_BYTES} once encoded\n * as stored (`encodeJsonBytes`, which sorts nothing, so key order does not\n * change the size). Call it on the whole document a write would commit,\n * not on an update patch: a small patch can still grow a row past the cap.\n * A row already stored larger is not checked here; only a write producing\n * an over-cap post-image is refused.\n *\n * I/O-free. The value must already be in the JSON document domain (see\n * `assertDocumentValues`); a value `JSON.stringify` cannot encode\n * throws its own error.\n *\n * @param verb the calling verb, used as the message prefix.\n * @throws BaerlyError code=\"InvalidConfig\" — the encoded post-image is over\n * the cap. The message states its size and the limit.\n */\nexport const assertDocumentSize = (value: unknown, verb: string): void => {\n const bytes = jsonByteLengthAbove(JSON.stringify(value), MAX_DOCUMENT_BYTES);\n if (bytes !== undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: the document encodes to ${bytes} bytes of JSON, over the ${MAX_DOCUMENT_BYTES}-byte (1 MiB) document limit`,\n { resolution: DOCUMENT_SIZE_RESOLUTION },\n );\n }\n};\n","import { FORBIDDEN_MERGE_KEYS } from \"./constants.ts\";\n\n/**\n * The shape constraint for documents stored in a {@link Collection}.\n *\n * Plain JSON object: string-keyed; values are strings, numbers,\n * booleans, nested {@link DocumentData}, or arrays of\n * {@link DocumentValue}.\n *\n * The document **body** itself must be an object (not an array) —\n * baerly-storage's writer is built on JSON Merge Patch (RFC 7386), which\n * is only defined over object documents. Array *values* at any\n * nested level are fine; per RFC 7386, an array in a patch\n * replaces the target array wholesale (baerly-storage has no array-merge\n * semantics).\n */\nexport type DocumentData = { [x: string]: DocumentValue };\n\n/**\n * A single field value inside a {@link DocumentData}. The recursive\n * type that backs {@link DocumentData}, also used by predicate and\n * order-spec types in `@baerly/protocol/query`.\n *\n * Arrays are valid values; they are replaced (not merged) on patch.\n */\nexport type DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>;\n\n/**\n * The patch an `update` takes for a row of type `T`: a JSON Merge Patch\n * (RFC 7396), typed against the row.\n *\n * - Every key is optional; a key left out is left unchanged.\n * - An optional key also accepts `null`, which deletes the field.\n * A required key does not: remove it with `replace` instead.\n * - A required object member with a single object type accepts a nested\n * `MergePatch`, merged field by field. Union-valued members require a\n * whole value because the current value may belong to another variant.\n * - An optional plain-object member takes its whole value or `null`,\n * never a nested patch: to change part of an optional object, pass\n * the whole object or use `replace`.\n * - Arrays and scalars replace the stored value whole; array elements\n * are never merged.\n *\n * Supplying a whole object still merges its fields; use `replace` to\n * discard existing fields. Values must be plain JSON at runtime; this\n * structural type cannot distinguish data-only classes from interfaces.\n *\n * On an unbound collection (`T` is `DocumentData`) every key is\n * optional, so any field accepts a value, a nested patch or `null`.\n *\n * @example\n * ```ts\n * type Ticket = {\n * title: string;\n * note?: string;\n * meta: { owner: string; reviewer?: string };\n * extra?: { flag?: boolean };\n * };\n *\n * const patch: MergePatch<Ticket> = {\n * note: null, // deletes `note`\n * meta: { reviewer: null }, // merges into the required `meta`\n * extra: { flag: true }, // supplies the whole optional object\n * };\n * // @ts-expect-error — `title` is required; use `replace` to remove it\n * const bad: MergePatch<Ticket> = { title: null };\n * ```\n */\nexport type MergePatch<T> = {\n [K in keyof T]?: string extends K\n ? MergePatchObjectValue<T[K]> | null\n : {} extends Pick<T, K>\n ? T[K] | null\n : MergePatchValue<T[K]>;\n};\n\n/**\n * Only a single object type guarantees that required nested fields\n * already exist. A union may switch variants, so it takes a whole value.\n */\ntype MergePatchValue<V> = true extends IsUnion<V> ? V : MergePatchObjectValue<V>;\n\ntype IsUnion<T, Whole = T> = T extends Whole ? ([Whole] extends [T] ? false : true) : never;\n\n/** Index-signature values stay permissive, including nested patches. */\ntype MergePatchObjectValue<V> = V extends readonly unknown[]\n ? V\n : V extends object\n ? MergePatch<V>\n : V;\n\nexport type JSONObject = { [x: string]: JSONValue };\nexport type JSONValue = string | number | boolean | null | JSONObject | Array<JSONValue>;\n\n/**\n * Structural equality of two JSON values.\n *\n * Both inputs must already be JSON-normalized, i.e. the result of a\n * `JSON.parse` — typically `JSON.parse(JSON.stringify(body))` compared\n * against a stored row decoded from JSON. The round-trip drops\n * `undefined` properties (as the write path's encoder does) and turns\n * `-0` into `0`; that normalization is the caller's responsibility.\n * Raw inputs holding `undefined` or `-0` are outside the contract.\n *\n * Uses an explicit work stack so comparison does not consume the\n * JavaScript call stack with each nesting level. No depth cap is enforced.\n *\n * - Object key order is ignored; the key sets must match exactly.\n * - Arrays compare element-wise in order, and an array is never equal\n * to an object (`[1]` vs `{\"0\":1}` is `false`).\n * - Primitives compare with `===`.\n *\n * Deliberately not `deepEqualDocumentValue`, which cannot tell an array\n * from an index-keyed object.\n */\nexport function jsonValueEqual(a: JSONValue, b: JSONValue): boolean {\n const pending: Array<[JSONValue, JSONValue]> = [[a, b]];\n while (pending.length > 0) {\n const [left, right] = pending.pop()!;\n if (left === right) {\n continue;\n }\n if (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) {\n return false;\n }\n if (Array.isArray(left)) {\n if (!Array.isArray(right) || left.length !== right.length) {\n return false;\n }\n // Indexed loop, not `every`: `every` skips holes, which would make a\n // sparse array compare asymmetrically.\n for (let i = 0; i < left.length; i++) {\n pending.push([left[i]!, right[i]!]);\n }\n continue;\n }\n if (Array.isArray(right)) {\n return false;\n }\n const keys = Object.keys(left);\n if (keys.length !== Object.keys(right).length) {\n return false;\n }\n for (const key of keys) {\n if (!Object.prototype.hasOwnProperty.call(right, key)) {\n return false;\n }\n pending.push([left[key]!, right[key]!]);\n }\n }\n return true;\n}\n\nconst isPlainObject = (value: DocumentValue | undefined): value is DocumentData =>\n // Stryker disable next-line ConditionalExpression: `value !== null` is a defensive guard — null\n // is not in DocumentValue; null patches are caught by the `patch === null` early-return before\n // isPlainObject is called. Replacing `value !== null` with `true` is equivalent for all\n // reachable call sites: genuine dead-branch equivalence.\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Apply a JSON Merge Patch to a document, exactly as RFC 7396 §2 defines\n * it. This is what `update` commits: `applyMergePatch(row, patch)`.\n *\n * An object patch merges key by key into the target, or into `{}` when\n * the target is absent or not an object. A `null` member deletes that\n * key, at every depth, so a patch never stores a `null` member: under an\n * absent field, `{ meta: { a: 1, b: null } }` stores `meta: { a: 1 }`.\n * A scalar or array patch replaces the target whole; arrays are opaque\n * values, so a `null` inside one is kept. An `undefined` member is\n * absent, as in the patch's JSON form.\n *\n * Two values outside RFC 7396's JSON domain: an `undefined` patch is the\n * identity (returns `target`), and a `null` patch at the root returns\n * `undefined`, since a document cannot be `null`.\n *\n * `__proto__`, `constructor` and `prototype` members are skipped\n * (`FORBIDDEN_MERGE_KEYS`). Recursion follows the patch, whose depth\n * `assertDocumentValues` caps at `MAX_DOCUMENT_DEPTH` before `update`\n * applies it.\n */\nexport function applyMergePatch<T extends DocumentValue>(\n target: T | undefined,\n patch: Partial<T> | null | undefined,\n): T | undefined {\n if (patch === undefined) {\n return target;\n }\n if (patch === null) {\n return undefined;\n }\n if (!isPlainObject(patch as DocumentValue)) {\n return patch as T;\n }\n // An absent or non-object target merges as `{}` (RFC 7396 §2).\n const combined: DocumentData = isPlainObject(target) ? { ...target } : {};\n const members = patch as Record<string, DocumentValue | null | undefined>;\n for (const key of Object.keys(members)) {\n // Object.keys returns own enumerable string keys — but `__proto__`\n // is an own property when patches arrive via JSON.parse (HTTP PATCH\n // bodies hit this path through query.ts:runUpdate). Guard remains\n // load-bearing. See predicate.test.ts for the same vector.\n if (FORBIDDEN_MERGE_KEYS.has(key)) {\n continue;\n }\n const value = members[key];\n if (value === undefined) {\n continue;\n }\n if (value === null) {\n delete combined[key];\n } else {\n combined[key] = applyMergePatch(combined[key], value)!;\n }\n }\n return combined as T;\n}\n\n/**\n * Coalesce two merge patches into one: the summary patch for `earlier`\n * followed by `later`. Folding from `undefined`,\n * `fold(coalesceMergePatches, undefined, patches)` summarizes a window.\n *\n * Unlike {@link applyMergePatch}, an object patch over an absent or\n * non-object accumulator is taken as written, nulls included, so\n * `coalesceMergePatches(undefined, { x: null })` keeps the delete as\n * `{ x: null }`. The summary is exact only inside the type-stable window\n * `docs/spec/json-merge-patch.md` (\"Log can be coalesced\") describes: a\n * `later` delete of a key `earlier` set removes it from the summary, and\n * a delete followed by an object re-add cannot be expressed. No runtime\n * path coalesces patches today; `update` commits full post-images.\n */\nexport function coalesceMergePatches<T extends DocumentValue>(\n earlier: T | undefined,\n later: Partial<T> | null | undefined,\n): T | undefined {\n if (later === undefined) {\n return earlier;\n }\n if (later === null) {\n return undefined;\n }\n\n // Later patch is primitive or an array → replace wholesale.\n if (!isPlainObject(later as DocumentValue)) {\n return later as T;\n }\n // Later patch is a plain object but the accumulator isn't → take it\n // as written, so its deletes survive.\n if (!isPlainObject(earlier)) {\n return later as T;\n }\n\n const combined = { ...(earlier as DocumentData) } as T;\n for (const key of Object.keys(later) as Array<Extract<keyof T, string>>) {\n if (FORBIDDEN_MERGE_KEYS.has(key)) {\n continue;\n }\n if (later[key] === null) {\n delete combined[key];\n } else {\n combined[key] = coalesceMergePatches(\n earlier[key] as DocumentValue,\n later[key] as DocumentValue,\n ) as T[Extract<keyof T, string>];\n }\n }\n return combined as T;\n}\n","import { BaerlyError, CODE_RESOLUTIONS, type DocumentData, jsonValueEqual } from \"@baerly/protocol\";\nimport { markCallerFacing } from \"./caller-facing-error.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\nimport { assertNfcSegment, assertPathSegment, assertWellFormedSegment } from \"./path-segment.ts\";\n\n/**\n * Resolution for a non-NFC `_id`. A row stored under one by an earlier\n * release stays readable and deletable, so it is migrated by copy.\n */\nconst DOC_ID_NFC_RESOLUTION =\n 'Pass id.normalize(\"NFC\") for a new _id. To migrate a stored non-NFC row, insert a copy under a fresh NFC id that is not canonically equivalent to the original (for example, omit _id for a UUID), then delete the original.';\n\n/**\n * Resolution for an `_id` with an unpaired surrogate. A row stored under\n * one by an earlier release stays readable and deletable in-process, so it\n * is migrated by copy.\n */\nconst DOC_ID_WELL_FORMED_RESOLUTION =\n \"Pass an _id with no unpaired UTF-16 surrogate (id.isWellFormed() is true), or omit _id for a UUID. To migrate a stored row with such an _id, read it by _id, remove _id from the copy so insert generates a fresh UUID, then delete the original.\";\n\n/**\n * Resolution for a point read whose id no row can be stored under.\n */\nconst READ_ID_RESOLUTION =\n 'Pass the _id string of a stored row. A valid _id is non-empty, at most 256 UTF-8 bytes, has no \"/\" or control characters, does not start with \"_\", and is not \".\" or \"..\".';\n\n/**\n * Guard an `_id` a write is about to store a row under: an insert, a\n * replace, an update, or any `I` / `U` commit. The `_id` analogue of\n * `assertKeySegment` (`db.ts`).\n *\n * Applies {@link assertStoredDocId}, then requires the id to be\n * well-formed UTF-16 (no unpaired surrogate, which no URL or S3 key can\n * carry) and in Unicode Normalization Form C (`id === id.normalize(\"NFC\")`),\n * so each canonical-equivalence class (NFC `é` and NFD `e` + U+0301) has one\n * spelling and one byte form. R2 stores canonically-equivalent keys as one\n * object, so any object a future format keys by `_id` (an index-aware\n * snapshot, say) would otherwise merge two rows whose ids differ only by\n * normalization; the rule keeps that door open, and loosening it later is\n * not a breaking change. Case and compatibility variants (`A` / `a`, `fi` / `fi`)\n * are distinct NFC strings and stay distinct ids.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the id breaks the key-segment\n * rule, holds an unpaired surrogate, or is not NFC.\n */\nexport const assertDocId = (id: string): void => {\n assertStoredDocId(id);\n assertWellFormedSegment(id, \"_id\", \"\", DOC_ID_WELL_FORMED_RESOLUTION);\n assertNfcSegment(id, \"_id\", \"\", DOC_ID_NFC_RESOLUTION);\n};\n\n/**\n * Guard an `_id` that names an existing row: the `doc_id` of a delete.\n * Only the key-segment rule applies (the single shared\n * {@link assertPathSegment}: empty / `\"/\"` / `\".\"`|`\"..\"` / C0-C1 control\n * chars / leading `\"_\"` (ADR-003) / overlong, all as\n * `BaerlyError{code:\"InvalidConfig\"}`), so a row stored under a non-NFC\n * id, or an id with an unpaired surrogate, before {@link assertDocId}\n * refused them can still be deleted.\n */\nexport const assertStoredDocId = (id: string): void => {\n assertPathSegment(id, \"_id\");\n};\n\n/**\n * Guard the `id` of a point read (`Collection.get`, `GET\n * /v1/c/:collection/:id`) before any I/O. Applies the stored-id rule\n * ({@link assertStoredDocId}), not the NFC or well-formed write rules, so\n * a row an earlier release stored under such an id stays readable. The error is marked\n * caller-facing so HTTP returns its message with the 400.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `id` is not a string or breaks\n * the key-segment rule.\n */\nexport const assertReadDocId = (id: string): void => {\n let message: string | undefined;\n if (typeof id !== \"string\") {\n message = `get: _id must be a string, got ${typeof id}`;\n } else {\n try {\n assertPathSegment(id, \"_id\", \"get\");\n } catch (error) {\n if (!(error instanceof BaerlyError)) {\n throw error;\n }\n message = error.message;\n }\n }\n if (message !== undefined) {\n throw markCallerFacing(\n new BaerlyError(\"InvalidConfig\", message, { resolution: READ_ID_RESOLUTION }),\n );\n }\n};\n\n/**\n * The `AlreadyExists` an insert throws when a live row holds `docId`.\n * Shared by `runInsert`'s check read (`./query.ts`) and the writer's\n * insert guard (`./writer.ts`), so a caller sees one error whichever\n * side caught the collision. Not retriable; `err._id` is `docId`.\n */\nexport const insertAlreadyExists = (collection: string, docId: string): BaerlyError =>\n new BaerlyError(\n \"AlreadyExists\",\n `insert: _id ${JSON.stringify(docId)} already exists in collection ${JSON.stringify(collection)}`,\n { resolution: CODE_RESOLUTIONS.AlreadyExists, _id: docId },\n );\n\n/**\n * `true` when the stored live row `stored` is the row an insert of `body`\n * would have written: structurally equal after the JSON round-trip the\n * write path's encoder applies (key order ignored, `undefined` properties\n * dropped). `body` is the insert's post-image `{ ...doc, _id }`; the\n * stored row carries no other server-stamped field (log metadata lives on\n * the `LogEntry`, not in `after`).\n *\n * Shared by `runInsert`'s check read and the writer's insert guard, so an\n * SDK-minted insert replays on the same rule whichever side found the row.\n */\nexport const insertReplaysRow = (body: DocumentData, stored: DocumentData | undefined): boolean =>\n stored !== undefined && jsonValueEqual(JSON.parse(JSON.stringify(body)), stored);\n\n/**\n * Count an SDK-minted insert answered as a replay of its stored row on\n * `db.write.insert_replayed_total` (labelled by `collection`). A replay\n * commits nothing and records no write metric, so without this counter it\n * is invisible on the canonical line. Shared by `runInsert`'s check read\n * and the writer's insert guard, the two places a replay is decided.\n */\nexport const recordInsertReplay = (collection: string): void => {\n getCurrentContext()?.recorder.counter(\"db.write.insert_replayed_total\", 1, { collection });\n};\n","import { BaerlyError, MAX_KEY_BYTES } from \"@baerly/protocol\";\n\nconst utf8 = new TextEncoder();\n\n/**\n * Reject an assembled object key over the S3/R2 full-key ceiling\n * ({@link MAX_KEY_BYTES}) as `InvalidConfig`. Per-segment caps don't\n * bound the sum, and index values skip `assertPathSegment` entirely, so\n * this post-encoding check at the writer's PUT sites is their only\n * overflow guard. @see docs/spec/storage-compatibility.md\n */\nexport const assertKeyWithinLimit = (key: string): void => {\n const bytes = utf8.encode(key).length;\n if (bytes > MAX_KEY_BYTES) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `object key exceeds ${MAX_KEY_BYTES} bytes (got ${bytes}): ${JSON.stringify(key.slice(0, 80))}…`,\n );\n }\n};\n","/**\n * Self-session log-conflict adoption — the one decision that\n * distinguishes a retry of our own prior commit attempt from a\n * peer racing us at the same `seq`.\n *\n * Background. `Writer.#singleAttemptCommit` creates each log entry\n * with `If-None-Match: \"*\"` — and that create IS the commit. A 412 on\n * `/log/<seq>.json` can mean either\n *\n * (a) a peer genuinely won that seq (a foreign entry is committed\n * there); or\n * (b) our OWN previous attempt landed the committing log create but\n * its ack was lost — we never observed the `200` — and we're now\n * re-driving the same logical commit.\n *\n * This function makes the (a)/(b) call. It is callable, separately\n * testable, and patent-disclosable in isolation from the rest of the\n * commit path.\n *\n * ## Soundness invariant\n *\n * Adoption is sound iff all three hold:\n *\n * 1. **Same session.** `existing.session === self.session`. The\n * session id is a per-commit, in-RAM-only secret minted at\n * `Writer.commit` from `crypto.randomUUID().slice(0,\n * SESSION_ID_LENGTH)`; an adversary with bucket-write access\n * can forge any other field but cannot forge a value they\n * did not observe being PUT.\n * 2. **Matching seq.** `existing.seq === self.expectedSeq`. The\n * seq match is also implied by the key shape (the writer\n * reads `/log/<expectedSeq>.json`), but is re-asserted here\n * so the invariant is visible at the decision site.\n * 3. **Matching write intent.** The occupant's writer-minted log\n * fields match the entry this writer just attempted to create.\n * Same session + same seq alone is not sufficient: a collision,\n * test seam, or out-of-model bucket writer must not be able to\n * make this writer adopt a different logical mutation.\n *\n * When any of (1)/(2)/(3) fails, the caller MUST refuse adoption\n * and treat the occupant as a conflicting committed entry.\n *\n * A fourth precondition — single-input commit — is now structural,\n * not a runtime check: `#singleAttemptCommit` takes one `CommitInput`,\n * so a multi-input commit is unrepresentable. It matters because the\n * single `log/<seq>` create is the all-or-nothing commit point, so\n * per-input adoption decisions could not compose.\n *\n * ## Threat model\n *\n * The adversary may (a) write arbitrary bytes to any key in the\n * bucket, (b) replay any PUT they previously observed on the wire,\n * (c) reorder or drop network packets between the writer and the\n * bucket. The adversary may NOT (d) read the writer's local RAM\n * and therefore cannot learn the per-commit `session` id before\n * observing the writer's own `/log/<seq>.json` PUT. Under these\n * constraints, conditions (1)+(2)+(3) close every attack path in\n * the adversarial-replay property test\n * (`tests/integration/log-conflict-adversarial.test.ts`).\n *\n * **Pinned by:** `tests/integration/log-conflict-forgery.test.ts`\n * exercises the session-id-unguessability claim under a\n * `ForgeryStorage` adversary that plants arbitrary entries at the\n * writer's expected log key. Property verified by default at\n * `numRuns: 1000`; `FC_NUM_RUNS=10000` for the hardening sweep.\n *\n * ## Prior art\n *\n * SlateDB's manifest-pivot writer protocol (rfcs/0001-manifest.md,\n * scenarios 1–4) is the closest published prior art on the broader\n * commit-protocol skeleton. SlateDB's scenario 3 — \"conflicting SST\n * has same `writer_epoch` as me\" — is explicitly labelled an\n * **illegal state that should panic**. The three-clause adoption\n * decision encoded here (same session ∧ matching seq ∧ matching intent)\n * recognises that case as the writer's own prior in-flight attempt\n * and adopts it as success rather than aborting, closing the recovery\n * gap SlateDB leaves to operator intervention.\n *\n * Apache Iceberg and Delta Lake commits surface analogous failures as\n * `CommitFailedException` / commit-conflict retries; neither inspects\n * the conflicting object to determine ownership.\n *\n * See `docs/spec/prior-art.md` for the wider prior-art comparison.\n *\n * @see docs/spec/sync-protocol.md §\"Contention and retries\"\n */\n\nimport type { LogEntry } from \"@baerly/protocol\";\n\n/**\n * Inputs to {@link tryAdoptOwnSessionLogEntry}. All fields are\n * required; the writer constructs this struct at the call site.\n */\nexport interface AdoptionContext {\n /**\n * The entry the writer just attempted to PUT. Carries the\n * writer's session, expected seq, and the rest of the LogEntry\n * shape minted in `Writer.#singleAttemptCommit` step 3.\n */\n readonly self: LogEntry;\n /**\n * The entry currently stored at `/log/<self.seq>.json`, as read\n * back after a 412. The caller is responsible for the GET (the\n * function is pure, no I/O).\n */\n readonly existing: LogEntry;\n}\n\n/**\n * Discriminated outcome of {@link tryAdoptOwnSessionLogEntry}.\n * `adopt: true` carries the existing entry (which by the invariant\n * matches `self` on writer-minted intent fields); the caller\n * substitutes it for `self` so the returned `CommitResult` matches\n * what's actually stored. `adopt: false` carries a machine-readable\n * `reason` so callers and tests can discriminate which clause of the\n * invariant failed.\n */\nexport type AdoptionDecision =\n | { readonly adopt: true; readonly entry: LogEntry }\n | {\n readonly adopt: false;\n readonly reason: \"foreign-session\" | \"wrong-seq\" | \"intent-mismatch\";\n };\n\n/**\n * Decide whether the entry already at `/log/<seq>.json` is the\n * writer's own prior in-flight attempt and may be adopted. Pure\n * function; no I/O. The caller performs the GET (when the log PUT\n * surfaces 412) and passes the read-back body in `ctx.existing`.\n *\n * ## Correctness precondition\n *\n * A fresh `session` id is minted per `commit()` call, seq-stable\n * across that call's retries. Adoption compares the writer-minted\n * intent/body fields as well as session and seq: a dropped-ack retry\n * reuses the same attempted entry and adopts, while a same-session /\n * same-seq occupant carrying a different logical mutation is treated as\n * a conflict and skipped by the caller's forward-probe loop.\n *\n * @see {@link AdoptionDecision} for the return shape.\n * @see The soundness invariant in this module's header docstring.\n */\nexport const tryAdoptOwnSessionLogEntry = (ctx: AdoptionContext): AdoptionDecision => {\n // Clause (1) — same session.\n if (ctx.existing.session !== ctx.self.session) {\n return { adopt: false, reason: \"foreign-session\" };\n }\n // Clause (2) — matching seq. The seq is also implied by the\n // key the caller read from, but re-asserted here for\n // patent-disclosure clarity.\n if (ctx.existing.seq !== ctx.self.seq) {\n return { adopt: false, reason: \"wrong-seq\" };\n }\n // Clause (3) — matching write intent: full-entry equality, including\n // `commit_ts`. A legitimate lost-ack self-retry passes this ONLY under\n // two premises:\n // P1 (single mint): `commit_ts`/`lsn`/`session` are minted once per\n // slot in `#singleAttemptCommit` (one `Date.now()`), the Writer\n // sends that entry once, and the adapter's retries re-send the same\n // bytes, so a real read-back is byte-identical to `self`,\n // `commit_ts` included.\n // P2 (order-stable round-trip): stored bytes are\n // `encodeJsonBytes` (`JSON.stringify`) and read back via\n // `JSON.parse`; `JSON.stringify(JSON.parse(...))` preserves key\n // order, so the two stringifications match.\n // If either breaks (re-mint on retry, or a canonical/sorting encoder /\n // normalizing read-back), a legit self-retry would falsely mismatch\n // here and DUPLICATE-write. P2 is pinned by `bytes.test.ts`.\n if (JSON.stringify(ctx.existing) !== JSON.stringify(ctx.self)) {\n return { adopt: false, reason: \"intent-mismatch\" };\n }\n return { adopt: true, entry: ctx.existing };\n};\n","import { BaerlyError, type DocumentData } from \"@baerly/protocol\";\nimport type { CodecCode, CodecFail } from \"./snapshot-codec.ts\";\n\nconst throwBaerlyError: CodecFail = (code, message, cause) => {\n throw new BaerlyError(code, `post-image: ${message}`, { cause });\n};\n\n/**\n * Assert that an insert/update post-image names the document it is stored\n * under: `after` is a plain object (prototype `Object.prototype` or `null`,\n * not an array) whose own enumerable data property `_id` is a string\n * `=== docId`.\n *\n * This checks identity only. It does not validate `docId` against the\n * `utf8-scalar-v1` domain, and it does not validate any other field of the\n * document. Callers that need the scalar domain call `assertSnapshotDocId`\n * first.\n *\n * `code` selects the failure polarity: `InvalidConfig` for caller input,\n * `InvalidResponse` for stored input. Failures go through `fail` when given,\n * so a codec keeps its own message prefix; otherwise this throws a\n * `BaerlyError` with `code`.\n */\nexport function assertPostImageIdentity(\n docId: string,\n after: unknown,\n code: CodecCode,\n fail: CodecFail = throwBaerlyError,\n): asserts after is DocumentData {\n if (after === null || typeof after !== \"object\" || Array.isArray(after)) {\n fail(code, \"after must be a document object\");\n }\n const prototype = Object.getPrototypeOf(after);\n if (prototype !== Object.prototype && prototype !== null) {\n fail(code, \"after must be a plain object\");\n }\n const descriptor = Object.getOwnPropertyDescriptor(after, \"_id\");\n if (descriptor === undefined || !descriptor.enumerable || !(\"value\" in descriptor)) {\n fail(code, \"after._id must be an own enumerable data property\");\n }\n if (typeof descriptor.value !== \"string\" || descriptor.value !== docId) {\n fail(code, \"after._id must equal doc_id\");\n }\n}\n","/**\n * `Writer` — stateless multi-instance write engine (single-write commit).\n *\n * Each {@link Writer.commit} reads `current.json` FRESH (for\n * `log_seq_start` / `tail_hint` as a probe FLOOR — a lower bound, NOT a\n * CAS precondition), then **creates `log/<seq>` via `If-None-Match: \"*\"`.\n * That create IS the commit / linearization point.** The writer writes NOTHING to `current.json` on the commit\n * path; `tail_hint` advances outside ordinary commits via compaction\n * folds, write-tick refreshes, and explicit operator/import paths. The\n * commit model and its invariants are recorded in ADR-004\n * (`docs/adr/004-single-write-commit.md`). The\n * optional integrity walk is gated by\n * {@link WriterOptions.verifyLogIntegrityOnCommit} (default off).\n *\n * No per-write cache: every commit re-reads + re-probes, so N stateless\n * instances contend at one place — the `If-None-Match` create of\n * `log/<seq>`. The loser gets a 412 and re-probes forward to the next\n * empty slot. A 412 from the writer's OWN session at the same seq is its\n * own lost-ack / crashed-but-durable commit → adopted (not retried), so\n * the write lands at EXACTLY `seq`, never duplicated.\n *\n * **First insert wins.** An `I` carrying {@link CommitInput.insertGuard}\n * reads the log window its caller's absence check could not see and\n * refuses to commit over a live row a peer's `I` put there\n * (`AlreadyExists`), so of concurrent inserts of one `doc_id` at most one\n * commits (exactly one, absent storage failures). See {@link InsertGuard}\n * and `docs/spec/sync-protocol.md` §\"Insert: the first `I` wins\".\n *\n * **Caller re-decisions.** A {@link CommitAdmission} re-runs the caller's\n * decision over the same window; its verdict may replace a `U`'s\n * post-image, which the write verbs use to re-apply an update to the\n * newest version of its row. See {@link CommitVerdict} and\n * `docs/spec/sync-protocol.md` §\"Update and delete: decided on the newest\n * row version\".\n *\n * **Crash safety.** The `log/<seq>` create is the commit's only write.\n * `LogEntry.after` is the authoritative post-image, so a crash before the\n * create leaves nothing of the commit on the bucket, and a crash after it\n * leaves a durable commit. The writer maintains no secondary objects:\n * declared indexes change no storage call (ADR-004 Q4, superseded in 0.7).\n *\n * **`LogEntry` shape.** Emitted entries follow the contract in\n * `packages/protocol/src/log.ts` (see {@link LogEntry}) and\n * `docs/spec/log-entry-shape.md`. The on-bucket key is\n * `log/<seq>.json` (the integer `seq` is the load-bearing\n * identifier; the `lsn` string is schema-only).\n *\n * @see docs/spec/sync-protocol.md for the protocol invariants this\n * loop preserves.\n * @see docs/spec/log-entry-shape.md for the per-field contract.\n */\n\nimport {\n CURRENT_JSON_SCHEMA_VERSION,\n assertDocumentSize,\n CODE_RESOLUTIONS,\n COMMIT_RESOLUTION_RESERVE,\n type CurrentJson,\n type CurrentJsonRead,\n type DocumentData,\n type LogEntry,\n type MetricsRecorder,\n certifiedDeleteFloor,\n createCurrentJson,\n decodeJsonBytes,\n encodeJsonBytes,\n logObjectKey,\n logSeqStartOf,\n mintGeneration,\n BaerlyError,\n isWriteConflict,\n noopMetricsRecorder,\n type Storage,\n LOG_FORWARD_PROBE_CAP,\n MAX_PARALLEL_LOG_READS,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_TAIL_HINT_REFRESH_WRITES,\n SESSION_ID_LENGTH,\n STORAGE_RETRY_MAX_ATTEMPTS,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n} from \"@baerly/protocol\";\nimport {\n assertDocId,\n assertStoredDocId,\n insertAlreadyExists,\n insertReplaysRow,\n recordInsertReplay,\n} from \"./doc-id.ts\";\nimport { assertKeyWithinLimit } from \"./key-limit.ts\";\nimport { walkLogRange } from \"./log-walk.ts\";\nimport { findLogTail, probeTailFrom } from \"./log-tail.ts\";\nimport { tryAdoptOwnSessionLogEntry } from \"./log-conflict-adoption.ts\";\nimport { dispatchWriteTick, shouldFireMaintenance } from \"./maintenance.ts\";\nimport type { InternalBoundedMaintenanceOptions } from \"./maintenance-options.ts\";\nimport { getCurrentContext, runWithContext } from \"./observability/context.ts\";\nimport { assertPostImageIdentity } from \"./post-image-identity.ts\";\nimport { isOwnCollection } from \"./collection-alias.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Tunables for {@link Writer}. All optional.\n *\n * There is no Writer retry knob: the `Storage` adapter retries each\n * request under the one storage retry policy, and the Writer resolves an\n * uncertain log create by occupant readback rather than resending it.\n */\nexport interface WriterOptions {\n /**\n * When `true`, every commit walks the live log range\n * `[log_seq_start, tail_hint)` before minting a new entry, surfacing\n * a missing or malformed entry as `BaerlyError{code:\"Internal\"}`\n * (or `\"InvalidResponse\"` for parse failures). The walk is purely\n * observational — the per-doc fold lives in the read path\n * (`./query.ts`) and any hole inside the visible range would also\n * fire on the next read.\n *\n * Production callers default this OFF: the walk issues `O(tail)`\n * Class-B GETs on every commit. Tests\n * that intentionally puncture bucket state to exercise the\n * invariant trigger opt in by passing `true`.\n *\n * Default `false`.\n */\n readonly verifyLogIntegrityOnCommit?: boolean;\n}\n\n/**\n * Single-doc mutation request. One `commit()` ↔ one {@link LogEntry}.\n */\nexport interface CommitInput {\n /** The mutation op. Maps directly to {@link LogEntry.op}. */\n readonly op: \"I\" | \"U\" | \"D\";\n\n /** The collection (table) name. Becomes {@link LogEntry.collection}. */\n readonly collection: string;\n\n /**\n * The document primary key. Becomes {@link LogEntry.doc_id}. Must be\n * NFC for `I` / `U`; a `D` accepts any key-safe id, so a row stored\n * under a non-NFC id by an earlier release stays deletable.\n */\n readonly docId: string;\n\n /**\n * For `I` / `U`: the post-image. Becomes {@link LogEntry.after}. Must\n * be `undefined` for `op: \"D\"`.\n */\n readonly body?: DocumentData;\n\n /** Optional ISO-8601 origin marker; becomes {@link LogEntry.origin}. */\n readonly origin?: string;\n\n /**\n * First-insert-wins guard. Valid only with `op: \"I\"`; any other op\n * throws `InvalidConfig` before I/O. See {@link InsertGuard}.\n *\n * @internal — set by `Collection.insert` (`runInsert` in `./query.ts`).\n */\n readonly insertGuard?: InsertGuard;\n\n /**\n * Force the post-commit maintenance tick (main-10 G6): dispatch it even\n * when the ratio-OR-boundary gate is closed, and let it bypass Gate 1\n * inside the runner. Ignored under `BAERLY_MAINTENANCE_DISABLE`.\n *\n * @internal — set by the write verbs in `./query.ts` while a growth\n * write would be refused (`capacityDecision`'s `pressure`).\n */\n readonly forceMaintenance?: boolean;\n\n /**\n * Commit-time re-check of a decision the caller made at a log tail it\n * read (main-10 G5-race). See {@link CommitAdmission}.\n *\n * @internal — set by the write verbs in `./query.ts` for the capacity\n * re-check (`capacityDecision`).\n */\n readonly admission?: CommitAdmission;\n}\n\n/**\n * Backward validation of a caller's decision, like {@link InsertGuard}\n * but with the decision supplied by the caller. The caller decided to\n * commit from the collection state folded through log tail `fromSeq`.\n * The writer reads every log entry in `[fromSeq, seq)` (the same window\n * read as the insert guard, shared with it when both are set) and passes\n * it to `check` before the first create, and again with the longer\n * window after each lost create race, before the next create.\n * `check` throws to refuse; nothing is committed. It may instead return a\n * {@link CommitVerdict} whose `body` replaces a `U`'s post-image: the\n * write verbs re-apply an update to the newest version of its row this\n * way (EvalPlanQual; `docs/spec/sync-protocol.md` §\"Update and delete:\n * decided on the newest row version\").\n *\n * Precondition: `fromSeq` is a tail a read-path probe observed on this\n * collection's log, or one past a seq the caller's own commit landed at.\n * With an `insertGuard`, it must equal `absentBelowSeq`.\n *\n * @internal\n */\nexport interface CommitAdmission {\n /** The log tail the caller's decision folded through. */\n readonly fromSeq: number;\n /**\n * Re-decide over `window`, every entry in `[fromSeq, tail)` in seq\n * order, where `tail` is the slot the next create targets. Throw to\n * refuse the commit. The verdict of the last call before the winning\n * create decides what commits; `undefined` keeps the input as given.\n */\n readonly check: (\n window: readonly LogEntry[],\n tail: number,\n ) => CommitVerdict | undefined | Promise<CommitVerdict | undefined>;\n}\n\n/**\n * What a {@link CommitAdmission.check} call decided.\n *\n * @internal\n */\nexport interface CommitVerdict {\n /**\n * Force the post-commit maintenance tick, as\n * {@link CommitInput.forceMaintenance} does.\n */\n readonly forceMaintenance?: boolean;\n /**\n * The post-image to commit instead of {@link CommitInput.body}; valid\n * only on a `U`, and identity-checked like the input body.\n */\n readonly body?: DocumentData;\n}\n\n/**\n * Backward validation for an `I` commit. The caller has already checked\n * that the doc has no live row in the collection state folded through\n * log tail `absentBelowSeq`. The writer then reads every log entry in\n * `[absentBelowSeq, seq)` — the window that check could not see — and\n * refuses the commit with `AlreadyExists` when the last entry for this\n * `(collection, doc_id)` in it is an `I` or `U`. So the first `I` for a\n * `doc_id` wins, and a concurrent later insert commits nothing.\n *\n * With `replayIdentical`, a live last entry whose `after` equals the\n * insert's body is not a collision but this insert's own earlier success\n * (an SDK resending an auto-ID insert): the commit returns that entry and\n * writes nothing.\n *\n * Precondition: `absentBelowSeq` is a tail observed on this\n * collection's log by a read-path probe (the first empty slot it found).\n * A value above the true tail would make the writer create past a hole.\n *\n * @internal\n */\nexport interface InsertGuard {\n /** The log tail the caller's absence check folded through. */\n readonly absentBelowSeq: number;\n /**\n * Treat a live `I` / `U` for the doc whose `after` equals the body\n * (`insertReplaysRow`) as this insert's original success: return it\n * as the commit result, with no create and no maintenance tick. Set only for an\n * SDK-minted `_id` (`runInsert`'s `mintedId`); a caller-chosen `_id`\n * keeps strict `AlreadyExists`. Default `false`.\n */\n readonly replayIdentical?: boolean;\n}\n\n/** Return shape of {@link Writer.commit}. */\nexport interface CommitResult {\n /**\n * The committed `LogEntry`. Caller can ack on `entry.lsn`. For a\n * guarded insert that replayed ({@link InsertGuard.replayIdentical}),\n * it is instead the stored live `I` / `U` in the guarded window whose\n * `after` the body matched, written by an earlier commit, and this call\n * wrote nothing.\n */\n readonly entry: LogEntry;\n\n /**\n * ETag of `current.json` as read at the start of the commit (Step 1),\n * on a replay as on a commit. The commit path never writes\n * `current.json` (the `log/<seq>` create IS the commit), so this is the\n * manifest's pre-commit ETag, not a post-write one.\n */\n readonly currentEtag: string;\n}\n\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Successful outcome of one full {@link Writer.#singleAttemptCommit}\n * attempt: either it committed (`replayed: false`, with the commit's\n * Class A op count), or a guarded insert replayed a stored identical row\n * (`replayed: true`) and committed nothing, so it is not a logical write.\n * Rejected creates resolve by readback or throw non-retriable\n * `AmbiguousCommit`; exceeding the foreign-occupant forward-probe budget\n * throws `Internal`. Failures before dispatching the create, and a\n * definitive rejection of the slot's only send, propagate.\n */\ntype SingleAttemptSuccess =\n | {\n readonly replayed: false;\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: number;\n }\n | {\n readonly replayed: true;\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n };\n\n/**\n * Stateless write engine for the multi-instance core.\n *\n * Construction is cheap and performs zero I/O — adapters build a\n * fresh `Writer` per request and discard it. All real work\n * happens in {@link commit}.\n *\n * @example\n * ```ts\n * import { Writer } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const writer = new Writer({\n * storage: new MemoryStorage(),\n * currentJsonKey: \"app/tickets/tenant/acme/manifests/tickets/current.json\",\n * });\n *\n * const result = await writer.commit({\n * op: \"I\",\n * collection: \"tickets\",\n * docId: \"doc-1\",\n * body: { _id: \"doc-1\", title: \"hello\" },\n * });\n * console.log(result.entry.seq);\n * ```\n */\nexport class Writer {\n readonly #storage: Storage;\n readonly #currentJsonKey: string;\n readonly #verifyLogIntegrityOnCommit: boolean;\n\n constructor(opts: {\n storage: Storage;\n /**\n * Full bucket-relative key of the CAS pointer, e.g.\n * `app/tickets/tenant/acme/manifests/tickets/current.json`. The\n * collection-prefix half lives at\n * `currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"))` — the\n * log keys are derived from it.\n */\n currentJsonKey: string;\n options?: WriterOptions;\n }) {\n this.#storage = opts.storage;\n this.#currentJsonKey = opts.currentJsonKey;\n this.#verifyLogIntegrityOnCommit = opts.options?.verifyLogIntegrityOnCommit ?? false;\n }\n\n /**\n * Atomically commit one mutation. Reads `current.json` fresh (as a\n * probe FLOOR, not a CAS precondition), then creates `log/<seq>` via\n * `If-None-Match: \"*\"` — that create IS the commit (single-write\n * commit; no `current.json` CAS follows it).\n *\n * The hot-path cost under no contention is 3 GETs + 1 PUT, whatever\n * indexes the collection declares: the Step 1 `current.json` read,\n * `findLogTail`'s forward probe (one 404 GET when `tail_hint` is\n * accurate, `O(log gap)` GETs when it lags a fold interval), the\n * committing `log/<seq>` create, and the post-create `current.json`\n * re-read that rejects a create landing below the certified delete\n * floor (`#assertCommitAboveDeleteFloor`). A peer that won the slot\n * costs one occupant readback GET, the forward probe's GETs, and one\n * more create at the next slot.\n *\n * Idempotency: `LogEntry.after` carries the full post-image, and the\n * `log/<seq>` create uses `If-None-Match: \"*\"`, so two writers racing\n * the same tail cause\n * exactly one create to win; the loser reads back the occupant,\n * adopts its own lost-ack write or re-probes forward to the next\n * empty slot.\n *\n * **Uncertain commit fate.** If the committing create wins at a\n * `seq` the collection has already certified deleted — reachable when a\n * create PUT or a lost-ack retry straddles a fold plus a retirement pass —\n * the object it wrote is beneath every reader's floor. The commit then fails\n * with `AmbiguousCommit` rather than acknowledging a mutation no fresh\n * reader can see. The writer cannot tell whether an earlier attempt of its\n * own landed and was folded before retirement removed the slot, so the\n * mutation may or may not have been applied. The same uncertainty exists\n * when a rejected create cannot be resolved by reading its slot, including\n * rejections that follow a send of unknown outcome. The Writer never\n * resends a create at the same slot (the adapter already retried it); it\n * reads the slot back once instead. A missing readback does not prove that\n * an earlier send will not land. Exact own-entry readback is adopted; an\n * unresolved fate throws `AmbiguousCommit` with `err.retriable === false`.\n * Reconcile state before deliberately retrying: a new logical call can\n * duplicate work, including minting a second auto-ID document.\n *\n * @throws BaerlyError code=\"AmbiguousCommit\" when the committing create\n * landed below `min(log_delete_floor, log_seq_start)`, or a possibly\n * durable create could not be resolved. The mutation's fate is unknown;\n * `err._id` is `input.docId`.\n * @throws BaerlyError code=\"Internal\" when a log entry expected in\n * `[0, tail_hint)` is missing — a protocol-invariant violation\n * (compactor bug or stale `current.json`).\n * @throws BaerlyError code=\"InvalidResponse\" when a log-entry body\n * isn't valid JSON.\n * @throws BaerlyError code=\"InvalidConfig\" when `docId` breaks the\n * key-segment rule, when an `I` / `U` `docId` is not NFC, when an\n * `I` / `U` body is not a plain object whose own `_id` is the string\n * `docId`, when an `I` / `U` post-image encodes to more than\n * `MAX_DOCUMENT_BYTES`, or when `insertGuard` is set on a non-`I` op.\n * Checked before any I/O (an admission verdict's replacement\n * post-image is size-checked when it is returned).\n * @throws BaerlyError code=\"AlreadyExists\" when `insertGuard` is set and\n * the log window `[absentBelowSeq, seq)` holds a live `I` / `U` for\n * this doc (unless `replayIdentical` is set and its `after` equals the\n * body, which returns that entry instead). Nothing was committed;\n * `err._id` is `input.docId`.\n * @throws BaerlyError code=\"WriteConflict\" when `insertGuard` or\n * `admission` is set and part of its window was folded and retired (or\n * is longer than `LOG_FORWARD_PROBE_CAP`) before the writer could read\n * it. Nothing was committed; re-read and retry.\n * @throws BaerlyError code=\"CapacityExceeded\" when the request ledger\n * cannot afford this commit's create and `COMMIT_RESOLUTION_RESERVE`,\n * checked before each create; or when the ledger refused the create\n * itself before any attempt was sent (`cause.notApplied`), or any\n * storage call before it. Nothing was committed.\n * @throws whatever `admission.check` throws (the write verbs throw\n * `CapacityExceeded` or `MaintenancePending`). Nothing was committed.\n *\n * **Window cost.** A commit with `insertGuard` or `admission` probes the\n * tail linearly from `max(windowFrom, log_seq_start)` with\n * `probeTailFrom` instead of galloping from\n * `max(log_seq_start, tail_hint)`. Uncontended, `windowFrom` is the\n * tail, so that is one 404 GET. Each entry a peer committed after the\n * caller's read costs one more GET, and if a fold moved `log_seq_start`\n * past `windowFrom`, each folded slot in between costs one GET too.\n *\n * **Implicit provisioning.** When `current.json` does not exist at\n * `currentJsonKey` (fresh bucket, fresh collection), the writer\n * auto-creates it with a zero-state manifest before the commit\n * lands. The cost is one extra Class A PUT on the very first\n * commit per collection; steady-state cost is unchanged. A peer\n * racing the same first-write loses cleanly on the create CAS\n * and re-reads to pick up the winner's manifest.\n */\n async commit(input: CommitInput): Promise<CommitResult> {\n // Validate the doc id BEFORE any I/O so every commit caller — the\n // public write path AND a direct caller like `baerly admin restore`\n // — is covered (defense in depth, mirroring the db-layer guard).\n // Rejects empty / `\"/\"` / `\".\"`|`\"..\"` / control / leading `\"_\"` /\n // overlong `docId` as `BaerlyError{code:\"InvalidConfig\"}`, so a\n // traversal-shaped `_id` can never become a written key segment.\n // An `I` / `U` mints a row identity, so it must also be NFC: one id\n // has one byte form, whatever key canonicalization a backend applies\n // to a future id-keyed object. A `D` only names an existing row, which\n // an earlier release may have stored under a non-NFC id.\n if (input.op === \"D\") {\n assertStoredDocId(input.docId);\n } else {\n assertDocId(input.docId);\n }\n // An `I` / `U` post-image must name the document it is stored under:\n // a plain object whose own `_id` is the string `docId`. Without this,\n // `log/<seq>` would record a row whose `after._id` disagrees with its\n // `doc_id`, and later reads key that row by the wrong id.\n if (input.op !== \"D\") {\n assertPostImageIdentity(input.docId, input.body, \"InvalidConfig\");\n // The committed post-image is bounded, whatever the write path: an\n // in-process call has no body cap, and a merge-patch within one can\n // still grow the row. A `D` is never checked, so a row stored larger\n // by an earlier release stays deletable.\n assertDocumentSize(input.body, \"Writer\");\n }\n if (input.insertGuard !== undefined) {\n assertInsertGuardShape(input);\n }\n if (input.admission !== undefined) {\n assertAdmissionShape(input);\n }\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // One attempt: a log-create 412 is resolved inside it (own-session\n // adoption or a bounded forward-probe), and nothing after the create\n // may re-run it — a durable create re-run at a fresh tail would\n // duplicate the logical write.\n const success = await this.#singleAttemptCommit(input, session, logPrefix, \"Writer\");\n // A replay committed nothing, so it is not a logical write and records\n // no write-amplification sample; it is counted as a replay instead.\n if (success.replayed) {\n recordInsertReplay(input.collection);\n } else {\n this.#emitWriteMetrics(input.collection, success.classAOps);\n }\n return {\n entry: success.entries[0]!,\n currentEtag: success.currentEtag,\n };\n }\n\n /**\n * One full commit attempt — the body of {@link commit}. Reads\n * `current.json`, then forward-probes the tail and creates `log/<seq>`\n * once via `If-None-Match: \"*\"` — the numbered log create IS the commit\n * (single-write commit; no `current.json` CAS follows it). Returns the\n * success payload.\n *\n * Commits exactly one {@link CommitInput} — the numbered log create is\n * the single linearization point per call.\n *\n * A log-create 412 is disambiguated by session read-back: own session\n * / own seq ⇒ our crashed-or-lost-ack commit is already durable ⇒\n * adopt; foreign session ⇒ re-probe forward and create at the next\n * empty slot. Each slot gets one `Storage.put` and never a same-slot\n * resend, because the adapter already retried it. A definitive\n * `AccessDenied` / `InvalidConfig` propagates as-is. A 412 or an uncertain\n * failure resolves by one occupant readback, because adapters can hide\n * earlier sends. When the call reports every attempt refused unapplied\n * (`cause.notApplied`), the same readback runs because a throttle can hide\n * a lost race: a foreign occupant forward-probes, a slot read back as\n * empty or unreadable propagates the retriable `NetworkError`: the\n * adapter already guarantees no attempt applied or can still apply.\n * Unresolved creates throw non-retriable `AmbiguousCommit`; failures\n * before the create propagate.\n *\n * Crash safety: the create is the attempt's only write. A crash before\n * it leaves nothing; a crash after it is a durable, committed write at\n * `seq`, carrying its full post-image in `LogEntry.after`.\n */\n async #singleAttemptCommit(\n input: CommitInput,\n session: string,\n logPrefix: string,\n errorPrefix: string,\n ): Promise<SingleAttemptSuccess> {\n // ── Step 1. Read current.json (fresh; carries the ETag). ────────\n // On a fresh bucket / fresh collection the manifest doesn't exist\n // yet. Auto-create it with a zero-state initial so `db.collection(x)\n // .insert(...)` works zero-shot. A peer racing the same create\n // loses cleanly on `If-None-Match: \"*\"`; we re-read to pick up\n // the winner's manifest. Cost: one extra Class A PUT on the very\n // first commit per collection, zero overhead thereafter.\n const read =\n (await readCurrentJson(this.#storage, this.#currentJsonKey)) ??\n (await this.#provisionCurrentJson());\n const current = read.json;\n const baseEtag = read.etag;\n\n // ── Step 2. Optional integrity walk (`verifyLogIntegrityOnCommit`,\n // default off). Surfaces missing / malformed entries inside\n // `[log_seq_start, tail_hint)` as `Internal` / `InvalidResponse`;\n // entries below `log_seq_start` are folded into the snapshot\n // by `compact()` and possibly swept by `runGc()`, so the walk is\n // bounded to the live tail. The read path catches the same\n // conditions on the next consult — production callers leave the\n // walk off to avoid `O(tail)` Class-B GETs per CAS attempt.\n if (this.#verifyLogIntegrityOnCommit) {\n await this.#walkLog(logPrefix, logSeqStartOf(current), current.tail_hint);\n }\n\n // ── Step 3. Find the true tail (Class B forward-probe), then mint. ─\n // `tail_hint` is a non-authoritative lower bound (the writer no\n // longer advances it — only the compactor stamps it durably). The\n // forward-probe discovers the first empty seq >= the floor: the slot\n // this commit will create. Floor at `max(log_seq_start, tail_hint)`\n // so a compactor that advanced `log_seq_start` past a stale\n // `tail_hint` doesn't make us re-walk folded-but-unswept entries.\n // Bind to a local (oxlint `no-await-expression-member`).\n //\n // A guarded insert (`input.insertGuard`) or an admission re-check\n // (`input.admission`) instead reads every entry in its unseen window\n // `[windowFrom, tail)`: Step 3a GETs the part a fold already moved\n // below `log_seq_start`, and Step 3b probes the rest with\n // `probeTailFrom`, which returns the entries it passes.\n const guard = input.insertGuard;\n const admission = input.admission;\n const windowFrom = guard?.absentBelowSeq ?? admission?.fromSeq;\n const logSeqStart = logSeqStartOf(current);\n let commitWindow: LogEntry[] | undefined;\n // Whether the latest `admission.check` asked to force the write tick.\n let admissionForces = false;\n // The post-image this attempt commits: the input's, or the latest\n // `admission.check` verdict's.\n let body = input.body;\n const decide = async (window: readonly LogEntry[], tail: number): Promise<void> => {\n if (admission === undefined) {\n return;\n }\n const verdict = await admission.check(window, tail);\n admissionForces = verdict?.forceMaintenance === true;\n if (verdict?.body !== undefined) {\n if (input.op !== \"U\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${errorPrefix}: an admission verdict may replace only a U post-image; got op ${JSON.stringify(input.op)}`,\n );\n }\n assertPostImageIdentity(input.docId, verdict.body, \"InvalidConfig\");\n assertDocumentSize(verdict.body, errorPrefix);\n body = verdict.body;\n }\n };\n let preCommitTail: number;\n if (windowFrom === undefined) {\n const probeFloor = Math.max(logSeqStart, current.tail_hint);\n // `findLogTail`'s density precondition holds: the floor sits in the\n // dense prefix because tail_hint advancers probe or derive known tails\n // from committed entries, while ordinary writer commits never stamp\n // `tail_hint`, so nothing advances the floor past a hole.\n preCommitTail = await findLogTail(this.#storage, logPrefix, probeFloor);\n } else {\n // ── Step 3a. Folded part of the window, `[windowFrom, floor)`.\n const folded = await this.#readFoldedWindow(logPrefix, windowFrom, logSeqStart, errorPrefix);\n // ── Step 3b. Live part, probed from `max(windowFrom, floor)`.\n // That start meets `probeTailFrom`'s retention precondition (it is\n // at or above this manifest read's `log_seq_start`) and sits in the\n // dense prefix: `windowFrom` was the first empty slot a read probe\n // found with every slot from its floor up occupied (or one past a\n // slot the caller's own create won), creates only ever land at a\n // first-empty slot, and retirement stays below `log_seq_start`.\n // Starting below `tail_hint` re-reads the slots in\n // `[windowFrom, tail_hint)`; those are exactly the window entries the\n // caller's decision could not see, so none of the GETs is wasted.\n // Uncontended, `windowFrom` is the tail: one 404 GET, never more\n // than the gallop above.\n const probe = await probeTailFrom(\n this.#storage,\n logPrefix,\n Math.max(windowFrom, logSeqStart),\n );\n commitWindow = [...folded, ...probe.entries];\n // ── Step 3c. Window decisions, BEFORE the first create, so a loser\n // caught here writes nothing at all, and a replay of an identical\n // live row returns it having written nothing.\n // The insert decision runs first: a peer's live row is\n // `AlreadyExists` whatever the capacity re-check would say.\n if (guard !== undefined) {\n const replayed = decideInsertTarget(commitWindow, input);\n if (replayed !== undefined) {\n return { replayed: true, entries: [replayed], currentEtag: baseEtag };\n }\n }\n await decide(commitWindow, probe.tail);\n preCommitTail = probe.tail;\n }\n let seq = preCommitTail;\n\n // All entries share `session` (one session per logical commit) and\n // a single commit instant: `lsn`'s timestamp and `commit_ts` are\n // derived from ONE clock read so they can't drift apart under skew\n // (a reader validates `commit_ts` against `LAG_WINDOW_MILLIS`, and\n // two independent reads could straddle that band). The LSN's\n // `countKey(seq)` suffix MUST track the probed seq — it's compared on\n // adoption, so a stale suffix would misfire the disambiguation.\n const commitNowMs = Date.now();\n const commitTs = new Date(commitNowMs).toISOString();\n const lsnTimestamp = timestamp(commitNowMs);\n const mintEntry = (atSeq: number): LogEntry => ({\n lsn: `${lsnTimestamp}_${session}_${countKey(atSeq)}`,\n commit_ts: commitTs,\n op: input.op,\n collection: input.collection,\n doc_id: input.docId,\n session,\n seq: atSeq,\n ...(input.op !== \"D\" && body !== undefined ? { after: body } : {}),\n ...(input.origin !== undefined ? { origin: input.origin } : {}),\n });\n let entry = mintEntry(seq);\n\n // ── Step 4. Create the commit: PUT log/<seq> via If-None-Match. ─\n // The numbered log create IS the commit (single-write commit). No\n // `current.json` CAS follows it — the create is the linearization\n // point (exactly-one-winner, CI-gated across all backends).\n //\n // The commit-resolution reserve (`COMMIT_RESOLUTION_RESERVE`): each\n // slot's attempt (the create, the readback, and on a resolved commit\n // the Step 4a floor check) runs under a request ledger hold of\n // everything it may spend, taken only if it fits; otherwise\n // `CapacityExceeded`, with nothing of the attempt sent.\n //\n // Each slot gets exactly ONE `storage.put`: the adapter already retried\n // it under the storage retry policy, so a Writer-level resend would\n // multiply that policy's attempts (retry at one layer). The outcome of\n // that one call decides the next step:\n // - success ⇒ committed at `seq`;\n // - `cause.notApplied` (every attempt provably unapplied) ⇒ one\n // occupant readback, because a throttle may hide a lost race: own\n // entry ⇒ adopt; foreign ⇒ forward-probe; an observed empty slot\n // or unreadable ⇒ the retriable `NetworkError` propagates;\n // - `AccessDenied` / `InvalidConfig` ⇒ definitive under the\n // `Storage.put` contract; propagates as-is;\n // - a 412, or any other failure (an uncertain send — e.g. a dropped\n // ack on a create that may already have landed) ⇒ one occupant\n // readback. Own entry ⇒ adopt; foreign ⇒ forward-probe (a new\n // slot, not a resend); absent or unreadable ⇒ `AmbiguousCommit`,\n // because an absent slot cannot prove an in-flight send won't land.\n // A lost ack resolves without a resend: the adapter's own next attempt\n // sees the landed object as a 412, or the readback finds it.\n let committedEntry: LogEntry;\n let probes = 0;\n const ambiguous = (cause: unknown): BaerlyError => {\n ctxMetrics().counter(\"db.write.unresolved_create_total\", 1, {\n collection: entry.collection,\n });\n return new BaerlyError(\n \"AmbiguousCommit\",\n `${errorPrefix}: the committing create at seq ${seq} on ${this.#currentJsonKey} was rejected and its fate could not be resolved; an earlier send may already have landed or may still land, so retrying may duplicate logical work`,\n { cause, resolution: CODE_RESOLUTIONS.AmbiguousCommit, _id: entry.doc_id },\n );\n };\n for (;;) {\n const outcome = await this.#withCommitHold(\n errorPrefix,\n async (): Promise<{ committed: LogEntry } | { foreign: LogEntry }> => {\n const logEntryKey = logObjectKey(logPrefix, seq);\n assertKeyWithinLimit(logEntryKey);\n // Encoded outside the try: an unencodable entry is the caller's\n // error, and no send was made that a readback would need to resolve.\n const entryBody = encodeJsonBytes(entry);\n let resolved: LogEntry | undefined;\n let createFailure: unknown;\n let notApplied = false;\n try {\n await this.#storage.put(logEntryKey, entryBody, {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n resolved = entry;\n } catch (error) {\n createFailure = error;\n this.#observe429(error, entry.collection);\n if (isWriteConflict(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n // Even a visible 412 can be our entry: the adapter may have\n // retried a landed send internally.\n } else if (isDefinitiveCreateRejection(error)) {\n // `Storage.put` contract: no attempt of this call was applied,\n // and this is the slot's only send, so nothing of ours is at\n // `seq`.\n throw error;\n } else if (isCreateNotApplied(error)) {\n // A throttle can hide a lost race (R2 can answer a same-key\n // create race with a 429, not a 412), so the readback still\n // tells a peer's slot from an empty one.\n notApplied = true;\n }\n }\n if (resolved === undefined) {\n let occupant: LogEntry;\n let decision: ReturnType<typeof tryAdoptOwnSessionLogEntry>;\n try {\n occupant = await this.#readLogOccupant(logEntryKey);\n decision = tryAdoptOwnSessionLogEntry({ self: entry, existing: occupant });\n } catch (error) {\n if (notApplied) {\n // The adapter guarantees no attempt applied or can still\n // apply. An empty, unreadable, or malformed slot cannot make\n // retry unsafe.\n throw createFailure;\n }\n throw ambiguous(\n new AggregateError(\n [createFailure, error],\n \"The create and its readback could not be resolved\",\n ),\n );\n }\n if (!decision.adopt) {\n return { foreign: occupant };\n }\n // Own crashed/lost-ack commit already durable at `seq`. Adopt it\n // (byte-identical to the attempted `entry`, INCLUDING\n // `commit_ts` — adoption compares the full entry) — the logical\n // write lands at EXACTLY `seq`, never duplicated.\n resolved = decision.entry;\n }\n // ── Step 4a. Refuse a create that re-filled a retired hole. ─────\n // Both resolved paths above land here with the resolved committing\n // `seq`: the fresh win and the own-session adoption.\n await this.#assertCommitAboveDeleteFloor(\n logPrefix,\n seq,\n input.collection,\n input.docId,\n errorPrefix,\n );\n return { committed: resolved };\n },\n );\n if (\"committed\" in outcome) {\n committedEntry = outcome.committed;\n break;\n }\n const occupant = outcome.foreign;\n // Foreign session (or wrong seq) — re-probe forward from seq+1 and\n // create at the new first-empty slot, re-minting seq + LSN. The hold\n // is released: the occupant proves nothing of this commit landed, so\n // a refusal from here to the next hold is clean.\n if (++probes > LOG_FORWARD_PROBE_CAP) {\n throw new BaerlyError(\n \"Internal\",\n `${errorPrefix}: log-tail forward-probe exceeded ${LOG_FORWARD_PROBE_CAP} on ${this.#currentJsonKey}`,\n );\n }\n if (commitWindow === undefined) {\n seq = await findLogTail(this.#storage, logPrefix, seq + 1);\n } else {\n // Windowed commit: the occupant and every entry the forward probe\n // passes join the window, and the window decisions re-run before\n // the next create. A refusal here (`AlreadyExists`, or the\n // admission's own error) is sound because a foreign occupant at\n // `seq` proves this commit's send did not land there. A replay of\n // an identical live row returns here for the same reason: nothing\n // of this commit landed.\n commitWindow.push(occupant);\n const probe = await probeTailFrom(this.#storage, logPrefix, seq + 1);\n commitWindow.push(...probe.entries);\n if (guard !== undefined) {\n const replayed = decideInsertTarget(commitWindow, input);\n if (replayed !== undefined) {\n return { replayed: true, entries: [replayed], currentEtag: baseEtag };\n }\n }\n await decide(commitWindow, probe.tail);\n seq = probe.tail;\n }\n entry = mintEntry(seq);\n }\n const committedEntries: readonly LogEntry[] = [committedEntry];\n\n // ── Step 5. Write-tick maintenance dispatch. ────────────────────\n // Single funnel site: write-tick maintenance dispatch. Reached by\n // `commit()` exactly once per logical commit, after the committing\n // log create has landed.\n //\n // Config rides the per-request observability context\n // (`getCurrentContext()?.maintenance`), set by the adapter — NOT the\n // Writer constructor / `Db.create`. Absent ⇒ inline dispatch +\n // CF-free-safe caps, so a bare `Db.create(...).collection(...)\n // .insert(...)` maintains inline by default once enough writes\n // accrue.\n //\n // `prevSeq` is the pre-commit tail (`preCommitTail`); the slot we won\n // is `seq` (== prevSeq unless a forward re-probe moved it past a\n // foreign winner), so the boundary check spans `(prevSeq,\n // observedTail]`. `observedTail = seq+1` is a fresh in-memory lower\n // bound on the true tail: winning `log/<seq>` means `[tail_hint, seq)`\n // were observed occupied, so `seq+1 ≤ true tail`. We pass `current`\n // (the Step-1 read) for the snapshot fields — there is no `next`.\n const prevSeq = preCommitTail;\n const observedTail = seq + 1;\n const maint = getCurrentContext()?.maintenance;\n // Same absent-context default as runBoundedMaintenance's\n // `options?.profile ?? MAINTENANCE_PROFILE_CF_FREE` — keep the two in\n // step (this gate reads only gcInterval; the runner resolves the whole\n // profile) so the pre-fire cadence can't diverge from the fold's.\n const gcInterval =\n maint?.options?.profile?.gcInterval ?? MAINTENANCE_PROFILE_CF_FREE.gcInterval;\n // A forced tick (main-10 G6) skips the ratio-OR-boundary gate: the\n // verb found the collection at its growth-refusal point.\n const forceFold =\n (input.forceMaintenance === true || admissionForces) && maint?.disabled !== true;\n // The adapter's host trigger (`InternalBoundedMaintenanceOptions`): a\n // live tail this long fires too, so the runner's Gate 1 sees it.\n const foldAtTailEntries = (maint?.options as InternalBoundedMaintenanceOptions | undefined)\n ?.foldAtTailEntries;\n const maintenanceDue =\n maint?.disabled === true\n ? observedTail - current.tail_hint >= MAINTENANCE_TAIL_HINT_REFRESH_WRITES\n : forceFold ||\n (foldAtTailEntries !== undefined &&\n observedTail - current.log_seq_start >= foldAtTailEntries) ||\n shouldFireMaintenance(current, prevSeq, gcInterval, observedTail);\n if (maintenanceDue) {\n await dispatchWriteTick({\n storage: this.#storage,\n currentJsonKey: this.#currentJsonKey,\n collection: input.collection,\n prevSeq,\n observedTail,\n ...(forceFold && { forceFold: true }),\n });\n }\n\n // Class-A op count for this commit: the committing log create alone.\n // No current.json CAS. Forward-probe and readback GETs are Class B and\n // excluded, as are creates refused at slots a foreign writer won.\n const classAOps = 1;\n return {\n replayed: false,\n entries: committedEntries,\n // No current.json write on the commit path — return the manifest\n // etag read in Step 1 (still a valid etag of the current manifest).\n currentEtag: baseEtag,\n classAOps,\n };\n }\n\n /**\n * Auto-create the per-collection `current.json` at\n * `this.#currentJsonKey` with a zero-state initial manifest. Called\n * by `#singleAttemptCommit` when the read returned `null` (fresh\n * bucket / fresh collection).\n *\n * Concurrency: `createCurrentJson` uses `If-None-Match: \"*\"`. If a\n * peer raced us and won, the storage layer surfaces `WriteConflict`; we\n * recover by re-reading the now-present manifest. We do NOT retry\n * the create — a single recover-via-read covers every race that\n * could have produced our null read.\n *\n * The seed shape (`snapshot: null`, `tail_hint: 0`, `log_seq_start:\n * 0`, `writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" }`)\n * matches `ensureTable`, so an\n * operator who pre-provisions and a writer who auto-creates land on\n * equivalent state. NOT byte-identical any more: `generation` is a\n * fresh nonce per provisioner. That is harmless — `If-None-Match`\n * means exactly one of them ever lands, and no reader compares a\n * generation across provisioners, only against the cursor it minted.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the post-recover\n * re-read also returned null. Defensive guard; in practice\n * unreachable because the WriteConflict implies the key now exists.\n */\n async #provisionCurrentJson(): Promise<CurrentJsonRead> {\n const initial: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n generation: mintGeneration(),\n };\n let createFailure: unknown;\n try {\n return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);\n } catch (error) {\n // A provably unapplied create may hide a peer provisioning the same\n // key, so it recovers by re-read like a 412.\n if (!isWriteConflict(error) && !isCreateNotApplied(error)) {\n throw error;\n }\n createFailure = error;\n }\n const recovered = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (recovered === null && isCreateNotApplied(createFailure)) {\n throw createFailure;\n }\n if (recovered === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Writer: current.json missing at ${this.#currentJsonKey} after auto-create raced and recover read returned null`,\n );\n }\n return recovered;\n }\n\n /**\n * Fail the commit if the create landed at a sequence the collection has\n * already certified deleted.\n *\n * **What a sub-floor `seq` proves, and what it does not.** A winning\n * `If-None-Match: \"*\"` create means the slot was empty immediately before the\n * PUT, so the object this commit just wrote sits beneath every reader's floor\n * and no reader will ever consult it. What a sub-floor `seq` does NOT prove\n * is that the *logical mutation* is invisible. Two histories reach this\n * branch: the create re-filled a hole retirement had already certified\n * deleted (invisible — the defect this check exists for), or it landed in a\n * live empty slot that a fold and then a retirement pass swept out from under\n * it (visible through the snapshot). That second history is a real\n * over-rejection, pinned as contract by a test in\n * `./log-retirement-aba.test.ts`, not an accident. It is the safe direction,\n * and \"What the caller is being told\" below is why guessing between the two\n * is worse than reporting both as ambiguous.\n *\n * **`log_delete_floor <= seq < log_seq_start` is NOT a failure.** Not because\n * that band is provably safe — it is undecidable in the very same way. A\n * winning create means the slot was empty just before the PUT, so what a fold\n * absorbed there was either an earlier attempt of ours (mutation visible) or\n * a foreign writer's entry (ours invisible), and the fold keeps no writer\n * identity to tell them apart. The band is accepted because keying the check\n * on `log_seq_start` would reject ordinary post-fold commits — a far\n * larger harm than the residual it would catch. That residual is the\n * invisible half of the undecidable band `docs/spec/sync-protocol.md`\n * invariant 5 describes; it is not reachable by the certified-floor check,\n * by construction.\n *\n * The floor is clamped to `min(log_delete_floor, log_seq_start)` for the\n * reason invariant 12 gives: the `<= log_seq_start` bound is\n * transition-scoped, so an out-of-bound stored floor is readable off disk\n * and would otherwise fail a perfectly good commit.\n *\n * **What the caller is being told.** Not \"your write failed\" —\n * `AmbiguousCommit`. An earlier attempt by this same writer may have landed\n * and been folded before retirement removed the slot, and nothing durable\n * distinguishes that history from a foreign writer's entry being folded\n * instead: the fold keeps no writer identity, tombstones are purged,\n * `current.json` holds no per-writer completion state, and `writer_fence` is\n * not a replay filter (invariant 11). So the write contract under this fault\n * is at-least-once, and re-probing-and-re-applying is emphatically not a\n * safe default: `LogEntry.after` is a full post-image, so a duplicate\n * clobbers a concurrent newer value and mints a second `lsn` for one logical\n * mutation.\n *\n * The phantom object is DELETEd best-effort, and it is the only thing\n * standing between a rejected commit and a permanently leaked object.\n * Nothing reclaims the phantom afterwards: it sits at a seq *below*\n * `log_delete_floor` — that is the precondition for reaching this branch —\n * and `computeRetirableRange` (`./log-retention.ts`) *starts* at the\n * certified floor, so retirement never revisits a slot beneath its own\n * floor. GC does not reclaim log objects at all. So a `cleanup: \"failed\"`\n * on `db.write.ambiguous_commit_total` is a genuine permanent leak, not a\n * deferral. Deleting it is safe: no reader may read below the certified\n * floor (invariant 5). A failed cleanup is recorded on the counter and never masks the\n * throw.\n *\n * **A failed manifest read skips the check rather than failing the commit —\n * except an abort, which propagates.** The check runs over an already-durable\n * create, and an unreadable manifest is no evidence of a sub-floor `seq`, so a\n * transient read failure is swallowed. An `AbortError` is rethrown instead: it\n * is the caller's own cancellation rather than a blip, and it carries none of\n * the `retriable` re-run hazard that motivates swallowing the rest. The skip\n * is recorded on `db.write.delete_floor_check_skipped_total` so a sustained\n * rate is visible to an operator rather than silent.\n *\n * Cost: one Class B GET per commit.\n * `billableClassAOps = puts + lists` excludes GET, so billing is unchanged;\n * it is one of the calls `COMMIT_RESOLUTION_RESERVE` keeps on the request\n * ledger.\n *\n * @throws BaerlyError code=\"AmbiguousCommit\"\n */\n async #assertCommitAboveDeleteFloor(\n logPrefix: string,\n seq: number,\n collection: string,\n docId: string,\n errorPrefix: string,\n ): Promise<void> {\n let read: CurrentJsonRead | null;\n try {\n read = await readCurrentJson(this.#storage, this.#currentJsonKey);\n } catch (error) {\n if (isAbortError(error)) {\n // An abort is the caller's deliberate cancellation, not a transient\n // blip, and the caller already knows it cancelled. The hazard the\n // swallow below exists for is specific to `retriable` errors; an\n // `AbortError` is not one, so rethrowing costs that reasoning nothing.\n throw error;\n }\n // A failed read is not evidence of a sub-floor commit, so skipping the\n // check preserves the pre-existing commit contract exactly and forgoes\n // only a safety net on a rare blip. Propagating instead would be worse\n // than useless: the create already committed, and `NetworkError` is\n // `retriable`, so a generic retry wrapper would re-run the whole logical\n // write at a fresh tail — duplicating the mutation and minting a second\n // `lsn`. The maintenance dispatch after it swallows its non-abort\n // failures for the same reason. Failing closed is not the answer either\n // — throwing `AmbiguousCommit` on an unreadable manifest would reject\n // durable commits far more often than the fault this check catches.\n ctxMetrics().counter(\"db.write.delete_floor_check_skipped_total\", 1, { collection });\n countPostCommitRefusal(error, collection, \"delete-floor-check\");\n return;\n }\n if (read === null) {\n // The manifest vanished between Step 1 and here. Unreachable in\n // practice (Step 1 read or provisioned it), and a missing manifest\n // certifies no deleted prefix, so there is nothing to reject against.\n return;\n }\n const deleteFloor = certifiedDeleteFloor(read.json);\n // `deleteFloor === 0` means no deleted prefix is certified — same silent\n // arm as `Db.assertAtOrAboveLogFloor`.\n if (deleteFloor <= 0 || seq >= deleteFloor) {\n return;\n }\n let cleanup: \"deleted\" | \"failed\" = \"deleted\";\n await this.#storage.delete(logObjectKey(logPrefix, seq)).catch(() => {\n cleanup = \"failed\";\n });\n ctxMetrics().counter(\"db.write.ambiguous_commit_total\", 1, { collection, cleanup });\n throw new BaerlyError(\n \"AmbiguousCommit\",\n `${errorPrefix}: the committing create at seq ${seq} on ${this.#currentJsonKey} landed below the certified delete floor ${deleteFloor}; that log object is beneath every reader's floor, and this mutation may or may not have been applied by an earlier attempt — retry is at-least-once`,\n { resolution: CODE_RESOLUTIONS.AmbiguousCommit, _id: docId },\n );\n }\n\n /**\n * Run one commit slot's attempt, `fn` (the committing create and the\n * calls that resolve it), under a hold on the active request ledger of\n * everything it may spend: the create at full retries, plus\n * {@link COMMIT_RESOLUTION_RESERVE} for the readback and the delete-floor\n * check. `fn` runs in a child observability context carrying the hold, so\n * only its own storage calls draw on it; work outside that context (a\n * `ctx.waitUntil` write tick of an earlier row, the read cache) sees the\n * ledger net of it and cannot spend it. The hold is released when `fn`\n * settles.\n *\n * Refuses, before `fn` sends anything, when the ledger's room is short\n * of the hold. No create of this commit has landed or can land then:\n * before the first slot nothing was sent, and before a later one a\n * foreign occupant holds the slot this commit's only send targeted. A host without request\n * limits (Node, or no ledger) never refuses and takes no hold.\n *\n * @throws BaerlyError code=\"CapacityExceeded\", cause `{ refused: true }`.\n */\n /**\n * The collection segment of `current.json`'s key, for messages that\n * reach HTTP callers unscrubbed (`CapacityExceeded` is `public`), which\n * must not carry the storage key.\n */\n #collectionName(): string {\n const parts = this.#currentJsonKey.split(\"/\");\n return parts[parts.length - 2] ?? \"\";\n }\n\n async #withCommitHold<T>(errorPrefix: string, fn: () => Promise<T>): Promise<T> {\n const ctx = getCurrentContext();\n const ledger = ctx?.ledger;\n const remaining = ledger?.storageRemaining() ?? Infinity;\n if (ctx === undefined || ledger === undefined || remaining === Infinity) {\n return await fn();\n }\n const needed = STORAGE_RETRY_MAX_ATTEMPTS + COMMIT_RESOLUTION_RESERVE;\n if (remaining < needed) {\n throw new BaerlyError(\n \"CapacityExceeded\",\n `${errorPrefix}: this request has ${String(remaining)} storage calls left, fewer than the ${String(needed)} a commit to collection ${JSON.stringify(this.#collectionName())} may need (the committing create, with retries, plus resolving it), so nothing was committed; the work this request needs does not fit in one request on this host`,\n // The HTTP envelope fills in the code's canonical resolution.\n { cause: { refused: true, needed, remaining } },\n );\n }\n const hold = ledger.hold(needed);\n try {\n return await runWithContext({ ...ctx, hold }, fn);\n } finally {\n hold.release();\n }\n }\n\n /**\n * Walk `log/<logSeqStart>.json` … `log/<nextSeq - 1>.json` with\n * bounded parallelism via `walkLogRange`. Materialised entries are\n * discarded — the walk's only job is to surface a hole or a\n * malformed body inside the visible range as\n * `BaerlyError{code:\"Internal\"}` / `\"InvalidResponse\"`.\n *\n * Gated on `verifyLogIntegrityOnCommit`; default off in production\n * because the per-doc fold already lives in the read path. See the\n * option's docstring for the rationale and the opt-in convention.\n *\n * `logSeqStart` is the boundary set by the compactor on\n * `current.json.log_seq_start`. Entries below it have been folded\n * into the snapshot and may have been swept off the bucket, so the\n * walk MUST NOT GET-require them.\n */\n async #walkLog(logPrefix: string, logSeqStart: number, nextSeq: number): Promise<void> {\n await walkLogRange(this.#storage, logPrefix, logSeqStart, nextSeq);\n }\n\n /**\n * Read `[fromSeq, logSeqStart)` for a windowed commit (insert guard or\n * admission) whose window starts below the floor of this commit's\n * manifest read: a fold absorbed those entries after the caller's read. Slots below the floor stay\n * readable until log retirement deletes them, so a missing slot means\n * this commit can no longer check its window: `WriteConflict`, nothing\n * committed, and the caller's next read sees the folded state. A window\n * longer than {@link LOG_FORWARD_PROBE_CAP} is refused the same way\n * rather than spending an unbounded run of GETs on the write path.\n *\n * @throws BaerlyError code=\"WriteConflict\" — a slot is missing, or the\n * range exceeds the cap.\n * @throws BaerlyError code=\"InvalidResponse\" — a slot's body is not JSON.\n */\n async #readFoldedWindow(\n logPrefix: string,\n fromSeq: number,\n logSeqStart: number,\n errorPrefix: string,\n ): Promise<LogEntry[]> {\n if (fromSeq >= logSeqStart) {\n return [];\n }\n const refuse = (detail: string): BaerlyError =>\n new BaerlyError(\n \"WriteConflict\",\n `${errorPrefix}: commit window [${fromSeq}, ${logSeqStart}) on ${this.#currentJsonKey} ${detail}; nothing was committed`,\n );\n // Backstop only. In practice the window holds just the entries a fold\n // absorbed between two reads in one request, and the host's\n // subrequest budget ends that request long before 100k GETs.\n if (logSeqStart - fromSeq > LOG_FORWARD_PROBE_CAP) {\n throw refuse(`exceeds ${LOG_FORWARD_PROBE_CAP} folded entries`);\n }\n const entries: LogEntry[] = [];\n for (let chunk = fromSeq; chunk < logSeqStart; chunk += MAX_PARALLEL_LOG_READS) {\n const end = Math.min(chunk + MAX_PARALLEL_LOG_READS, logSeqStart);\n const keys = Array.from({ length: end - chunk }, (_, i) =>\n logObjectKey(logPrefix, chunk + i),\n );\n const bodies = await Promise.all(keys.map((key) => this.#storage.get(key)));\n for (let i = 0; i < bodies.length; i++) {\n const got = bodies[i];\n if (got === null || got === undefined) {\n throw refuse(`was retired at seq ${chunk + i} before it could be checked`);\n }\n try {\n entries.push(decodeJsonBytes<LogEntry>(got.body));\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `${errorPrefix}: malformed log entry at ${keys[i]!}`,\n { cause: error },\n );\n }\n }\n }\n return entries;\n }\n\n /**\n * Read the occupant of a slot whose committing create was rejected, with\n * one `Storage.get` (the adapter retries it; the Writer does not). A failed\n * read, an empty slot, or an occupant without a writer identity throws:\n * none of them proves the slot holds a foreign entry rather than a pending\n * send of our own.\n */\n async #readLogOccupant(key: string): Promise<LogEntry> {\n const got = await this.#storage.get(key);\n if (got === null) {\n throw new BaerlyError(\"NotFound\", `Writer: ${key} is empty after its create was rejected`);\n }\n let existing: unknown;\n try {\n existing = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `Writer: malformed log occupant at ${key}`, {\n cause: error,\n });\n }\n if (!hasWriterIdentity(existing)) {\n // Parsed JSON alone cannot establish a conflicting writer's identity.\n throw new BaerlyError(\"InvalidResponse\", `Writer: malformed log occupant at ${key}`);\n }\n return existing;\n }\n\n /**\n * Bump the `db.r2.put.429_total` counter when `err` looks like an\n * R2 prefix-partition rate-limit. Best-effort: detected via\n * `BaerlyError{code:\"NetworkError\"}` with a `429` token in the\n * message. Called from every PUT call site's catch arm; mutually\n * exclusive in practice with `isWriteConflict` (412 ≠ 429).\n */\n #observe429(err: unknown, collection: string): void {\n if (is429(err)) {\n ctxMetrics().counter(\"db.r2.put.429_total\", 1, { collection });\n }\n }\n\n /**\n * Emit the per-logical-write `class_a_ops_per_logical_write`\n * histogram for `commit`. `classAOps` is the committing create, computed\n * by `#singleAttemptCommit`.\n */\n #emitWriteMetrics(collection: string, classAOps: number): void {\n ctxMetrics().histogram(\"db.write.class_a_ops_per_logical_write\", classAOps, { collection });\n }\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when a create rejection proves the create did not land. Under the\n * `Storage.put` contract an adapter that retried internally reports such a\n * rejection as `NetworkError`, so these codes describe the only attempt.\n */\nconst isDefinitiveCreateRejection = (err: unknown): boolean =>\n err instanceof BaerlyError && (err.code === \"AccessDenied\" || err.code === \"InvalidConfig\");\n\n/**\n * `true` when a create-only put reports, per the `Storage.put` contract,\n * that no attempt of the call was applied: a `NetworkError` after every\n * attempt was throttled or refused before issue, or the request ledger's\n * `CapacityExceeded` when it refused the call before any attempt of\n * unknown outcome. `cause.notApplied` is the proof either way.\n */\nconst isCreateNotApplied = (err: unknown): boolean =>\n err instanceof BaerlyError &&\n (err.code === \"NetworkError\" || err.code === \"CapacityExceeded\") &&\n ((err as BaerlyError).cause as { notApplied?: boolean } | undefined)?.notApplied === true;\n\n/**\n * Count a post-commit step the request ledger refused on\n * `db.write.post_commit_refused_total`. The step runs after a known\n * commit and swallows its failure, so the refusal leaves the commit\n * acknowledged; `phase` names the step that went without (the delete-floor\n * check is the only one).\n */\nconst countPostCommitRefusal = (\n err: unknown,\n collection: string,\n phase: \"delete-floor-check\",\n): void => {\n if (\n err instanceof BaerlyError &&\n err.code === \"CapacityExceeded\" &&\n (err.cause as { refused?: boolean } | undefined)?.refused === true\n ) {\n ctxMetrics().counter(\"db.write.post_commit_refused_total\", 1, { collection, phase });\n }\n};\n\n/**\n * Reject an `insertGuard` on anything but an `I`, or with an\n * `absentBelowSeq` that is not a log seq. Runs before any I/O.\n */\nconst assertInsertGuardShape = (input: CommitInput): void => {\n if (input.op !== \"I\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: insertGuard is valid only with op \"I\"; got op ${JSON.stringify(input.op)}`,\n );\n }\n const seq = input.insertGuard?.absentBelowSeq;\n if (typeof seq !== \"number\" || !Number.isSafeInteger(seq) || seq < 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: insertGuard.absentBelowSeq must be a non-negative safe integer; got ${String(seq)}`,\n );\n }\n const replay = input.insertGuard?.replayIdentical;\n if (replay !== undefined && typeof replay !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: insertGuard.replayIdentical must be a boolean; got ${typeof replay}`,\n );\n }\n};\n\n/**\n * Reject an `admission` whose `fromSeq` is not a log seq, or differs from\n * the insert guard's window start. Runs before any I/O.\n */\nconst assertAdmissionShape = (input: CommitInput): void => {\n const seq = input.admission?.fromSeq;\n if (typeof seq !== \"number\" || !Number.isSafeInteger(seq) || seq < 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: admission.fromSeq must be a non-negative safe integer; got ${String(seq)}`,\n );\n }\n if (typeof input.admission?.check !== \"function\") {\n throw new BaerlyError(\"InvalidConfig\", \"Writer: admission.check must be a function\");\n }\n const guarded = input.insertGuard?.absentBelowSeq;\n if (guarded !== undefined && guarded !== seq) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Writer: admission.fromSeq ${seq} must equal insertGuard.absentBelowSeq ${guarded}`,\n );\n }\n};\n\n/**\n * Window decision for a guarded insert. `window` holds the log entries\n * in `[absentBelowSeq, seq)` in seq order, unfiltered. The LAST entry for\n * this `(collection, doc_id)` decides: a `D`, or no entry, means the row\n * is absent and the insert may commit (`undefined`). An `I` or `U` means a\n * row is live: with `replayIdentical` set and that entry's `after` equal\n * to the body, the insert is a replay of its own earlier success and the\n * entry is returned; otherwise the insert throws `AlreadyExists`.\n *\n * @throws BaerlyError code=\"AlreadyExists\"\n */\nconst decideInsertTarget = (\n window: readonly LogEntry[],\n input: CommitInput,\n): LogEntry | undefined => {\n for (let i = window.length - 1; i >= 0; i--) {\n const e = window[i]!;\n if (!isOwnCollection(e.collection, input.collection) || e.doc_id !== input.docId) {\n continue;\n }\n if (e.op === \"D\") {\n return undefined;\n }\n if (\n input.insertGuard?.replayIdentical === true &&\n input.body !== undefined &&\n insertReplaysRow(input.body, e.after)\n ) {\n return e;\n }\n throw insertAlreadyExists(input.collection, input.docId);\n }\n return undefined;\n};\n\n/** `true` when a decoded log occupant carries the identity adoption compares. */\nconst hasWriterIdentity = (value: unknown): value is LogEntry => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const { session, seq } = value as { session?: unknown; seq?: unknown };\n return (\n typeof session === \"string\" &&\n session.length > 0 &&\n typeof seq === \"number\" &&\n Number.isSafeInteger(seq) &&\n seq >= 0\n );\n};\n\n/**\n * `true` when a rejection is an `AbortError` — the caller's own cancellation\n * through an `AbortSignal`, never a transient storage failure. Matched\n * structurally on `name` rather than `instanceof DOMException` because a host\n * may surface an abort as a plain `Error` so named (as `Storage` impls and the\n * test fixtures do). `@baerly/client` carries the same predicate; it is\n * duplicated rather than shared because `server` may not import `client`\n * (`scripts/lint-package-layers.mjs`) and one predicate does not earn a new\n * module in `@baerly/protocol`.\n */\nconst isAbortError = (err: unknown): boolean =>\n typeof err === \"object\" && err !== null && \"name\" in err && err.name === \"AbortError\";\n\n/**\n * `true` when the underlying storage surfaced an R2 prefix-partition\n * rate-limit. {@link S3HttpStorage} stamps the upstream HTTP status\n * onto `BaerlyError.cause` as `{ status }`; we discriminate on that\n * structured field rather than regex-matching the message.\n */\nconst is429 = (err: unknown): boolean => {\n if (!(err instanceof BaerlyError) || err.code !== \"NetworkError\") {\n return false;\n }\n const cause = err.cause as { status?: number } | undefined;\n return cause?.status === 429;\n};\n","/**\n * `baerly admin restore` — bulk-import NDJSON into a fresh collection.\n *\n * Reads NDJSON from stdin, reconstructs each row, and calls\n * `Writer.commit({op:\"I\"})` per row into the target bucket.\n * Programmatic callers (today: tests + the export round-trip\n * integration test) can divert the input by passing\n * `{ streams: { stdin } }` to {@link runRestore}. Idempotent on a fresh\n * bucket: re-running on a half-completed restore **refuses** unless\n * `--force` is set (which reseeds a fresh `current.json` above the old\n * tail first).\n *\n * Args:\n * --bucket Required. Target bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Target collection name.\n * --force Truncate the target if it exists (reseed above the old tail).\n * --json JSON envelope.\n *\n * stdin: NDJSON, one `{_id, ...}` row per line. Empty lines tolerated.\n * EOF terminates.\n *\n * Side effect: both reseed branches also delete any leftover\n * `gc/pending.json` for the collection before the first row commits. A\n * candidate marked before the reseed names a key from the old\n * incarnation of the log, which the commits below may re-create at the\n * same seq; the stale ledger's pending depth no longer describes this\n * collection either. A missing ledger is a no-op.\n *\n * Cost shape: before any in-band maintenance triggered by a long import,\n * the base billable shapes are fresh non-empty `N + 2` (initial seed,\n * one committing `log/<seq>` create per row, final `tail_hint` stamp),\n * force non-empty `N + 2 + P`, fresh empty `1`, and force empty\n * `1 + P`, where `P` is the number of provider LIST pages consumed by\n * the one `Storage.list()` iterator in `tailFromListedLogKeys`.\n * Maintenance adds the same measured profile overhead as the main\n * cost model.\n *\n * Partial-restore semantics: validation is per row, in stream order. A\n * line that fails (bad JSON, missing/duplicate/invalid-domain `_id`, or a\n * storage error) stops the run; rows BEFORE it stay committed, that line\n * and later ones are not, and the error message says how many rows\n * committed. The final `tail_hint` stamp may not have landed. Restore\n * again into a fresh target, or with `--force`. A whole-stream pre-pass\n * is deliberately not done (stdin is a stream). `_id`s are never\n * rewritten.\n *\n * Exit codes:\n * 0 — every row committed.\n * 1 — InvalidConfig (bad bucket URI, missing args, duplicate `_id`, or\n * an `_id` outside the write domain: key-segment rule + NFC).\n * 2 — Network / storage error mid-stream, or a malformed NDJSON\n * line (raised as a plain `Error`, not `BaerlyError`).\n * 3 — AlreadyExists from a pre-existing target without --force, or a\n * WriteConflict from a lost `current.json` CAS against\n * maintenance/compaction during --force.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { type ArgsDef } from \"citty\";\nimport {\n assertCurrentJsonTransition,\n assertDocumentSize,\n assertDocumentValues,\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type CurrentJson,\n type DocumentData,\n encodeJsonBytes,\n gcPendingKey,\n mintGeneration,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { assertDocId, Writer } from \"@baerly/server/_internal/testing\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n assertWritableNames,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"../subcommand.ts\";\nimport { collectionPrefixOf } from \"./usage.ts\";\n\nconst RESTORE_OWNER = \"baerly-restore\";\n\nconst RESTORE_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Target bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: {\n type: \"string\",\n required: true,\n description: \"Target collection name.\",\n valueHint: \"name\",\n },\n force: {\n type: \"boolean\",\n description: \"Reseed the target when it already exists.\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst tailFromListedLogKeys = async (\n storage: Storage,\n collectionPrefix: string,\n): Promise<number> => {\n const logPrefix = `${collectionPrefix}/log/`;\n let maxSeq = -1;\n for await (const entry of storage.list(logPrefix)) {\n const tail = entry.key.slice(logPrefix.length);\n const match = /^(\\d+)\\.json$/.exec(tail);\n if (match === null) {\n continue;\n }\n const seq = Number.parseInt(match[1]!, 10);\n if (Number.isFinite(seq) && seq > maxSeq) {\n maxSeq = seq;\n }\n }\n return maxSeq + 1;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.restore\",\n meta: {\n description:\n \"Bulk-import canonical NDJSON into a fresh collection. Validates per row: rows before a failing line stay committed, and the error reports the count (re-run into a fresh target or with --force). Duplicate or non-NFC/invalid _ids are refused, never rewritten.\",\n },\n args: RESTORE_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly admin restore\");\n assertWritableNames({ app, tenant, collection: args.collection }, \"baerly admin restore\");\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const collectionPrefix = collectionPrefixOf(currentJsonKey);\n const pendingKey = gcPendingKey(collectionPrefix);\n\n let baseSeq = 0;\n const head = await readCurrentJson(bucket.storage, currentJsonKey);\n if (head !== null && args.force !== true) {\n throw new BaerlyError(\n \"AlreadyExists\",\n `baerly admin restore: collection ${JSON.stringify(args.collection)} (app ${JSON.stringify(app)}, tenant ${JSON.stringify(tenant)}) already exists; pass --force to truncate it`,\n {\n resolution:\n \"Pass --force to truncate the existing collection, or restore into an empty target.\",\n },\n );\n }\n if (head !== null) {\n // --force: reseed `current.json` above the old tail under\n // If-Match. The If-Match guards against a concurrent COMPACTOR\n // (the only steady-state writer of `current.json` under\n // single-write commit) landing between our read and our PUT —\n // that surfaces WriteConflict (exit 3). It does NOT fence concurrent\n // WRITERS: under single-write commit writers never touch\n // `current.json`, so the dormant `writer_fence` epoch is no\n // longer consulted. `restore` therefore assumes operational\n // exclusivity — do not run it against a collection taking live\n // writes. (We still bump the fence epoch to keep the field\n // monotone, but nothing reads it.)\n //\n // That contract covers concurrent MAINTENANCE PASSES too, not only\n // concurrent writers, and `runScheduledMaintenance` fires them on a\n // cron independent of writes — so \"no live writes\" is not by\n // itself enough. A GC pass reads `current.json` once at its top and\n // never re-reads it before issuing its sweep DELETEs, so a pass\n // that started before this reseed carries the pre-reseed floor\n // all the way through and, if a legacy ledger hands it `stale-log`\n // candidates, can delete log objects the reseed below re-creates.\n // The ledger clear does not close that window: such a pass loaded\n // its candidates into memory before the clear landed. A concurrent\n // `retireLogRange` is fenced instead of raced — it recomputes its\n // range inside the CAS mutator, so a reseed that lands first makes\n // it abort with `WriteConflict` and zero DELETEs.\n //\n // CRITICAL: stale log entries from the old generation still\n // live on disk under `log/<seq>.json` paths. The writer's\n // `If-None-Match: \"*\"` log PUT will 412 if we restart `tail_hint`\n // at 0 and collide with `log/0.json`. We instead advance\n // `tail_hint` and `log_seq_start` past the old data so new\n // commits land at fresh sequence numbers and the old log files\n // become unreferenced orphans (computed-range retirement reclaims\n // them once the new generation's fold floor advances past them).\n // Do this from LISTed log keys, not\n // by folding the old log bodies: `--force` must be able to recover\n // from malformed old entries, and a hole must not make us\n // under-shoot a later old entry.\n const truncatedNext = await tailFromListedLogKeys(bucket.storage, collectionPrefix);\n baseSeq = truncatedNext;\n // FLOOR EXEMPTION — deliberate. `casUpdateCurrentJson` rejects any\n // write that lowers `log_seq_start`; this PUT is not routed through\n // it, so `--force` can reseed BELOW the old floor. The compactor's\n // fold CAS also bypasses that helper, but calls the shared transition\n // validator directly before publication. `--force` is the only path\n // that intentionally lowers the floor.\n //\n // Why lowering is sound. `truncatedNext` is strictly greater than\n // every log object still on the bucket, so the writer's committing\n // `log/<seq>` create cannot collide with an old-generation object —\n // that 412 hazard is the whole point of the reseed (see above). It\n // can land below the old FOLD floor whenever the surviving log\n // objects stop short of it. Retirement is budget-bounded, so it\n // normally leaves a contiguous suffix and `truncatedNext` reaches\n // the fold floor — but two paths break that. A pass that crashes\n // between its floor CAS and the end of its DELETE loop leaves an\n // arbitrary subset of the authorized range behind\n // (`log-retention.ts`: leak, never corruption), and a failed\n // phantom cleanup on the `AmbiguousCommit` path leaves an isolated\n // sub-floor object. So fold floor 12 with `log/8` and `log/9`\n // retained and `log/10`, `log/11` gone is reachable, yielding\n // `truncatedNext` 10 < 12.\n //\n // Nothing is lost by that. Readers never see the survivors: they\n // walk from the new floor, and `fsck` bounds itself by listed keys,\n // so sub-floor objects produce no findings. The truncate is complete\n // with respect to every reader, which is what truncating means.\n //\n // It is not complete with respect to BYTES, and deliberately so.\n // Resetting `snapshot` to `null` makes the whole old generation\n // unreachable. The surviving sub-floor `log/` objects are reclaimed\n // by computed-range retirement once the new generation's fold floor\n // advances past them — the reseed literal below omits\n // `log_delete_floor`, so it decodes to 0 and the computed range\n // starts there, covering every survivor. Legacy `content/<sha>.json`\n // side objects stay put: no kernel reader opens one, so they are\n // inert, and an operator who wants the bytes back deletes the prefix\n // directly (`docs/guide/backups.md`).\n //\n // Do not \"repair\" this with `Math.max`; that reseeds a floor above\n // `tail_hint`, trips `assertCurrentJson`, and breaks truncate.\n // `restore.test.ts` pins both the empty-prefix and partial-sweep\n // cases.\n // `log_delete_floor` IS DELIBERATELY ABSENT from this literal. Do not\n // \"repair\" that with `...head.json`.\n //\n // Dropping it is the correct truncate semantics: the field is the\n // exclusive upper bound of the contiguous log prefix certified\n // deleted. A truncate starts a new generation, so its certification\n // resets to \"no deleted prefix is certified.\"\n //\n // Carrying it forward is not merely redundant, it is unsound. This PUT\n // is the one `current.json` writer that does not call\n // `assertCurrentJsonTransition` (invariant 12 names it as the deliberate\n // exemption), so a carried floor is published UNCHECKED. A reseed can\n // land below the old delete floor only when the certified old prefix —\n // potentially the entire old log — is gone. With no surviving log\n // objects, LIST yields `truncatedNext = 0`; restored rows then reuse\n // slots below the old floor. Carrying that old-generation certificate\n // would store `log_delete_floor > log_seq_start`, which the very next\n // validated write rejects — in practice this command's own post-reseed\n // tail stamp. `restore.test.ts` pins the empty-old-log case, the field\n // omission, and the subsequent validated transition.\n const reseeded: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n // Also resets `tail_hint` unclamped, so an over-claimed old hint\n // moves DOWN here (unlike the final stamp below, which clamps).\n // Safe: the hint is a non-authoritative lower bound, and the\n // forward-probe finds the true tail regardless.\n tail_hint: truncatedNext,\n log_seq_start: truncatedNext,\n writer_fence: {\n epoch: head.json.writer_fence.epoch + 1,\n owner: RESTORE_OWNER,\n claimed_at: \"\",\n },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n // New generation. This is the one write in the system that\n // lowers `log_seq_start`, so it is the one write that can leave\n // a live `/v1/since` cursor pointing above the floor but into a\n // dead generation. Re-minting here is what lets the next resume\n // on that cursor fail loudly (`CursorExpired` → re-bootstrap)\n // instead of silently skipping the restored rows beneath it.\n generation: mintGeneration(),\n };\n try {\n await bucket.storage.put(currentJsonKey, encodeJsonBytes(reseeded), {\n ifMatch: head.etag,\n contentType: \"application/json\",\n });\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `baerly admin restore: failed to reseed current.json: ${(error as Error).message}`,\n );\n }\n // Clear the GC ledger the old incarnation left behind. A\n // candidate marked before this reseed names a key from the\n // truncated log, which the commits below may re-create at the\n // same seq; the ledger's pending depth no longer describes this\n // collection either. Clear it before the\n // writer's first commit below — write-tick maintenance runs\n // `runGc` inline (CF-free profile, `gcInterval = 4`), so a GC\n // pass can happen during the restore itself. `Storage.delete` is\n // idempotent (404 ⇒ no-op) per the `Storage` contract, so this is\n // safe whether or not a ledger exists.\n await bucket.storage.delete(pendingKey);\n } else {\n // Fresh target: seed `current.json` with `tail_hint=0`. This literal\n // omits `log_delete_floor` too, and correctly: it routes through\n // `createCurrentJson`, so no transition rule applies, and \"no deleted\n // prefix is certified\" is exactly what an absent field decodes to.\n // Named here so a sweep for missing-field sites stops rather than\n // adding it.\n const seed: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: RESTORE_OWNER, claimed_at: \"\" },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n // Mint here too, even though there is no old generation at this\n // key right now. A client can still hold a cursor from a\n // previous incarnation of this collection (dropped, then\n // restored), and `writer_fence.epoch` resets to 0 on this branch\n // — which is exactly why the epoch cannot serve as the\n // discriminator and a nonce can.\n generation: mintGeneration(),\n };\n await createCurrentJson(bucket.storage, currentJsonKey, seed);\n // Same clear as the `--force` branch above, for the case where\n // `current.json` is absent but a ledger is not. There is no\n // `admin drop` subcommand, so this is not a product path — it is\n // reachable by operator surgery (deleting `current.json` by hand,\n // or restoring into a prefix a previous collection used) and by a\n // partially-completed reseed. Cheap insurance rather than a case\n // the CLI can produce on its own; must land before the writer's\n // first commit either way.\n await bucket.storage.delete(pendingKey);\n }\n\n const writer = new Writer({ storage: bucket.storage, currentJsonKey });\n\n const input = ctx.streams?.stdin ?? process.stdin;\n const rl = createInterface({ input, crlfDelay: Infinity });\n let count = 0;\n let lineNo = 0;\n const seenIds = new Map<string, number>();\n // Every failure past this point says how many rows are already\n // durable, so the operator knows what the target now holds.\n const committedNote = (when = \"before this line\"): string =>\n `; ${count} row${count === 1 ? \"\" : \"s\"} committed ${when} (they remain in the target; restore again into a fresh target, or with --force)`;\n const idFix =\n \"Restore never rewrites an _id. Fix the dump line, or rewrite it to a fresh NFC _id that is not canonically equivalent to the original.\";\n // Catch iterator failures separately from validation and commit failures,\n // which already carry their line-specific progress (or ambiguity range).\n const lines = (async function* () {\n try {\n yield* rl;\n } catch (error) {\n const failure = error instanceof Error ? error : new Error(String(error));\n failure.message += committedNote(\"before input failed\");\n throw failure;\n }\n })();\n try {\n for await (const line of lines) {\n lineNo++;\n if (line.length === 0) {\n continue;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n // Malformed NDJSON mid-stream → exit 2. Bare `Error` (not\n // `BaerlyError`) routes through the helper's \"unknown\" arm.\n throw new Error(\n `baerly admin restore: line ${lineNo} is not valid JSON: ${(error as Error).message}${committedNote()}`,\n { cause: error },\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\n `baerly admin restore: line ${lineNo} is not a JSON object${committedNote()}`,\n );\n }\n const row = parsed as Record<string, unknown>;\n const id = row[\"_id\"];\n if (typeof id !== \"string\" || id.length === 0) {\n const fix = \"Add a non-empty string _id to the dump line.\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin restore: line ${lineNo} missing non-empty string _id${committedNote()}. ${fix}`,\n { resolution: fix },\n );\n }\n const firstLine = seenIds.get(id);\n if (firstLine !== undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin restore: line ${lineNo} repeats _id ${JSON.stringify(id)} first seen on line ${firstLine}${committedNote()}. ${idFix}`,\n { resolution: idFix },\n );\n }\n try {\n assertDocId(id);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin restore: line ${lineNo} has an invalid _id ${JSON.stringify(id)}: ${(error as Error).message}${committedNote()}. ${idFix}`,\n { cause: error, resolution: idFix },\n );\n }\n seenIds.set(id, lineNo);\n // Document-value domain: JSON.parse can still yield a value the\n // write path refuses (`1e999` parses to Infinity), or a row an\n // earlier release stored over the per-document size cap.\n try {\n assertDocumentValues(row, \"restore\");\n assertDocumentSize(row, \"restore\");\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin restore: line ${lineNo} (_id ${JSON.stringify(id)}) has an invalid document: ${error.message}${committedNote()}${error.resolution === undefined ? \"\" : `. ${error.resolution}`}`,\n { cause: error, resolution: error.resolution },\n );\n }\n throw error;\n }\n\n // Pass the full object as the body — `_id` is part of the\n // body in the doc shape, and the writer keys on `docId`\n // separately.\n const body = row as unknown as DocumentData;\n try {\n await writer.commit({\n op: \"I\",\n collection: args.collection,\n docId: id,\n body,\n });\n } catch (error) {\n if (error instanceof Error) {\n if ((error as { code?: unknown }).code === \"AmbiguousCommit\") {\n // The committing create's fate is unresolved: line N may\n // already be durable, so the count is a range, not a figure.\n error.message += `; line ${lineNo} may or may not be committed (between ${count} and ${count + 1} rows are in the target); restore again with --force to get an exact copy of the dump`;\n } else {\n error.message += `; line ${lineNo} was not committed${committedNote()}`;\n }\n }\n throw error;\n }\n count++;\n }\n } finally {\n rl.close();\n }\n // Stamp the final `tail_hint` durably. Under single-write commit the\n // writer never advances the hint (it's compactor-advanced) — but a\n // bulk restore knows exactly how many rows it wrote, so it stamps the\n // true tail (`baseSeq + count`) under If-Match so the restored bucket\n // reads efficiently without a forward-probe. A concurrent compactor\n // between our last commit and this stamp surfaces WriteConflict (exit 3).\n // CLAMP: `tail_hint` is a monotone lower bound, so never stamp it\n // BELOW what is already durable — take the max of our computed tail,\n // the value already stored, and `log_seq_start`. (Defends against a\n // compactor that advanced the hint between the reseed and here.)\n if (count > 0) {\n try {\n const afterLoad = await readCurrentJson(bucket.storage, currentJsonKey);\n if (afterLoad !== null) {\n const clampedTail = Math.max(\n baseSeq + count,\n afterLoad.json.tail_hint,\n afterLoad.json.log_seq_start,\n );\n const stamped: CurrentJson = { ...afterLoad.json, tail_hint: clampedTail };\n assertCurrentJsonTransition(afterLoad.json, stamped, currentJsonKey);\n await bucket.storage.put(currentJsonKey, encodeJsonBytes(stamped), {\n ifMatch: afterLoad.etag,\n contentType: \"application/json\",\n });\n }\n } catch (error) {\n // No retry: the If-Match stop-rule holds. All rows are durable;\n // only the read-efficiency hint is missing, and a rerun with\n // --force truncates the collection and restores it cleanly.\n throw new BaerlyError(\n error instanceof BaerlyError ? error.code : \"NetworkError\",\n `baerly admin restore: all ${count} row${count === 1 ? \"\" : \"s\"} were committed, but stamping tail_hint on current.json failed: ${(error as Error).message}. Rerun restore with --force to truncate and restore the dump again.`,\n { cause: error },\n );\n }\n }\n emitSuccess({\n command: \"admin.restore\",\n status: \"ok\",\n collection: args.collection,\n restored: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin restore`. */\nexport const restoreCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runRestore = bundle.run;\n"],"mappings":";;;;;;;;;;;;AAGA,MAAa,mBAA6D;CACxE,eACE;CACF,eACE;CACF,iBACE;CACF,kBACE;CACF,oBACE;CACF,eACE;CACF,iBAAiB;CACjB,sBACE;CACF,cAAc;CACd,cAAc;CACd,UAAU;AACZ;;ACQA,MAAM,wBACJ;AACF,MAAM,8BACJ;AACF,MAAM,+BACJ;AACF,MAAM,uBACJ;AACF,MAAM,2BACJ;AACF,MAAM,qBACJ;AACF,MAAM,sBACJ;AACF,MAAM,mBAAmB;;AAGzB,MAAM,eAAe,UAA2B;CAC9C,KACE,IAAI,KAAoB,OACxB,OAAO,MACP,KAAK,OAAO,eAAe,EAAE,GAC7B;EACA,MAAM,aAAa,OAAO,yBAAyB,IAAI,QAAQ;EAC/D,IAAI,eAAe,KAAA,GAGjB,OAAO,EAAE,WAAW,eAAe,OAAO,WAAW,UAAU;CAEnE;CACA,OAAO;AACT;AAWA,MAAM,aAAa;AAEnB,MAAM,iBAAiB,QAAiC;CACtD,IAAI,OAAO,QAAQ,UACjB,OAAO,IAAI,IAAI;CAEjB,IAAI,IAAI,SAAA,IACN,OAAO,IAAI,KAAK,UAAU,IAAI,MAAM,GAAA,EAAgC,CAAC,EAAE;CAEzE,OAAO,WAAW,KAAK,GAAG,IAAI,IAAI,QAAQ,IAAI,KAAK,UAAU,GAAG,EAAE;AACpE;;AAGA,MAAM,UAAU,OAAwC;CACtD,MAAM,OAA+B,CAAC;CACtC,KAAK,IAAI,OAA4B,IAAI,MAAM,QAAQ,KAAA,GAAW,OAAO,KAAK,QAC5E,KAAK,KAAK,KAAK,GAAG;CAEpB,KAAK,QAAQ;CACb,OAAO;AACT;;;;;;AAOA,MAAM,UAAU,OAAwB;CACtC,MAAM,OAAO,OAAO,EAAE;CAEtB,MAAM,OACJ,KAAK,SAAS,IACV,GAAG,KAAK,MAAM,GAAG,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U;KACnB,aAAa;IACf,CAAC;GACH;EACF,SAAS,OAAO;GAId,MAAM,IAAI,YACR,iBAAiB,cAAc,MAAM,OAAO,gBAC5C,6BAA6B,MAAM,MAAM,UAAU,IAAI,KAAK,IAAI,kEAAmE,MAAgB,QAAQ,uEAC3J,EAAE,OAAO,MAAM,CACjB;EACF;EAEF,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,UAAU;EACZ,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,aAAa,OAAO;AAOP,OAAO"}
@@ -0,0 +1,126 @@
1
+ import { w as STORAGE_RETRY_MAX_DELAY_MILLIS } from "./constants-D3GSH3tc.js";
2
+ import { i as isWriteConflict, t as BaerlyError } from "./errors-7Rk1HGCE.js";
3
+ import { t as delay } from "./time-DRxTP9iv.js";
4
+ import { n as currentRequestHold, r as currentRequestLedger } from "./ledger-Dj_bGgo0.js";
5
+ // packages/protocol/src/storage/retry.ts
6
+ /**
7
+ * Permanent {@link BaerlyError} codes that end `retryStorageCall` at
8
+ * once. These represent caller- or environment-level faults where
9
+ * retrying cannot succeed: `AccessDenied` (403 — credentials/policy),
10
+ * `InvalidConfig` (bad bucket / unsupported credential type),
11
+ * `InvalidResponse` (server returned unparseable data), and
12
+ * `WriteConflict` (a precondition was rejected). `NetworkError` is
13
+ * intentionally absent — it covers transient transport faults and stays
14
+ * retryable.
15
+ *
16
+ * Storage-layer set, distinct from `RETRIABLE_CODES` in `errors.ts`. A
17
+ * blind re-PUT of the same request re-loses a rejected precondition, so
18
+ * this layer never resends it. `WriteConflict` is still retriable for the
19
+ * logical caller: it re-reads and issues a new request, which is what
20
+ * `retriable` means.
21
+ */
22
+ const PERMANENT_STORAGE_ERROR_CODES = /* @__PURE__ */ new Set([
23
+ "AccessDenied",
24
+ "InvalidConfig",
25
+ "InvalidResponse",
26
+ "WriteConflict"
27
+ ]);
28
+ /** `true` when an attempt uses the throttle backoff. */
29
+ const isThrottled = (e) => e instanceof BaerlyError && e.cause?.throttled === true;
30
+ /**
31
+ * `true` when an attempt was refused before it was issued and a resend
32
+ * in the same invocation is refused too (the Workers subrequest limit).
33
+ * This proves the attempt was not applied and ends the loop at once.
34
+ */
35
+ const isRefused = (e) => e instanceof BaerlyError && e.cause?.refused === true;
36
+ /**
37
+ * `true` for an `AbortError`: a cancellation raised by a call that did
38
+ * not pass its signal in {@link StorageRetryOptions.signal}. A resend
39
+ * would fail the same way, so the loop ends and the error surfaces as is,
40
+ * as the other adapters raise it. Matched on `name` like the writer's
41
+ * predicate: workerd and undici reject with different `DOMException`
42
+ * classes. A passed signal covers every abort reason, not only this name.
43
+ */
44
+ const isAbortError = (e) => typeof e === "object" && e !== null && "name" in e && e.name === "AbortError";
45
+ const retryAfterMillis = (e) => {
46
+ if (!(e instanceof BaerlyError)) return;
47
+ const seconds = e.cause?.retryAfterSeconds;
48
+ return seconds === void 0 ? void 0 : seconds * 1e3;
49
+ };
50
+ /**
51
+ * The wait before retry `retryIndex` (0-based) after `error`.
52
+ *
53
+ * A server `Retry-After` hint (`cause.retryAfterSeconds`) wins, clamped
54
+ * to `STORAGE_RETRY_MAX_DELAY_MILLIS`. Otherwise full jitter:
55
+ * `random() * min(cap, base * 2^retryIndex)`, with the throttle base for
56
+ * an error whose cause carries `throttled: true` and the transient base
57
+ * for everything else, unless `backoffMs` overrides both.
58
+ */
59
+ const storageRetryDelayMillis = (error, retryIndex, opts = {}) => {
60
+ const hintMs = retryAfterMillis(error);
61
+ if (hintMs !== void 0) return Math.min(hintMs, STORAGE_RETRY_MAX_DELAY_MILLIS);
62
+ const base = opts.backoffMs ?? (isThrottled(error) ? 1e3 : 50);
63
+ const ceiling = Math.min(STORAGE_RETRY_MAX_DELAY_MILLIS, base * 2 ** retryIndex);
64
+ return (opts.random ?? Math.random)() * ceiling;
65
+ };
66
+ /**
67
+ * Run one storage request under the single adapter retry policy: at most
68
+ * `retries + 1` attempts (default {@link STORAGE_RETRY_MAX_ATTEMPTS}; one
69
+ * for a `compareAndSwap` call),
70
+ * one counter for throttles and transient failures alike, full-jitter
71
+ * backoff between attempts (see {@link storageRetryDelayMillis}). A
72
+ * {@link PERMANENT_STORAGE_ERROR_CODES} failure, an error whose cause
73
+ * carries `refused: true`, an `AbortError`, or a failure after
74
+ * `opts.signal` aborted ends the loop at once.
75
+ *
76
+ * Every adapter wraps each request — one object call, or one `list`
77
+ * page — in exactly one `retryStorageCall`, so a failing call costs at
78
+ * most `retries + 1` requests. Callers above the `Storage` boundary must
79
+ * not add their own blind resend loop on top.
80
+ *
81
+ * Each attempt is charged to the active invocation's request ledger
82
+ * ({@link currentRequestLedger}) on `opts.pool` before it is sent. An
83
+ * attempt the ledger refuses is never sent: the refusal (`CapacityExceeded`,
84
+ * `cause.refused`) ends the loop like any refusal.
85
+ */
86
+ const retryStorageCall = async (fn, opts = {}) => {
87
+ const retries = opts.compareAndSwap === true ? 0 : opts.retries ?? 2;
88
+ if (!Number.isSafeInteger(retries) || retries < 0) throw new BaerlyError("InvalidConfig", `storage retries must be a non-negative integer, got ${String(retries)}`);
89
+ const sleep = opts.sleep ?? delay;
90
+ const ledger = currentRequestLedger();
91
+ const pool = opts.pool ?? "external";
92
+ let uncertain = false;
93
+ for (let attempt = 0; attempt <= retries; attempt++) try {
94
+ opts.signal?.throwIfAborted();
95
+ ledger?.acquire(pool, currentRequestHold());
96
+ return await fn();
97
+ } catch (error) {
98
+ const aborted = opts.signal?.aborted === true;
99
+ if (isAbortError(error) || aborted && !(error instanceof BaerlyError)) throw error;
100
+ if (error instanceof BaerlyError && PERMANENT_STORAGE_ERROR_CODES.has(error.code)) {
101
+ if (opts.conditionalCreate === true && uncertain && !isWriteConflict(error)) throw new BaerlyError("NetworkError", `${error.message} (an earlier attempt of this conditional create may have landed)`, { cause: error });
102
+ throw error;
103
+ }
104
+ const refused = isRefused(error);
105
+ const mayHaveApplied = error instanceof BaerlyError && error.cause?.mayHaveApplied === true;
106
+ if (!isThrottled(error) && !refused || mayHaveApplied) uncertain = true;
107
+ if (attempt >= retries || refused || aborted) {
108
+ if (opts.conditionalCreate === true && error instanceof BaerlyError) {
109
+ if (!uncertain) throw new BaerlyError(error.code, error.message, {
110
+ cause: {
111
+ ...error.cause,
112
+ notApplied: true
113
+ },
114
+ ...error.resolution !== void 0 && { resolution: error.resolution }
115
+ });
116
+ if (refused && error.code !== "NetworkError") throw new BaerlyError("NetworkError", `${error.message} (an earlier attempt of this conditional create may have landed)`, { cause: error.cause });
117
+ }
118
+ throw error;
119
+ }
120
+ await sleep(storageRetryDelayMillis(error, attempt, opts));
121
+ }
122
+ throw new BaerlyError("Internal", "storage retry loop exited without returning or throwing");
123
+ };
124
+ export { retryStorageCall as t };
125
+
126
+ //# sourceMappingURL=retry-OBtLB2GC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry-OBtLB2GC.js","names":[],"sources":["../packages/protocol/src/storage/retry.ts"],"sourcesContent":["import {\n STORAGE_RETRY_MAX_ATTEMPTS,\n STORAGE_RETRY_MAX_DELAY_MILLIS,\n STORAGE_RETRY_THROTTLE_BASE_MILLIS,\n STORAGE_RETRY_TRANSIENT_BASE_MILLIS,\n} from \"../constants.ts\";\nimport { BaerlyError, isWriteConflict, type BaerlyErrorCode } from \"../errors.ts\";\nimport { delay } from \"../time.ts\";\nimport { currentRequestHold, currentRequestLedger, type RequestPool } from \"./ledger.ts\";\n\n/**\n * Permanent {@link BaerlyError} codes that end `retryStorageCall` at\n * once. These represent caller- or environment-level faults where\n * retrying cannot succeed: `AccessDenied` (403 — credentials/policy),\n * `InvalidConfig` (bad bucket / unsupported credential type),\n * `InvalidResponse` (server returned unparseable data), and\n * `WriteConflict` (a precondition was rejected). `NetworkError` is\n * intentionally absent — it covers transient transport faults and stays\n * retryable.\n *\n * Storage-layer set, distinct from `RETRIABLE_CODES` in `errors.ts`. A\n * blind re-PUT of the same request re-loses a rejected precondition, so\n * this layer never resends it. `WriteConflict` is still retriable for the\n * logical caller: it re-reads and issues a new request, which is what\n * `retriable` means.\n */\nexport const PERMANENT_STORAGE_ERROR_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>(\n [\"AccessDenied\", \"InvalidConfig\", \"InvalidResponse\", \"WriteConflict\"],\n);\n\n/** Options for {@link retryStorageCall}. */\nexport interface StorageRetryOptions {\n /**\n * Retries after the first attempt: a non-negative integer, else the\n * call rejects with `InvalidConfig` before any attempt. Default\n * `STORAGE_RETRY_MAX_ATTEMPTS - 1`; `0` makes exactly one attempt.\n */\n readonly retries?: number;\n /**\n * Backoff base override in ms, applied to every failure class. Omit\n * for the default policy: `STORAGE_RETRY_TRANSIENT_BASE_MILLIS` after\n * a transient failure, `STORAGE_RETRY_THROTTLE_BASE_MILLIS` after a\n * throttle.\n */\n readonly backoffMs?: number;\n /**\n * Set for an `If-None-Match: \"*\"` create. An attempt that failed\n * transiently may still have landed, so a later permanent rejection\n * other than `WriteConflict` (for example a 403) cannot prove the\n * create is not durable; it is reported as `NetworkError` carrying the original\n * error as its cause, per the `Storage.put` contract. When every\n * attempt was throttled (`cause.throttled`) or refused\n * (`cause.refused`, which also ends the loop), the final `NetworkError`'s\n * cause carries `notApplied: true`, unless a throttle's cause carries\n * `mayHaveApplied: true` because the adapter cannot prove its outcome.\n */\n readonly conditionalCreate?: boolean;\n /**\n * Set for an `If-Match` PUT (a compare-and-swap). It gets exactly one\n * attempt, whatever `retries` says: if an attempt lands but its reply is\n * lost or comes back as a 5xx, a resend meets the request's own write as\n * a 412 and reports a false `WriteConflict`. Every in-tree CAS caller\n * treats a failure as \"skip; the next pass re-reads\", so the failure goes\n * straight to it. Adapters set this from `StoragePutOptions.ifMatch`.\n */\n readonly compareAndSwap?: boolean;\n /**\n * The {@link RequestPool} each attempt is charged to on the active\n * invocation's request ledger. `\"internal\"` for a call that stays\n * inside the host (the R2 binding); `\"external\"`, the default, for one\n * that leaves through `fetch`.\n */\n readonly pool?: RequestPool;\n /**\n * The caller's `AbortSignal`. Once it has aborted, whatever the reason,\n * no further attempt is signed, backed off or sent: an attempt that\n * fails after the abort ends the loop, and a backoff the abort lands in\n * ends with `signal.reason`, subject to conditional-create uncertainty\n * handling. A failure that is not a {@link BaerlyError}\n * (the adapter's rethrown abort reason) surfaces as is; a `BaerlyError`\n * goes through the final-attempt path, so a conditional create keeps\n * its unknown outcome.\n */\n readonly signal?: AbortSignal;\n /** Jitter source in `[0, 1)`. Test seam; defaults to `Math.random`. */\n readonly random?: () => number;\n /** Backoff sleep. Test seam; defaults to `delay`. */\n readonly sleep?: (ms: number) => Promise<void>;\n}\n\n/** `true` when an attempt uses the throttle backoff. */\nconst isThrottled = (e: unknown): boolean =>\n e instanceof BaerlyError && (e.cause as { throttled?: boolean } | undefined)?.throttled === true;\n\n/**\n * `true` when an attempt was refused before it was issued and a resend\n * in the same invocation is refused too (the Workers subrequest limit).\n * This proves the attempt was not applied and ends the loop at once.\n */\nconst isRefused = (e: unknown): boolean =>\n e instanceof BaerlyError && (e.cause as { refused?: boolean } | undefined)?.refused === true;\n\n/**\n * `true` for an `AbortError`: a cancellation raised by a call that did\n * not pass its signal in {@link StorageRetryOptions.signal}. A resend\n * would fail the same way, so the loop ends and the error surfaces as is,\n * as the other adapters raise it. Matched on `name` like the writer's\n * predicate: workerd and undici reject with different `DOMException`\n * classes. A passed signal covers every abort reason, not only this name.\n */\nconst isAbortError = (e: unknown): boolean =>\n typeof e === \"object\" && e !== null && \"name\" in e && e.name === \"AbortError\";\n\nconst retryAfterMillis = (e: unknown): number | undefined => {\n if (!(e instanceof BaerlyError)) {\n return undefined;\n }\n const seconds = (e.cause as { retryAfterSeconds?: number } | undefined)?.retryAfterSeconds;\n return seconds === undefined ? undefined : seconds * 1000;\n};\n\n/**\n * The wait before retry `retryIndex` (0-based) after `error`.\n *\n * A server `Retry-After` hint (`cause.retryAfterSeconds`) wins, clamped\n * to `STORAGE_RETRY_MAX_DELAY_MILLIS`. Otherwise full jitter:\n * `random() * min(cap, base * 2^retryIndex)`, with the throttle base for\n * an error whose cause carries `throttled: true` and the transient base\n * for everything else, unless `backoffMs` overrides both.\n */\nexport const storageRetryDelayMillis = (\n error: unknown,\n retryIndex: number,\n opts: Pick<StorageRetryOptions, \"backoffMs\" | \"random\"> = {},\n): number => {\n const hintMs = retryAfterMillis(error);\n if (hintMs !== undefined) {\n return Math.min(hintMs, STORAGE_RETRY_MAX_DELAY_MILLIS);\n }\n const base =\n opts.backoffMs ??\n (isThrottled(error) ? STORAGE_RETRY_THROTTLE_BASE_MILLIS : STORAGE_RETRY_TRANSIENT_BASE_MILLIS);\n const ceiling = Math.min(STORAGE_RETRY_MAX_DELAY_MILLIS, base * 2 ** retryIndex);\n return (opts.random ?? Math.random)() * ceiling;\n};\n\n/**\n * Run one storage request under the single adapter retry policy: at most\n * `retries + 1` attempts (default {@link STORAGE_RETRY_MAX_ATTEMPTS}; one\n * for a `compareAndSwap` call),\n * one counter for throttles and transient failures alike, full-jitter\n * backoff between attempts (see {@link storageRetryDelayMillis}). A\n * {@link PERMANENT_STORAGE_ERROR_CODES} failure, an error whose cause\n * carries `refused: true`, an `AbortError`, or a failure after\n * `opts.signal` aborted ends the loop at once.\n *\n * Every adapter wraps each request — one object call, or one `list`\n * page — in exactly one `retryStorageCall`, so a failing call costs at\n * most `retries + 1` requests. Callers above the `Storage` boundary must\n * not add their own blind resend loop on top.\n *\n * Each attempt is charged to the active invocation's request ledger\n * ({@link currentRequestLedger}) on `opts.pool` before it is sent. An\n * attempt the ledger refuses is never sent: the refusal (`CapacityExceeded`,\n * `cause.refused`) ends the loop like any refusal.\n */\nexport const retryStorageCall = async <T>(\n fn: () => Promise<T>,\n opts: StorageRetryOptions = {},\n): Promise<T> => {\n const retries =\n opts.compareAndSwap === true ? 0 : (opts.retries ?? STORAGE_RETRY_MAX_ATTEMPTS - 1);\n // A non-integer cap would end the loop between attempts and drop the\n // real error; reject it before any request is sent.\n if (!Number.isSafeInteger(retries) || retries < 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `storage retries must be a non-negative integer, got ${String(retries)}`,\n );\n }\n const sleep = opts.sleep ?? delay;\n const ledger = currentRequestLedger();\n const pool = opts.pool ?? \"external\";\n // Set once an attempt of a conditional create ends with an unknown outcome.\n let uncertain = false;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n // A backoff abort must preserve an earlier create's unknown outcome.\n opts.signal?.throwIfAborted();\n ledger?.acquire(pool, currentRequestHold());\n return await fn();\n } catch (error) {\n const aborted = opts.signal?.aborted === true;\n if (isAbortError(error) || (aborted && !(error instanceof BaerlyError))) {\n throw error;\n }\n if (error instanceof BaerlyError && PERMANENT_STORAGE_ERROR_CODES.has(error.code)) {\n if (opts.conditionalCreate === true && uncertain && !isWriteConflict(error)) {\n throw new BaerlyError(\n \"NetworkError\",\n `${error.message} (an earlier attempt of this conditional create may have landed)`,\n { cause: error },\n );\n }\n throw error;\n }\n const refused = isRefused(error);\n const mayHaveApplied =\n error instanceof BaerlyError &&\n (error.cause as { mayHaveApplied?: boolean } | undefined)?.mayHaveApplied === true;\n if ((!isThrottled(error) && !refused) || mayHaveApplied) {\n uncertain = true;\n }\n // The attempt cap and a refusal end here, through the one final-attempt\n // path. Only a create whose every attempt was provably unapplied\n // reports `notApplied`; a throttle may retain an unknown outcome.\n if (attempt >= retries || refused || aborted) {\n if (opts.conditionalCreate === true && error instanceof BaerlyError) {\n if (!uncertain) {\n throw new BaerlyError(error.code, error.message, {\n cause: {\n ...(error.cause as object),\n notApplied: true,\n },\n ...(error.resolution !== undefined && { resolution: error.resolution }),\n });\n }\n if (refused && error.code !== \"NetworkError\") {\n // A ledger refusal proves only that THIS attempt was not sent;\n // an earlier uncertain one may have landed, so the create's\n // fate is unknown, as for a permanent rejection above.\n throw new BaerlyError(\n \"NetworkError\",\n `${error.message} (an earlier attempt of this conditional create may have landed)`,\n { cause: error.cause },\n );\n }\n }\n throw error;\n }\n await sleep(storageRetryDelayMillis(error, attempt, opts));\n }\n }\n throw new BaerlyError(\"Internal\", \"storage retry loop exited without returning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C5B,QAAQ,QAAQ,MAAM,mBAAmB,CAAC;EAC1C,OAAO,MAAM,GAAG;CAClB,SAAS,OAAO;EACd,MAAM,UAAU,KAAK,QAAQ,YAAY;EACzC,IAAI,aAAa,KAAK,KAAM,WAAW,EAAE,iBAAiB,cACxD,MAAM;EAER,IAAI,iBAAiB,eAAe,8BAA8B,IAAI,MAAM,IAAI,GAAG;GACjF,IAAI,KAAK,sBAAsB,QAAQ,aAAa,CAAC,gBAAgB,KAAK,GACxE,MAAM,IAAI,YACR,gBACA,GAAG,MAAM,QAAQ,mEACjB,EAAE,OAAO,MAAM,CACjB;GAEF,MAAM;EACR;EACA,MAAM,UAAU,UAAU,KAAK;EAC/B,MAAM,iBACJ,iBAAiB,eAChB,MAAM,OAAoD,mBAAmB;EAChF,IAAK,CAAC,YAAY,KAAK,KAAK,CAAC,WAAY,gBACvC,YAAY;EAKd,IAAI,WAAW,WAAW,WAAW,SAAS;GAC5C,IAAI,KAAK,sBAAsB,QAAQ,iBAAiB,aAAa;IACnE,IAAI,CAAC,WACH,MAAM,IAAI,YAAY,MAAM,MAAM,MAAM,SAAS;KAC/C,OAAO;MACL,GAAI,MAAM;MACV,YAAY;KACd;KACA,GAAI,MAAM,eAAe,KAAA,KAAa,EAAE,YAAY,MAAM,WAAW;IACvE,CAAC;IAEH,IAAI,WAAW,MAAM,SAAS,gBAI5B,MAAM,IAAI,YACR,gBACA,GAAG,MAAM,QAAQ,mEACjB,EAAE,OAAO,MAAM,MAAM,CACvB;GAEJ;GACA,MAAM;EACR;EACA,MAAM,MAAM,wBAAwB,OAAO,SAAS,IAAI,CAAC;CAC3D;CAEF,MAAM,IAAI,YAAY,YAAY,yDAAyD;AAC7F"}
@@ -0,0 +1,12 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, flags) => {
4
+ let target = Object.setPrototypeOf({}, null);
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return flags & 2 ? target : Object.preventExtensions(target);
11
+ };
12
+ export { __exportAll as t };