@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.2

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 (178) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +2 -0
  3. package/PATENTS +12 -0
  4. package/README.md +93 -2
  5. package/dist/index.js +125 -0
  6. package/package.json +57 -4
  7. package/template/Dockerfile +37 -0
  8. package/template/README.md +389 -0
  9. package/template/_dockerignore +6 -0
  10. package/template/_env.example +122 -0
  11. package/template/_github/workflows/ci.yml +23 -0
  12. package/template/_gitignore +8 -0
  13. package/template/_prettierrc +6 -0
  14. package/template/apps/api/API.md +119 -0
  15. package/template/apps/api/package.json +39 -0
  16. package/template/apps/api/src/auth.ts +55 -0
  17. package/template/apps/api/src/bound-profiles.ts +590 -0
  18. package/template/apps/api/src/claims.ts +204 -0
  19. package/template/apps/api/src/cli.ts +99 -0
  20. package/template/apps/api/src/config.ts +180 -0
  21. package/template/apps/api/src/custody.ts +358 -0
  22. package/template/apps/api/src/dev-index.ts +120 -0
  23. package/template/apps/api/src/env-file.ts +55 -0
  24. package/template/apps/api/src/env.ts +14 -0
  25. package/template/apps/api/src/epcis/exchange.ts +434 -0
  26. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  27. package/template/apps/api/src/epcis/routes.ts +364 -0
  28. package/template/apps/api/src/epcis/sources.ts +142 -0
  29. package/template/apps/api/src/go-live.ts +226 -0
  30. package/template/apps/api/src/http-error.ts +15 -0
  31. package/template/apps/api/src/identifiers.ts +57 -0
  32. package/template/apps/api/src/index-client.ts +261 -0
  33. package/template/apps/api/src/index-projects.ts +53 -0
  34. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  35. package/template/apps/api/src/lifecycle.ts +485 -0
  36. package/template/apps/api/src/main.ts +58 -0
  37. package/template/apps/api/src/parties.ts +68 -0
  38. package/template/apps/api/src/platform.ts +176 -0
  39. package/template/apps/api/src/portability/commands.ts +224 -0
  40. package/template/apps/api/src/portability/export.ts +708 -0
  41. package/template/apps/api/src/portability/package.ts +270 -0
  42. package/template/apps/api/src/portability/restore.ts +863 -0
  43. package/template/apps/api/src/profiles.ts +125 -0
  44. package/template/apps/api/src/reader.ts +265 -0
  45. package/template/apps/api/src/resolver.ts +159 -0
  46. package/template/apps/api/src/sector-examples.ts +390 -0
  47. package/template/apps/api/src/server.ts +613 -0
  48. package/template/apps/api/src/store.ts +426 -0
  49. package/template/apps/api/src/validation-engine.ts +172 -0
  50. package/template/apps/api/src/wallet.ts +359 -0
  51. package/template/apps/api/src/worker.ts +113 -0
  52. package/template/apps/api/src/writer.ts +603 -0
  53. package/template/apps/api/test/bound-http.test.ts +496 -0
  54. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  55. package/template/apps/api/test/config.test.ts +160 -0
  56. package/template/apps/api/test/custody-journal.test.ts +415 -0
  57. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  58. package/template/apps/api/test/custom-profile.test.ts +167 -0
  59. package/template/apps/api/test/env-file.test.ts +53 -0
  60. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  61. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  62. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  63. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  64. package/template/apps/api/test/epcis-web.test.ts +230 -0
  65. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  66. package/template/apps/api/test/external-index.test.ts +32 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  89. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  90. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  91. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  92. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  93. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  94. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  95. package/template/apps/api/test/go-live.test.ts +179 -0
  96. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  97. package/template/apps/api/test/gs1-test-env.ts +5 -0
  98. package/template/apps/api/test/identifier-host.test.ts +256 -0
  99. package/template/apps/api/test/index-projects.test.ts +81 -0
  100. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  101. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  102. package/template/apps/api/test/lifecycle.test.ts +147 -0
  103. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  104. package/template/apps/api/test/network-guard.ts +113 -0
  105. package/template/apps/api/test/portability.test.ts +655 -0
  106. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  107. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  108. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  109. package/template/apps/api/test/sector-forms.test.ts +420 -0
  110. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  111. package/template/apps/api/test/validation-engine.test.ts +328 -0
  112. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  113. package/template/apps/api/test/writer-journal.test.ts +327 -0
  114. package/template/apps/api/tsconfig.json +9 -0
  115. package/template/apps/api/vitest.config.ts +12 -0
  116. package/template/apps/web/components.json +21 -0
  117. package/template/apps/web/index.html +12 -0
  118. package/template/apps/web/package.json +33 -0
  119. package/template/apps/web/src/app.tsx +55 -0
  120. package/template/apps/web/src/components/bits.tsx +188 -0
  121. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  122. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  123. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  124. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  125. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  126. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  127. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  128. package/template/apps/web/src/components/layout.tsx +135 -0
  129. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  130. package/template/apps/web/src/components/passport-form.tsx +244 -0
  131. package/template/apps/web/src/components/read-passport.tsx +49 -0
  132. package/template/apps/web/src/components/reading.tsx +150 -0
  133. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  134. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  135. package/template/apps/web/src/components/ui/button.tsx +63 -0
  136. package/template/apps/web/src/components/ui/card.tsx +91 -0
  137. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  138. package/template/apps/web/src/components/ui/input.tsx +20 -0
  139. package/template/apps/web/src/components/ui/label.tsx +21 -0
  140. package/template/apps/web/src/components/ui/select.tsx +189 -0
  141. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  142. package/template/apps/web/src/components/ui/table.tsx +115 -0
  143. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  144. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  145. package/template/apps/web/src/index.css +81 -0
  146. package/template/apps/web/src/lib/api.ts +396 -0
  147. package/template/apps/web/src/lib/auth.ts +10 -0
  148. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  149. package/template/apps/web/src/lib/bound/display.ts +122 -0
  150. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  151. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  152. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  153. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  154. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  155. package/template/apps/web/src/lib/bound/units.ts +37 -0
  156. package/template/apps/web/src/lib/epcis.ts +345 -0
  157. package/template/apps/web/src/lib/format.ts +87 -0
  158. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  159. package/template/apps/web/src/lib/session.tsx +92 -0
  160. package/template/apps/web/src/lib/use-load.ts +46 -0
  161. package/template/apps/web/src/main.tsx +18 -0
  162. package/template/apps/web/src/pages/accept.tsx +113 -0
  163. package/template/apps/web/src/pages/brand.tsx +94 -0
  164. package/template/apps/web/src/pages/brands.tsx +104 -0
  165. package/template/apps/web/src/pages/events.tsx +388 -0
  166. package/template/apps/web/src/pages/home.tsx +51 -0
  167. package/template/apps/web/src/pages/new-passport.tsx +137 -0
  168. package/template/apps/web/src/pages/operations.tsx +169 -0
  169. package/template/apps/web/src/pages/passport.tsx +632 -0
  170. package/template/apps/web/src/pages/public-passport.tsx +64 -0
  171. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  172. package/template/apps/web/src/pages/verify.tsx +30 -0
  173. package/template/apps/web/src/pages/wallet.tsx +141 -0
  174. package/template/apps/web/tsconfig.json +29 -0
  175. package/template/apps/web/vite.config.ts +23 -0
  176. package/template/deploy/compose.yml +38 -0
  177. package/template/package.json +48 -0
  178. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,381 @@
