@bsv/create-dpp-app 0.1.0-beta.1 → 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.
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +26 -6
- package/dist/index.js +36 -8
- package/package.json +9 -5
- package/template/Dockerfile +4 -2
- package/template/README.md +297 -42
- package/template/_env.example +82 -13
- package/template/_github/workflows/ci.yml +3 -3
- package/template/apps/api/API.md +86 -16
- package/template/apps/api/package.json +9 -4
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +175 -56
- package/template/apps/api/src/cli.ts +64 -7
- package/template/apps/api/src/config.ts +124 -10
- package/template/apps/api/src/custody.ts +241 -69
- package/template/apps/api/src/dev-index.ts +58 -9
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +1 -1
- package/template/apps/api/src/index-client.ts +131 -6
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +10 -2
- package/template/apps/api/src/parties.ts +2 -2
- package/template/apps/api/src/platform.ts +72 -17
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +38 -13
- package/template/apps/api/src/reader.ts +172 -3
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +253 -60
- package/template/apps/api/src/store.ts +198 -21
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +30 -17
- package/template/apps/api/src/worker.ts +20 -13
- package/template/apps/api/src/writer.ts +383 -131
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +148 -3
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +3 -2
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +17 -6
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/vitest.config.ts +3 -0
- package/template/apps/web/src/app.tsx +8 -4
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +17 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +2 -2
- package/template/apps/web/src/components/read-passport.tsx +4 -3
- package/template/apps/web/src/components/reading.tsx +32 -39
- package/template/apps/web/src/lib/api.ts +136 -26
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +27 -4
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/pages/accept.tsx +8 -3
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/new-passport.tsx +25 -2
- package/template/apps/web/src/pages/operations.tsx +22 -3
- package/template/apps/web/src/pages/passport.tsx +226 -162
- package/template/apps/web/src/pages/public-passport.tsx +50 -10
- package/template/apps/web/src/pages/wallet.tsx +1 -1
- package/template/apps/web/vite.config.ts +12 -4
- package/template/deploy/compose.yml +14 -2
- package/template/package.json +9 -3
|
@@ -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
|
+
}
|