1
+ // The MongoDB storage adapter for the EPCIS exchange.
2
+ //
3
+ // `@bsv/dpp-credentials/epcis-exchange` never opens a database. It is handed
4
+ // six methods and builds import, pull, export and recovery on them. This file
5
+ // is those six methods over MongoDB, and nothing else: it holds no EPCIS
6
+ // logic of its own.
7
+ //
8
+ // The hard promise is the batch: `commit` applies every write or none, also
9
+ // across a crash. The reference deployment runs one MongoDB node, where a
10
+ // multi-document transaction is not available, so the batch is made atomic
11
+ // without one:
12
+ //
13
+ // <prefix>log one document: a sequence number, and the batch that is
14
+ // committed and not yet applied, if there is one
15
+ // <prefix>records one document per record, stamped with the sequence of
16
+ // the batch that last wrote it
17
+ // <prefix>bytes one document per retained source: its length and how
18
+ // many chunks hold it
19
+ // <prefix>chunks the exact bytes, in chunks
20
+ //
21
+ // A commit reads the log document at sequence N, checks every expectation,
22
+ // and then replaces the log document with "sequence N+1, committed, these
23
+ // writes" on the condition that it is still at N and idle. That one
24
+ // conditional update of one document is the commit: MongoDB applies it
25
+ // whole or not at all on a single node, and it is acknowledged from the
26
+ // journal. Before it the batch never happened. After it the batch is applied
27
+ // record by record and the log document is marked idle again.
28
+ //
29
+ // A store that stopped in between finds the committed batch when it is next
30
+ // opened, or when any other call looks, and applies it again. Applying twice
31
+ // is harmless: each write sets a whole value, and only on a record whose
32
+ // stamp is older than the batch. For that guard to hold after a delete, a
33
+ // deleted record leaves a small marker in place of its value, so an old
34
+ // batch applied late can never bring it back. Markers are not removed.
35
+ //
36
+ // A read is taken between two looks at the log document. If the sequence
37
+ // moved, or a batch was half applied, the read is taken again, so a reader
38
+ // in another process never sees part of a batch.
39
+ //
40
+ // It passes the module's shared adapter suite, which is the claim it makes.
41
+ import { Binary, MongoServerError, type Collection, type Db } from 'mongodb'
42
+ import {
43
+ EPCIS_STORAGE_KEY,
44
+ EPCIS_STORAGE_KIND,
45
+ EpcisStorageError,
46
+ assertStorageBytes,
47
+ assertStorageDigest,
48
+ assertStorageList,
49
+ assertStorageName,
50
+ checkedWrites,
51
+ type EpcisCommitResult,
52
+ type EpcisExchangeStorage,
53
+ type EpcisStoredRecord,
54
+ type EpcisWriteExpectation,
55
+ } from '@bsv/dpp-credentials/epcis-exchange'
56
+
57
+ export const MONGO_EPCIS_STORAGE_FORMAT = { format: 'dpp-epcis-exchange-mongodb', version: '1' } as const
58
+
59
+ /** One batch is one MongoDB document until it is applied, and a document holds at most 16 MiB. A larger batch is refused before anything is written. */
60
+ export const MONGO_EPCIS_MAX_BATCH_BYTES = 15 * 1024 * 1024
61
+ const DEFAULT_CHUNK_BYTES = 1024 * 1024
62
+
63
+ /** The database steps a write goes through, in the order they happen. A test stops the adapter before any one of them. */
64
+ export type MongoEpcisStorageStep = 'bytes-chunk' | 'bytes-head' | 'bytes-delete' | 'batch-commit' | 'record-put' | 'record-delete' | 'batch-clear'
65
+
66
+ export interface MongoEpcisStorageOptions {
67
+ /** The collections are named `<prefix>log`, `<prefix>records`, `<prefix>bytes` and `<prefix>chunks`. `epcis_` by default. */
68
+ collectionPrefix?: string
69
+ /**
70
+ * Wait for the journal before a commit or a put of bytes is answered. On
71
+ * by default. Off only for a test that simulates crashes itself: without it
72
+ * a power loss can undo a write the caller was told had happened.
73
+ */
74
+ journal?: boolean
75
+ /** How many bytes one chunk document holds. 1 MiB by default. */
76
+ chunkBytes?: number
77
+ /**
78
+ * Called before each database step. A test throws from it to stop the
79
+ * adapter exactly where a crash would. Once it throws, this adapter answers
80
+ * nothing more and the database is left as it was at that step. A test may
81
+ * also wait in it, to hold one writer still while another works.
82
+ */
83
+ interrupt?: (step: MongoEpcisStorageStep) => void | Promise<void>
84
+ }
85
+
86
+ export interface MongoEpcisStorage extends EpcisExchangeStorage {
87
+ /** What opening the store had to finish: 1 when a committed batch was found and applied. */
88
+ readonly reopened: { batchesApplied: number }
89
+ /** Stop answering. The database connection belongs to whoever opened it and stays open. */
90
+ close(): Promise<void>
91
+ /** Stop answering and leave the database exactly as it is, the way a process that died would. For tests of recovery. */
92
+ abandon(): void
93
+ }
94
+
95
+ type JournalledWrite = { op: 'put'; kind: string; key: string; revision: number; json: string } | { op: 'delete'; kind: string; key: string }
96
+
97
+ interface LogDocument {
98
+ _id: 'log'
99
+ format: string
100
+ version: string
101
+ /** One more for each committed batch. */
102
+ sequence: number
103
+ /** `committed`: `writes` is a batch that will be applied, now or when the store is next opened. */
104
+ state: 'idle' | 'committed'
105
+ writes: JournalledWrite[]
106
+ }
107
+
108
+ interface RecordDocument {
109
+ _id: string
110
+ kind: string
111
+ key: string
112
+ /** False for the marker a delete leaves. */
113
+ live: boolean
114
+ /** The sequence of the batch that last wrote this document. */
115
+ sequence: number
116
+ revision?: number
117
+ /** The value as JSON text, so it is read back exactly as it was written, whatever its member names and numbers are. */
118
+ json?: string
119
+ }
120
+
121
+ interface BytesDocument {
122
+ _id: string
123
+ byteLength: number
124
+ chunks: number
125
+ chunkBytes: number
126
+ }
127
+
128
+ interface ChunkDocument {
129
+ _id: string
130
+ data: Binary
131
+ }
132
+
133
+ const isDuplicateKey = (error: unknown): boolean => error instanceof MongoServerError && error.code === 11000
134
+ const recordId = (kind: string, key: string): string => `${kind}/${key}`
135
+ const utf8Length = (text: string): number => Buffer.byteLength(text, 'utf8')
136
+
137
+ export async function openMongoEpcisStorage(db: Db, options: MongoEpcisStorageOptions = {}): Promise<MongoEpcisStorage> {
138
+ const prefix = options.collectionPrefix ?? 'epcis_'
139
+ if (!/^[a-z][a-z0-9_]{0,31}$/.test(prefix)) throw new EpcisStorageError('invalid-value', 'a collection prefix is a lower-case name of at most 32 characters')
140
+ const chunkBytes = options.chunkBytes ?? DEFAULT_CHUNK_BYTES
141
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1 || chunkBytes > 8 * 1024 * 1024) throw new EpcisStorageError('invalid-value', 'a chunk holds 1 byte to 8 MiB')
142
+ // `majority` is the node itself on a single node. The journal is what makes an acknowledged write survive a stop.
143
+ const durable = options.journal === false ? { writeConcern: { w: 1 as const } } : { writeConcern: { w: 'majority' as const, j: true } }
144
+
145
+ const log: Collection<LogDocument> = db.collection<LogDocument>(`${prefix}log`)
146
+ const records: Collection<RecordDocument> = db.collection<RecordDocument>(`${prefix}records`)
147
+ const heads: Collection<BytesDocument> = db.collection<BytesDocument>(`${prefix}bytes`)
148
+ const chunks: Collection<ChunkDocument> = db.collection<ChunkDocument>(`${prefix}chunks`)
149
+
150
+ let closed = false
151
+ let stopped: unknown
152
+ const usable = (): void => {
153
+ if (stopped != null) throw stopped
154
+ if (closed) throw new EpcisStorageError('closed', 'the EPCIS store was closed')
155
+ }
156
+ const step = async (name: MongoEpcisStorageStep): Promise<void> => {
157
+ if (options.interrupt == null) return
158
+ try {
159
+ await options.interrupt(name)
160
+ } catch (error) {
161
+ stopped = error
162
+ throw error
163
+ }
164
+ }
165
+
166
+ /* ---- the log document ---- */
167
+
168
+ try {
169
+ await log.updateOne({ _id: 'log' }, { $setOnInsert: { ...MONGO_EPCIS_STORAGE_FORMAT, sequence: 0, state: 'idle', writes: [] } }, { upsert: true, ...durable })
170
+ } catch (error) {
171
+ // Two processes opening a new store at once: the other one made the document.
172
+ if (!isDuplicateKey(error)) throw error
173
+ }
174
+ const readLog = async (): Promise<LogDocument> => {
175
+ const held = await log.findOne({ _id: 'log' })
176
+ if (held == null) throw new EpcisStorageError('corrupt', `${prefix}log holds no log document`)
177
+ if (held.format !== MONGO_EPCIS_STORAGE_FORMAT.format || held.version !== MONGO_EPCIS_STORAGE_FORMAT.version) throw new EpcisStorageError('corrupt', `${prefix}log holds format ${JSON.stringify({ format: held.format, version: held.version })}, which this adapter does not read`)
178
+ if (!Number.isSafeInteger(held.sequence) || (held.state !== 'idle' && held.state !== 'committed') || !Array.isArray(held.writes)) throw new EpcisStorageError('corrupt', `${prefix}log does not hold a log document this adapter could have written`)
179
+ return held
180
+ }
181
+
182
+ /** Apply one committed batch. Each write lands only on a record that an earlier batch wrote last, so applying it again, or late, changes nothing. */
183
+ const apply = async (writes: readonly JournalledWrite[], sequence: number): Promise<void> => {
184
+ for (const write of writes) {
185
+ if (!EPCIS_STORAGE_KIND.test(write.kind) || !EPCIS_STORAGE_KEY.test(write.key)) throw new EpcisStorageError('corrupt', `${prefix}log names a record this adapter could not have written`)
186
+ const older = { _id: recordId(write.kind, write.key), sequence: { $lt: sequence } }
187
+ try {
188
+ if (write.op === 'put') {
189
+ await step('record-put')
190
+ await records.updateOne(older, { $set: { kind: write.kind, key: write.key, live: true, revision: write.revision, json: write.json, sequence } }, { upsert: true })
191
+ } else {
192
+ await step('record-delete')
193
+ // No upsert: a record that was never written has nothing an older batch could bring back.
194
+ await records.updateOne(older, { $set: { live: false, sequence }, $unset: { revision: '', json: '' } })
195
+ }
196
+ } catch (error) {
197
+ // The record already carries this batch or a later one, so the insert the upsert fell back to met it.
198
+ if (!isDuplicateKey(error)) throw error
199
+ }
200
+ }
201
+ }
202
+
203
+ /** The sequence the store is idle at, after finishing any batch that was committed and not yet applied. */
204
+ let batchesApplied = 0
205
+ const settle = async (): Promise<number> => {
206
+ for (;;) {
207
+ const held = await readLog()
208
+ if (held.state === 'idle') return held.sequence
209
+ await apply(held.writes, held.sequence)
210
+ await step('batch-clear')
211
+ await log.updateOne({ _id: 'log', sequence: held.sequence, state: 'committed' }, { $set: { state: 'idle', writes: [] } })
212
+ batchesApplied += 1
213
+ }
214
+ }
215
+
216
+ // Reopening: finish what a stopped store had committed.
217
+ let known: number | undefined = await settle()
218
+ const reopened = { batchesApplied }
219
+
220
+ /** Take a read between two looks at the log. An unchanged, idle log means no batch was committed or half applied while the read was made. */
221
+ const consistently = async <T>(read: () => Promise<T>): Promise<T> => {
222
+ for (;;) {
223
+ if (known == null) known = await settle()
224
+ const answer = await read()
225
+ const held = await log.findOne({ _id: 'log' }, { projection: { sequence: 1, state: 1 } })
226
+ if (held != null && held.state === 'idle' && held.sequence === known) return answer
227
+ known = undefined
228
+ }
229
+ }
230
+
231
+ const toStored = (held: RecordDocument): EpcisStoredRecord => ({ kind: held.kind, key: held.key, revision: held.revision as number, value: JSON.parse(held.json as string) as EpcisStoredRecord['value'] })
232
+
233
+ /* ---- one call at a time in this process ---- */
234
+
235
+ let tail: Promise<unknown> = Promise.resolve()
236
+ const inTurn = <T>(run: () => Promise<T>): Promise<T> => {
237
+ const next = tail.then(run, run)
238
+ tail = next.catch(() => undefined)
239
+ return next
240
+ }
241
+
242
+ // Identifiers are ASCII, so `\uffff` sorts after every identifier that starts with the same text: it closes a range over one prefix.
243
+ const chunkRange = (sha256: string, size?: number): { $gte: string; $lt: string } => {
244
+ const start = size == null ? `${sha256}.` : `${sha256}.${size}.`
245
+ return { $gte: start, $lt: `${start}\uffff` }
246
+ }
247
+
248
+ return {
249
+ reopened,
250
+
251
+ putBytes: (sha256, bytes) =>
252
+ inTurn(async () => {
253
+ usable()
254
+ assertStorageBytes(sha256, bytes)
255
+ if ((await heads.findOne({ _id: sha256 }, { projection: { _id: 1 } })) != null) return
256
+ const count = Math.ceil(bytes.byteLength / chunkBytes)
257
+ // A chunk is named by the digest, the chunk size and its position, so one left by an interrupted put holds exactly what this put would write.
258
+ for (let index = 0; index < count; index += 1) {
259
+ await step('bytes-chunk')
260
+ const data = new Binary(Buffer.from(bytes.subarray(index * chunkBytes, (index + 1) * chunkBytes)))
261
+ await chunks.replaceOne({ _id: `${sha256}.${chunkBytes}.${String(index).padStart(6, '0')}` }, { data }, { upsert: true })
262
+ }
263
+ // The head document is the moment the bytes are held. It is written last, from the journal, so it never names chunks that are not there.
264
+ await step('bytes-head')
265
+ try {
266
+ await heads.insertOne({ _id: sha256, byteLength: bytes.byteLength, chunks: count, chunkBytes }, durable)
267
+ } catch (error) {
268
+ if (!isDuplicateKey(error)) throw error
269
+ }
270
+ }),
271
+
272
+ getBytes: (sha256) =>
273
+ inTurn(async () => {
274
+ usable()
275
+ assertStorageDigest(sha256)
276
+ const head = await heads.findOne({ _id: sha256 })
277
+ if (head == null) return undefined
278
+ const parts = await chunks.find({ _id: chunkRange(sha256, head.chunkBytes) }).sort({ _id: 1 }).toArray()
279
+ const out = new Uint8Array(head.byteLength)
280
+ let offset = 0
281
+ for (const part of parts) {
282
+ const data = part.data.buffer.subarray(0, part.data.position)
283
+ if (offset + data.byteLength > out.byteLength) break
284
+ out.set(data, offset)
285
+ offset += data.byteLength
286
+ }
287
+ // All of them or an error: part of a source is never answered.
288
+ if (parts.length !== head.chunks || offset !== head.byteLength) throw new EpcisStorageError('corrupt', `the bytes held under ${sha256} are not whole`)
289
+ return out
290
+ }),
291
+
292
+ deleteBytes: (sha256) =>
293
+ inTurn(async () => {
294
+ usable()
295
+ assertStorageDigest(sha256)
296
+ await step('bytes-delete')
297
+ // The head goes first, so the bytes are gone as one step and what is left of them is never read.
298
+ await heads.deleteOne({ _id: sha256 }, durable)
299
+ await chunks.deleteMany({ _id: chunkRange(sha256) })
300
+ }),
301
+
302
+ get: (kind, key) =>
303
+ inTurn(async () => {
304
+ usable()
305
+ assertStorageName(kind, key)
306
+ const held = await consistently(() => records.findOne({ _id: recordId(kind, key) }))
307
+ return held == null || !held.live ? undefined : toStored(held)
308
+ }),
309
+
310
+ list: (kind, options) =>
311
+ inTurn(async () => {
312
+ usable()
313
+ assertStorageList(kind, options)
314
+ const prefixed = options.prefix ?? ''
315
+ // Record identifiers are `<kind>/<key>`, so the order of the identifiers of one kind is the order of its keys.
316
+ const from = options.after != null && options.after >= prefixed ? { $gt: recordId(kind, options.after) } : { $gte: recordId(kind, prefixed) }
317
+ const held = await consistently(() =>
318
+ records
319
+ .find({ _id: { ...from, $lt: `${recordId(kind, prefixed)}\uffff` }, live: true })
320
+ .sort({ _id: 1 })
321
+ .limit(options.limit)
322
+ .toArray()
323
+ )
324
+ return held.filter((record) => record.key.startsWith(prefixed)).map(toStored)
325
+ }),
326
+
327
+ commit: (writes) =>
328
+ inTurn(async (): Promise<EpcisCommitResult> => {
329
+ usable()
330
+ const batch = checkedWrites(writes)
331
+ if (batch.length === 0) return { committed: true }
332
+ const texts = batch.map((write) => (write.op === 'put' ? JSON.stringify(write.value) : ''))
333
+ const size = texts.reduce((sum, text, index) => sum + utf8Length(text) + utf8Length(batch[index]!.key) + 128, 0)
334
+ if (size > MONGO_EPCIS_MAX_BATCH_BYTES) throw new EpcisStorageError('invalid-value', `a batch of ${size} bytes is larger than the ${MONGO_EPCIS_MAX_BATCH_BYTES} bytes this adapter commits as one MongoDB document; nothing was written`)
335
+ for (;;) {
336
+ const sequence: number = known ?? (await settle())
337
+ known = sequence
338
+ const held = new Map((await records.find({ _id: { $in: batch.map((write) => recordId(write.kind, write.key)) } }).toArray()).map((record) => [record._id, record]))
339
+ const journal: JournalledWrite[] = []
340
+ let failed: Extract<EpcisCommitResult, { committed: false }>['failed'] | undefined
341
+ batch.forEach((write, index) => {
342
+ const now = held.get(recordId(write.kind, write.key))
343
+ const found: EpcisWriteExpectation = now?.live === true ? (now.revision as number) : 'absent'
344
+ if (failed == null && write.expect !== undefined && write.expect !== found) failed = { kind: write.kind, key: write.key, expected: write.expect, found }
345
+ journal.push(write.op === 'delete' ? { op: 'delete', kind: write.kind, key: write.key } : { op: 'put', kind: write.kind, key: write.key, revision: (found === 'absent' ? 0 : found) + 1, json: texts[index]! })
346
+ })
347
+ if (failed != null) {
348
+ // The answer is given only if nothing was committed while the expectations were read. Otherwise they are read again.
349
+ const after = await log.findOne({ _id: 'log' }, { projection: { sequence: 1, state: 1 } })
350
+ if (after != null && after.state === 'idle' && after.sequence === sequence) return { committed: false, failed }
351
+ known = undefined
352
+ continue
353
+ }
354
+ // This update is the commit. It takes effect only if no other batch was committed since the expectations were read.
355
+ await step('batch-commit')
356
+ const taken = await log.updateOne({ _id: 'log', sequence, state: 'idle' }, { $set: { sequence: sequence + 1, state: 'committed', writes: journal } }, durable)
357
+ if (taken.matchedCount === 0) {
358
+ known = undefined
359
+ continue
360
+ }
361
+ known = undefined
362
+ await apply(journal, sequence + 1)
363
+ await step('batch-clear')
364
+ const cleared = await log.updateOne({ _id: 'log', sequence: sequence + 1, state: 'committed' }, { $set: { state: 'idle', writes: [] } })
365
+ // When another process finished the batch first it may have committed further ones, so the sequence is looked up again.
366
+ if (cleared.matchedCount === 1) known = sequence + 1
367
+ return { committed: true }
368
+ }
369
+ }),
370
+
371
+ close: () =>
372
+ inTurn(async () => {
373
+ closed = true
374
+ }),
375
+
376
+ abandon: () => {
377
+ if (closed || stopped != null) return
378
+ stopped = new EpcisStorageError('closed', 'the EPCIS store was abandoned')
379
+ },
380
+ }
381
+ }