@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.
Files changed (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -0,0 +1,1179 @@
1
+ // EPCIS exchange over the API: file import, a configured pull and exact
2
+ // export. Every answer here comes from `@bsv/dpp-credentials/epcis-exchange`
3
+ // through the routes under /api/epcis. The tests hold the routes to what the
4
+ // module promises: an upload is retained as the exact bytes that arrived, a
5
+ // retry is the same request, a refused transport keeps nothing, a pull
6
+ // continues where it stopped, and an export is the original, byte for byte.
7
+ import { copyFileSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { tmpdir } from 'node:os'
9
+ import { join } from 'node:path'
10
+ import { gzipSync } from 'node:zlib'
11
+ import { MongoMemoryServer } from 'mongodb-memory-server'
12
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
13
+ import { EPCIS_GS1_ARTEFACTS } from '@bsv/dpp-credentials'
14
+ import { EPCIS_RECORD_KINDS, EpcisStorageFault, checkEpcisExchangeInvariants, createMemoryEpcisStorage, faultInjectingEpcisStorage, openFileEpcisStorage, type EpcisExchangeStorage } from '@bsv/dpp-credentials/epcis-exchange'
15
+ import { EPCIS_DEFAULT_LIMITS } from '@bsv/dpp-credentials/epcis-source'
16
+ import { openMongoEpcisStorage } from '../src/epcis/mongo-storage.js'
17
+ import { mintPassportId } from '../src/identifiers.js'
18
+ import { MONGO_SERVER_SELECTION_TIMEOUT_MS } from '../src/platform.js'
19
+ import { CELL_A, CELL_B, ELECTROLYTE_LOT, MODULE, PACK, PALLET, SCRAP_CLASS, epcisDocument, eventId, fiveEventTypes, gs1Dir, item, minute, objectEvent, sha256, startApp, startEpcisSource, startMongo, testConfig, utf8, type Answer, type FixtureSource, type Json, type TestApp, type TestMongo } from './epcis-fixtures.js'
20
+
21
+ const SECRET = 'source-credential-51c9e0aa7b'
22
+ const apps: TestApp[] = []
23
+ const sources: FixtureSource[] = []
24
+ const folders: string[] = []
25
+ let mongo: TestMongo
26
+
27
+ beforeAll(async () => {
28
+ mongo = await startMongo()
29
+ })
30
+ afterEach(async () => {
31
+ await Promise.all(apps.splice(0).map((app) => app.close()))
32
+ await Promise.all(sources.splice(0).map((source) => source.close()))
33
+ })
34
+ afterAll(async () => {
35
+ await mongo.stop()
36
+ for (const dir of folders) rmSync(dir, { recursive: true, force: true })
37
+ })
38
+
39
+ const app = async (options: Parameters<typeof startApp>[0] = {}): Promise<TestApp> => {
40
+ const started = await startApp(options)
41
+ apps.push(started)
42
+ return started
43
+ }
44
+ const source = async (...args: Parameters<typeof startEpcisSource>): Promise<FixtureSource> => {
45
+ const started = await startEpcisSource(...args)
46
+ sources.push(started)
47
+ return started
48
+ }
49
+ /** The settings of one configured source that points at a fixture on this machine. */
50
+ const sourceSettings = (fixture: FixtureSource, over: Record<string, string> = {}): Record<string, string> => ({
51
+ EPCIS_SOURCES: 'supplier-a',
52
+ EPCIS_SOURCE_SUPPLIER_A_URL: fixture.baseUrl,
53
+ EPCIS_SOURCE_SUPPLIER_A_LOCAL_TEST: 'true',
54
+ EPCIS_SOURCE_SUPPLIER_A_BEARER_TOKEN: SECRET,
55
+ ...over,
56
+ })
57
+ const ref = (id: string): string => encodeURIComponent(id)
58
+ const importsOf = async (api: TestApp): Promise<Json[]> => (await api.get('/api/epcis/imports?limit=200')).body.imports as Json[]
59
+
60
+ // A passport identifier as this application mints one: a GS1 Digital Link under the demonstration prefix, with its check digit.
61
+ const PASSPORT = mintPassportId({ host: 'passports.example.com', prefix: '952' }, '100000001', 'EVENTS-1')
62
+ const valid = (): Json => epcisDocument([objectEvent(1, [item('HTTP-1'), PASSPORT]), objectEvent(2, [item('HTTP-1')], { 'example:note': 'seen on the line', 'example:reading': { value: 21.5, unit: 'CEL' } })])
63
+ /**
64
+ * A valid document written the way no serialiser here would write it: tabs,
65
+ * carriage returns, members out of their usual order, an escaped character,
66
+ * a number with an exponent and blank lines at the end. An export that had
67
+ * been parsed and written out again would differ from it.
68
+ */
69
+ const UNUSUAL = utf8(
70
+ [
71
+ '{\r\n\t"epcisBody" :\t{ "eventList":[',
72
+ `\t\t{ "disposition":"active","bizStep" : "inspecting", "action":"OBSERVE" ,"epcList":["${item('HTTP-9')}"],`,
73
+ `\t\t "recordTime":"2026-03-02T09:09:00.000Z","eventTimeZoneOffset":"+00:00","eventTime":"2026-03-02T08:09:00.000Z","eventID":"${eventId(9)}",`,
74
+ '\t\t "example:weight" : 1.250e1, "example:label":"caf\\u00e9", "type":"ObjectEvent" }',
75
+ '\t] },',
76
+ ' "creationDate":"2026-03-03T07:00:00.000Z", "schemaVersion":"2.0",',
77
+ ' "type":"EPCISDocument",',
78
+ ' "@context":[ "https://ref.gs1.org/standards/epcis/2.0.1/epcis-context.jsonld",{"example":"https://example.org/vocab/"} ]',
79
+ '}\n\n\n',
80
+ ].join('\r\n')
81
+ )
82
+
83
+ describe('sign-in', () => {
84
+ it('guards every exchange route, and keeps nothing of an upload that was not signed in', async () => {
85
+ const api = await app({ session: null })
86
+ const bytes = utf8(JSON.stringify(valid()))
87
+ expect((await api.upload('/api/epcis/imports?requestId=anonymous', bytes)).status).toBe(401)
88
+ for (const path of ['/api/epcis/status', '/api/epcis/sources', '/api/epcis/imports', '/api/epcis/imports/x', '/api/epcis/imports/x/original', '/api/epcis/sources/supplier-a/pulls/all', `/api/epcis/events?identifier=${ref(PASSPORT)}`, '/api/epcis/conflicts', '/api/epcis/conflicts/x']) {
89
+ const answer = await api.get(path)
90
+ expect(answer.status, path).toBe(401)
91
+ expect(answer.body, path).toMatchObject({ error: 'sign-in-required' })
92
+ }
93
+ expect((await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })).status).toBe(401)
94
+ expect((await api.post('/api/epcis/conflicts/x/resolutions', { decision: 'x', disposition: 'all-retained' })).status).toBe(401)
95
+ expect(await api.exchange.listImports({})).toEqual([])
96
+ expect(await api.exchange.storage.getBytes(sha256(bytes))).toBeUndefined()
97
+ })
98
+ })
99
+
100
+ describe('importing an uploaded document', () => {
101
+ it('retains the upload, answers its findings, lists it and reads it back', async () => {
102
+ const api = await app()
103
+ const bytes = utf8(JSON.stringify(valid(), null, 2))
104
+ const answer = await api.upload('/api/epcis/imports?requestId=upload-1&filename=line-events.jsonld', bytes)
105
+ expect(answer.status).toBe(201)
106
+ expect(answer.body).toMatchObject({ outcome: 'retained', replayed: false, resumed: false })
107
+ const record = answer.body.record
108
+ expect(record).toMatchObject({ sourceId: 'upload', requestId: 'upload-1', mediaType: 'application/ld+json', byteLength: bytes.byteLength, sha256: sha256(bytes), documentValidity: 'valid', state: 'evaluated', sourceLocation: { kind: 'file', filename: 'line-events.jsonld' }, policyId: 'starter-default@1' })
109
+ expect(record.events.map((event: Json) => event.arrival)).toEqual(['new', 'new'])
110
+ // A member the schema does not name is kept and named, never dropped.
111
+ expect(record.events[1].preservedExtensions).toEqual(['example:note', 'example:reading'])
112
+ // Nothing was mapped, signed or published: the record says so itself.
113
+ expect(record.events.every((event: Json) => (event.mapping as Json).outcome === 'not-attempted')).toBe(true)
114
+
115
+ expect(await importsOf(api)).toEqual([expect.objectContaining({ importId: record.importId, sourceId: 'upload', requestId: 'upload-1', sha256: sha256(bytes), documentValidity: 'valid', state: 'evaluated', events: 2, conflicts: 0, provenance: { kind: 'file', filename: 'line-events.jsonld' } })])
116
+ const read = await api.get(`/api/epcis/imports/${ref(record.importId)}`)
117
+ expect(read.status).toBe(200)
118
+ expect(read.body).toEqual(record)
119
+ expect((await api.get(`/api/epcis/imports/${ref('urn:bsv:dpp:epcis:import:sha256:' + '0'.repeat(64))}`)).status).toBe(404)
120
+ })
121
+
122
+ it('retains a document that parses and fails validation, with its findings, and says it is invalid', async () => {
123
+ const api = await app()
124
+ const { action: _dropped, ...withoutAction } = objectEvent(3, [item('HTTP-3')])
125
+ const answer = await api.upload('/api/epcis/imports?requestId=invalid-1', utf8(JSON.stringify(epcisDocument([withoutAction]))))
126
+ expect(answer.status).toBe(201)
127
+ expect(answer.body.record).toMatchObject({ documentValidity: 'invalid', state: 'evaluated' })
128
+ const findings = [...answer.body.record.findings, ...answer.body.record.events.flatMap((event: Json) => (event.validation as { findings: Json[] }).findings)]
129
+ expect(findings.some((finding: Json) => finding.severity === 'error')).toBe(true)
130
+ expect((await importsOf(api))[0]).toMatchObject({ documentValidity: 'invalid' })
131
+ expect((await importsOf(api))[0]!.findings).toBeGreaterThan(0)
132
+ })
133
+
134
+ it('retains a standalone event solely as an invalid receipt across upload, replay and original-byte export', async () => {
135
+ const api = await app()
136
+ const bytes = utf8(JSON.stringify(objectEvent(1, [CELL_A]), null, 2))
137
+ const request = '/api/epcis/imports?requestId=standalone-file'
138
+ const first = await api.upload(request, bytes)
139
+ expect(first.status).toBe(201)
140
+ const record = first.body.record
141
+ expect(record).toMatchObject({ documentValidity: 'invalid', events: [], sha256: sha256(bytes) })
142
+ expect(record.envelope).toBeUndefined()
143
+ expect(record.findings).toContainEqual(expect.objectContaining({ code: 'envelope-unrecognised' }))
144
+ const replay = await api.upload(request, bytes)
145
+ expect(replay.status).toBe(200)
146
+ expect(replay.body).toMatchObject({ replayed: true, record: { importId: record.importId, receivedAt: record.receivedAt, events: [] } })
147
+ expect(await importsOf(api)).toHaveLength(1)
148
+ const original = await api.get(`/api/epcis/imports/${ref(record.importId)}/original`)
149
+ expect(original.status).toBe(200)
150
+ expect(Buffer.from(original.bytes).equals(Buffer.from(bytes))).toBe(true)
151
+ })
152
+
153
+ it('answers a retry with the same request identifier as the same request, with one receipt', async () => {
154
+ const api = await app()
155
+ const bytes = utf8(JSON.stringify(valid()))
156
+ const first = await api.upload('/api/epcis/imports?requestId=retry-1', bytes)
157
+ const again = await api.upload('/api/epcis/imports?requestId=retry-1', bytes)
158
+ expect([first.status, again.status]).toEqual([201, 200])
159
+ expect(again.body).toMatchObject({ outcome: 'retained', replayed: true })
160
+ expect(again.body.record).toEqual(first.body.record)
161
+ expect(await importsOf(api)).toHaveLength(1)
162
+
163
+ // Three copies of one new request sent at once: one import, answered three times.
164
+ const together = await Promise.all([1, 2, 3].map(() => api.upload('/api/epcis/imports?requestId=retry-2', bytes)))
165
+ expect(together.map((answer) => answer.status).sort()).toEqual([200, 200, 201])
166
+ expect(new Set(together.map((answer) => answer.body.record.importId)).size).toBe(1)
167
+ expect(await importsOf(api)).toHaveLength(2)
168
+ // The second request holds the same bytes as the first, and every event of it repeats one that is held.
169
+ expect(together[0]!.body.record.events.map((event: Json) => event.arrival)).toEqual(['duplicate', 'duplicate'])
170
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
171
+ })
172
+
173
+ it('refuses the same request identifier with different bytes, and the first import stands', async () => {
174
+ const api = await app()
175
+ const bytes = utf8(JSON.stringify(valid()))
176
+ const other = utf8(JSON.stringify(valid(), null, 1))
177
+ const first = await api.upload('/api/epcis/imports?requestId=conflict-1', bytes)
178
+ const second = await api.upload('/api/epcis/imports?requestId=conflict-1', other)
179
+ expect(second.status).toBe(409)
180
+ expect(second.body).toMatchObject({ error: 'request-conflict', outcome: 'request-conflict', kept: false, existingImportId: first.body.record.importId })
181
+ // The same bytes under another media type are another request too.
182
+ expect((await api.upload('/api/epcis/imports?requestId=conflict-1', bytes, 'application/json')).status).toBe(409)
183
+ expect(await importsOf(api)).toHaveLength(1)
184
+ expect(await api.exchange.storage.getBytes(sha256(other))).toBeUndefined()
185
+ expect(sha256((await api.get(`/api/epcis/imports/${ref(first.body.record.importId)}/original`)).bytes)).toBe(sha256(bytes))
186
+ // The same identifier under another source scope is another request.
187
+ expect((await api.upload('/api/epcis/imports?requestId=conflict-1&sourceId=other-source', other)).status).toBe(201)
188
+ })
189
+
190
+ it('refuses a transport it cannot keep with a clear status, and keeps nothing', async () => {
191
+ const api = await app()
192
+ const good = JSON.stringify(valid())
193
+ const justOver = utf8(`${good}${' '.repeat(EPCIS_DEFAULT_LIMITS.maxDocumentBytes + 1 - good.length)}`)
194
+ const farOver = utf8(`${good}${' '.repeat(EPCIS_DEFAULT_LIMITS.maxDocumentBytes * 2)}`)
195
+ const cases: Array<[string, Uint8Array, string, Record<string, string>, number, string]> = [
196
+ ['a media type that is not EPCIS', utf8(good), 'text/plain', {}, 415, 'unsupported-media-type'],
197
+ ['no media type', utf8(good), '', {}, 415, 'unsupported-media-type'],
198
+ ['bytes that are not JSON', utf8('{"type":"EPCISDocument",'), 'application/ld+json', {}, 422, 'malformed-json'],
199
+ ['no bytes at all', new Uint8Array(0), 'application/ld+json', {}, 422, 'malformed-json'],
200
+ ['a member written twice', utf8('{"type":"EPCISDocument","type":"EPCISDocument"}'), 'application/json', {}, 422, 'duplicate-key'],
201
+ ['bytes that are not UTF-8', new Uint8Array([0x7b, 0x22, 0xff, 0xfe, 0x22, 0x7d]), 'application/json', {}, 422, 'malformed-utf8'],
202
+ ['a document one byte past the limit', justOver, 'application/ld+json', {}, 413, 'oversized'],
203
+ ['a document far past the limit', farOver, 'application/ld+json', {}, 413, 'oversized'],
204
+ ['a compressed body', new Uint8Array(gzipSync(good)), 'application/ld+json', { 'content-encoding': 'gzip' }, 415, 'content-encoding-unsupported'],
205
+ ]
206
+ for (const [what, bytes, mediaType, headers, status, code] of cases) {
207
+ const answer = await api.upload(`/api/epcis/imports?requestId=${ref(what)}`, bytes, mediaType, headers)
208
+ expect(answer.status, what).toBe(status)
209
+ expect(answer.body, what).toMatchObject({ error: code, outcome: 'refused', kept: false })
210
+ expect(typeof answer.body.description, what).toBe('string')
211
+ expect(await api.exchange.storage.getBytes(sha256(bytes)), what).toBeUndefined()
212
+ }
213
+ const unnamed = await api.upload('/api/epcis/imports', utf8(good))
214
+ expect(unnamed.status).toBe(400)
215
+ expect(unnamed.body.error).toBe('request-id-required')
216
+ // Nothing was kept of any of them: no receipt, no record of any kind.
217
+ expect(await importsOf(api)).toEqual([])
218
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
219
+ for (const kind of Object.values(EPCIS_RECORD_KINDS)) expect(await api.exchange.storage.list(kind, { limit: 10 }), kind).toEqual([])
220
+ })
221
+ })
222
+
223
+ describe('exporting an original', () => {
224
+ it('answers the uploaded bytes, byte for byte and by digest, under the media type they arrived with', async () => {
225
+ const api = await app()
226
+ const imported = await api.upload('/api/epcis/imports?requestId=unusual-1', UNUSUAL)
227
+ expect(imported.status).toBe(201)
228
+ expect(imported.body.record).toMatchObject({ documentValidity: 'valid', sha256: sha256(UNUSUAL), byteLength: UNUSUAL.byteLength })
229
+ const exported = await api.get(`/api/epcis/imports/${ref(imported.body.record.importId)}/original`)
230
+ expect(exported.status).toBe(200)
231
+ expect(sha256(exported.bytes)).toBe(sha256(UNUSUAL))
232
+ expect(Buffer.from(exported.bytes).equals(Buffer.from(UNUSUAL))).toBe(true)
233
+ // Parsing it and writing it out again would have given other bytes: the export is not that.
234
+ expect(sha256(JSON.stringify(JSON.parse(exported.text)))).not.toBe(sha256(UNUSUAL))
235
+ expect(exported.headers.get('content-type')).toBe('application/ld+json')
236
+ expect(exported.headers.get('content-length')).toBe(String(UNUSUAL.byteLength))
237
+ expect(exported.headers.get('x-content-sha256')).toBe(sha256(UNUSUAL))
238
+ expect(exported.headers.get('content-disposition')).toMatch(/^attachment; filename="epcis-[0-9a-f]{16}\.jsonld"$/)
239
+ expect(exported.headers.get('x-content-type-options')).toBe('nosniff')
240
+
241
+ // The same bytes sent as plain JSON are another import, exported as plain JSON.
242
+ const plain = await api.upload('/api/epcis/imports?requestId=unusual-2', UNUSUAL, 'application/json; charset=utf-8')
243
+ const plainExport = await api.get(`/api/epcis/imports/${ref(plain.body.record.importId)}/original`)
244
+ expect(plainExport.headers.get('content-type')).toBe('application/json')
245
+ expect(sha256(plainExport.bytes)).toBe(sha256(UNUSUAL))
246
+ expect((await api.get(`/api/epcis/imports/${ref('urn:bsv:dpp:epcis:import:sha256:' + 'f'.repeat(64))}/original`)).status).toBe(404)
247
+ })
248
+ })
249
+
250
+ describe('the events that name a product', () => {
251
+ it('lists each with its source and its validity, shows extension members, and says what an event is not', async () => {
252
+ const api = await app()
253
+ const first = await api.upload('/api/epcis/imports?requestId=events-1&sourceId=line-scanner', utf8(JSON.stringify(valid())))
254
+ // An invalid document names the same product. It is retained, and it is not indexed.
255
+ const { action: _dropped, ...withoutAction } = objectEvent(5, [PASSPORT])
256
+ await api.upload('/api/epcis/imports?requestId=events-2', utf8(JSON.stringify(epcisDocument([withoutAction]))))
257
+
258
+ const answer = await api.get(`/api/epcis/events?identifier=${ref(PASSPORT)}`)
259
+ expect(answer.status).toBe(200)
260
+ expect(answer.body).toMatchObject({ identifier: PASSPORT, granularity: 'instance', nature: 'supplied-data' })
261
+ expect(answer.body.notice).toMatch(/data a source supplied/)
262
+ expect(answer.body.notice).toMatch(/not signed/)
263
+ expect(answer.body.events).toHaveLength(1)
264
+ expect(answer.body.events[0]).toMatchObject({
265
+ association: { identifier: PASSPORT, role: 'object', granularity: 'instance', eventType: 'ObjectEvent', sourceId: 'line-scanner', errorDeclared: false },
266
+ source: { importId: first.body.record.importId, sourceId: 'line-scanner', documentValidity: 'valid', state: 'evaluated', provenance: { kind: 'file' }, sha256: first.body.record.sha256 },
267
+ event: { arrival: 'new', identityKind: 'event-id', identity: eventId(1) },
268
+ })
269
+
270
+ // The other item of the same document is in two events, one of which carries members the schema does not name.
271
+ const other = (await api.get(`/api/epcis/events?identifier=${ref(item('HTTP-1'))}`)).body.events as Json[]
272
+ expect(other).toHaveLength(2)
273
+ const extended = other.find((entry) => ((entry.event as Json).preservedExtensions as string[]).length > 0)!
274
+ expect((extended.event as Json).preservedExtensions).toEqual(['example:note', 'example:reading'])
275
+ expect(extended.body).toMatchObject({ 'example:note': 'seen on the line', 'example:reading': { value: 21.5, unit: 'CEL' } })
276
+
277
+ // Exact identifiers only, one item is not a class, and a source scope narrows the answer.
278
+ expect((await api.get(`/api/epcis/events?identifier=${ref(PASSPORT.toLowerCase())}`)).body.events).toEqual([])
279
+ expect((await api.get(`/api/epcis/events?identifier=${ref(PASSPORT)}&granularity=class`)).body.events).toEqual([])
280
+ expect((await api.get(`/api/epcis/events?identifier=${ref(PASSPORT)}&sourceId=upload`)).body.events).toEqual([])
281
+ expect((await api.get('/api/epcis/events')).status).toBe(400)
282
+ expect((await api.get(`/api/epcis/events?identifier=${ref(PASSPORT)}&granularity=everything`)).status).toBe(400)
283
+ })
284
+ })
285
+
286
+ describe('conflicts', () => {
287
+ it('lists two bodies under one event identifier, and records a decision that removes neither', async () => {
288
+ const api = await app()
289
+ await api.upload('/api/epcis/imports?requestId=body-1', utf8(JSON.stringify(epcisDocument([objectEvent(7, [item('HTTP-7')])]))))
290
+ const second = await api.upload('/api/epcis/imports?requestId=body-2', utf8(JSON.stringify(epcisDocument([objectEvent(7, [item('HTTP-7')], { disposition: 'in_transit' })]))))
291
+ expect(second.body.record).toMatchObject({ state: 'blocked', events: [{ arrival: 'conflict', conflict: { state: 'open' } }] })
292
+ const conflictId = second.body.record.events[0].conflict.conflictId as string
293
+
294
+ const listed = await api.get('/api/epcis/conflicts')
295
+ expect(listed.body).toMatchObject({ importsRead: 2, truncated: false, conflicts: [{ conflictId, state: 'open', identity: eventId(7), sourceId: 'upload' }] })
296
+ expect(listed.body.conflicts[0].observations).toHaveLength(2)
297
+ expect((await importsOf(api)).map((entry) => entry.conflicts).sort()).toEqual([0, 1])
298
+
299
+ const path = `/api/epcis/conflicts/${ref(conflictId)}/resolutions`
300
+ expect((await api.post(path, { decision: 'Keep both.', disposition: 'whichever' })).status).toBe(400)
301
+ expect((await api.post(`/api/epcis/conflicts/${ref('urn:bsv:dpp:epcis:conflict:sha256:' + '0'.repeat(64))}/resolutions`, { decision: 'Keep both.', disposition: 'all-retained' })).status).toBe(404)
302
+ const decision = { decision: 'The later reading stands. Both are kept.', disposition: 'all-retained', decidedAt: '2026-03-10T00:00:00.000Z' }
303
+ const decided = await api.post(path, decision)
304
+ expect(decided.status).toBe(201)
305
+ expect(decided.body).toMatchObject({ outcome: 'recorded', replayed: false, resolution: { conflictId, disposition: 'all-retained', decidedBy: 'developer', decidedAt: decision.decidedAt, sequence: 1 } })
306
+ // The same decision sent again is the one recorded.
307
+ const again = await api.post(path, decision)
308
+ expect(again.status).toBe(200)
309
+ expect(again.body).toMatchObject({ replayed: true, resolution: decided.body.resolution })
310
+
311
+ const after = await api.get(`/api/epcis/conflicts/${ref(conflictId)}`)
312
+ expect(after.body).toMatchObject({ state: 'resolved', currentResolutionId: decided.body.resolution.resolutionId })
313
+ expect(after.body.observations).toHaveLength(2)
314
+ expect(after.body.resolutions).toHaveLength(1)
315
+ expect((await api.get(`/api/epcis/imports/${ref(second.body.record.importId)}`)).body).toMatchObject({ state: 'evaluated', events: [{ conflict: { state: 'resolved' } }] })
316
+ })
317
+ })
318
+
319
+ describe('pulling from a configured source', () => {
320
+ const seven = (): Json[] => Array.from({ length: 7 }, (_, index) => objectEvent(index + 1, [item(`PULL-${index + 1}`)]))
321
+
322
+ it('describes the source without its credential, and reads several pages from it', async () => {
323
+ const fixture = await source(seven(), { requireAuthorization: `Bearer ${SECRET}` })
324
+ const api = await app({ config: testConfig(sourceSettings(fixture)) })
325
+
326
+ const described = await api.get('/api/epcis/sources')
327
+ expect(described.body).toEqual([{ sourceId: 'supplier-a', baseUrl: fixture.baseUrl, permittedOrigins: [fixture.origin], localTest: true, repeatListParameters: false, credentialConfigured: true, credentialScheme: 'bearer' }])
328
+ expect(described.text).not.toContain(SECRET)
329
+ expect((await api.get('/api/epcis/status')).body).toMatchObject({ storage: 'memory', artefacts: { state: 'present' }, recovery: { actions: [], remaining: 0 }, policy: 'starter-default@1' })
330
+
331
+ const run = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 3 } })
332
+ expect(run.status).toBe(200)
333
+ // The outcome is the module's, in its own words.
334
+ expect(run.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', completion: 'exhausted', exhausted: true, sourceId: 'supplier-a', queryId: 'all', localTest: true, events: { total: 7, new: 7, duplicate: 0 } })
335
+ expect(run.body.pages.map((page: Json) => [page.page, (page.events as Json).total, page.last])).toEqual([[1, 3, false], [2, 3, false], [3, 1, true]])
336
+ expect(run.body.completenessLimits[0]).toMatch(/not the complete history/)
337
+ // The credential went to the source, and came back in nothing.
338
+ expect(fixture.requests).toHaveLength(3)
339
+ expect(fixture.requests.every((request) => request.headers.authorization === `Bearer ${SECRET}`)).toBe(true)
340
+ expect(fixture.requests.every((request) => request.headers['gs1-epcis-version'] === '2.0.1' && request.headers['gs1-cbv-version'] === '2.0.0')).toBe(true)
341
+ expect(run.text).not.toContain(SECRET)
342
+ expect(run.body.pull.source).toMatchObject({ credentialsConfigured: true, localTest: true })
343
+
344
+ const state = await api.get('/api/epcis/sources/supplier-a/pulls/all')
345
+ expect(state.body.pull).toEqual(run.body.pull)
346
+ expect(state.body.pages).toEqual(run.body.pages)
347
+ // Each page is an import like any other: listed, and exported as the bytes the source sent.
348
+ const listed = await importsOf(api)
349
+ expect(listed.map((entry) => (entry.provenance as Json).kind)).toEqual(['query', 'query', 'query'])
350
+ for (const page of run.body.pages as Json[]) expect(sha256((await api.get(`/api/epcis/imports/${ref(String(page.importId))}/original`)).bytes)).toBe(page.sha256)
351
+ expect((await api.get(`/api/epcis/events?identifier=${ref(item('PULL-5'))}`)).body.events[0]).toMatchObject({ source: { sourceId: 'supplier-a', documentValidity: 'valid', provenance: { kind: 'query', origin: fixture.origin, page: 2 } } })
352
+
353
+ // What a request may not do: name an unknown source, leave out the query name, or redefine a query under a name already bound.
354
+ expect((await api.post('/api/epcis/sources/nobody/pulls', { queryId: 'all', query: {} })).status).toBe(404)
355
+ expect((await api.post('/api/epcis/sources/supplier-a/pulls', { query: {} })).status).toBe(400)
356
+ const redefined = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 5 } })
357
+ expect(redefined.status).toBe(409)
358
+ expect(redefined.body).toMatchObject({ error: 'pull-conflict', outcome: 'refused', requested: false })
359
+ expect((await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'bad', query: { everything: true } })).status).toBe(400)
360
+ expect((await api.get('/api/epcis/sources/supplier-a/pulls/never-run')).status).toBe(404)
361
+ expect(fixture.requests).toHaveLength(3)
362
+ })
363
+
364
+ it('says a history is partial when the source stops answering, and continues from its checkpoint after a restart', async () => {
365
+ const db = mongo.database()
366
+ // The third page request is answered 503, once.
367
+ const fixture = await source(seven(), { requireAuthorization: `Bearer ${SECRET}`, failRequest: (n) => (n === 3 ? 503 : undefined) })
368
+ const config = testConfig(sourceSettings(fixture))
369
+ const first = await app({ config, db })
370
+ expect(first.exchange.storageKind).toBe('mongodb')
371
+ const stopped = await first.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
372
+ expect(stopped.status).toBe(200)
373
+ expect(stopped.body).toMatchObject({ outcome: 'source-unavailable', reason: 'http-error', status: 503, completion: 'failed', exhausted: false, events: { total: 4, new: 4 } })
374
+ expect(stopped.body.pages).toHaveLength(2)
375
+ expect(stopped.body.completenessLimits.join(' ')).toMatch(/ended as http-error before the source's pages were exhausted/)
376
+ await first.close()
377
+ apps.splice(apps.indexOf(first), 1)
378
+
379
+ // A new process over the same database.
380
+ const lines: string[] = []
381
+ const second = await app({ config, db, lines })
382
+ expect(lines).toContain('EPCIS recovery: nothing was left unfinished.')
383
+ expect((await second.get('/api/epcis/sources/supplier-a/pulls/all')).body.pull).toMatchObject({ status: 'failed', pagesAcknowledged: 2 })
384
+ const resumed = await second.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
385
+ expect(resumed.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', exhausted: true, run: { run: 2, resumed: true }, events: { total: 3, new: 3, duplicate: 0 } })
386
+ expect(resumed.body.pages.map((page: Json) => page.page)).toEqual([3, 4])
387
+ // No page was asked for twice except the one that failed, and none was skipped.
388
+ expect(fixture.requests.map((request) => request.query.nextPageToken == null ? 0 : Number(Buffer.from(request.query.nextPageToken, 'base64url').toString()))).toEqual([0, 2, 4, 4, 6])
389
+ const state = (await second.get('/api/epcis/sources/supplier-a/pulls/all')).body
390
+ expect(state.pull).toMatchObject({ status: 'exhausted', pagesAcknowledged: 4, runs: 2, totals: { events: { total: 7, new: 7, duplicate: 0, conflict: 0 } } })
391
+ expect(state.pages.map((page: Json) => page.sequence)).toEqual([1, 2, 3, 4])
392
+ expect(await importsOf(second)).toHaveLength(4)
393
+ expect(await checkEpcisExchangeInvariants(second.exchange.storage, { associations: true })).toEqual([])
394
+ // The credential is in no record the database holds.
395
+ for (const name of ['epcis_log', 'epcis_records', 'epcis_bytes', 'epcis_chunks']) expect(JSON.stringify(await db.collection(name).find().toArray())).not.toContain(SECRET)
396
+ })
397
+
398
+ it('loses no page and repeats none when the process stops in the middle of a run', async () => {
399
+ const config = (fixture: FixtureSource) => testConfig(sourceSettings(fixture))
400
+ const body = { queryId: 'all', query: { perPage: 2 } }
401
+ // An uninterrupted run is the measure: what it leaves, and how many durable calls it made.
402
+ const controlSource = await source(seven(), { requireAuthorization: `Bearer ${SECRET}` })
403
+ const counting = faultInjectingEpcisStorage(await openMongoEpcisStorage(mongo.database(), { journal: false }))
404
+ const control = await app({ config: config(controlSource), storage: counting.storage })
405
+ expect((await control.post('/api/epcis/sources/supplier-a/pulls', body)).body).toMatchObject({ outcome: 'ok', events: { total: 7, new: 7 } })
406
+ const calls = counting.calls().length
407
+ expect(calls).toBeGreaterThan(30)
408
+ const eventsHeld = async (api: TestApp): Promise<string[]> => {
409
+ const out: string[] = []
410
+ for (let n = 1; n <= 7; n += 1) for (const entry of (await api.get(`/api/epcis/events?identifier=${ref(item(`PULL-${n}`))}`)).body.events as Json[]) out.push(`${n} ${(entry.source as Json).importId}`)
411
+ return out
412
+ }
413
+ const measure = await eventsHeld(control)
414
+ expect(measure).toHaveLength(7)
415
+
416
+ // Stopped after a durable call in the first, the middle and the last third of the run.
417
+ for (const at of [Math.floor(calls / 4), Math.floor(calls / 2), Math.floor((3 * calls) / 4)]) {
418
+ const db = mongo.database()
419
+ const fixture = await source(seven(), { requireAuthorization: `Bearer ${SECRET}` })
420
+ const faulty = faultInjectingEpcisStorage(await openMongoEpcisStorage(db, { journal: false }), { at, when: 'after' })
421
+ const dying = await app({ config: config(fixture), storage: faulty.storage })
422
+ const died = await dying.post('/api/epcis/sources/supplier-a/pulls', body)
423
+ // The run did not end: its process stopped. The answer names the store, says the run may be made again, and carries nothing of the store.
424
+ expect(died.status, `stopped after durable call ${at}`).toBe(503)
425
+ expect(died.body, `stopped after durable call ${at}`).toMatchObject({ error: 'storage-unavailable', outcome: 'failed', retryable: true })
426
+ // A run acknowledges page by page, so its answer does not say whether it was acknowledged.
427
+ expect(died.body, `stopped after durable call ${at}`).not.toHaveProperty('acknowledged')
428
+ expect(died.text).not.toContain(SECRET)
429
+
430
+ const lines: string[] = []
431
+ const restarted = await app({ config: config(fixture), db, lines })
432
+ expect(lines.some((line) => line.startsWith('EPCIS recovery:'))).toBe(true)
433
+ expect(await checkEpcisExchangeInvariants(restarted.exchange.storage, { associations: true }), `stopped after durable call ${at}`).toEqual([])
434
+ const finished = await restarted.post('/api/epcis/sources/supplier-a/pulls', body)
435
+ expect(finished.body, `stopped after durable call ${at}`).toMatchObject({ outcome: 'ok', reason: 'exhausted', run: { resumed: true } })
436
+ const state = (await restarted.get('/api/epcis/sources/supplier-a/pulls/all')).body
437
+ expect(state.pull, `stopped after durable call ${at}`).toMatchObject({ status: 'exhausted', pagesAcknowledged: 4, totals: { events: { total: 7, new: 7, duplicate: 0, conflict: 0 } } })
438
+ // Every event is held once, as after the uninterrupted run.
439
+ expect((await eventsHeld(restarted)).map((line) => line.split(' ')[0]), `stopped after durable call ${at}`).toEqual(measure.map((line) => line.split(' ')[0]))
440
+ expect(await importsOf(restarted)).toHaveLength(4)
441
+ expect(await checkEpcisExchangeInvariants(restarted.exchange.storage, { associations: true })).toEqual([])
442
+ expect(faulty.calls().length).toBe(at)
443
+ }
444
+ // The fault is the one the module's wrapper raises, so this is the stop the shared suite makes.
445
+ expect(new EpcisStorageFault(1, 'after', 'commit')).toBeInstanceOf(Error)
446
+ }, 120_000)
447
+
448
+ it('refuses a source whose address is outside its permitted origins, before anything is requested', async () => {
449
+ const fixture = await source(seven())
450
+ const api = await app({ config: testConfig(sourceSettings(fixture, { EPCIS_SOURCE_SUPPLIER_A_ORIGINS: 'https://events.example.org' })) })
451
+ const described = (await api.get('/api/epcis/sources')).body[0]
452
+ expect(described).toMatchObject({ permittedOrigins: ['https://events.example.org'], localTest: true })
453
+ expect(described.problem).toMatch(/permitted origins do not list/)
454
+ const refused = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })
455
+ expect(refused.status).toBe(400)
456
+ expect(refused.body).toMatchObject({ error: 'invalid-request', outcome: 'refused', requested: false })
457
+ expect(refused.body.description).toMatch(/permittedOrigins does not list/)
458
+ expect(fixture.requests).toEqual([])
459
+ expect((await api.get('/api/epcis/sources/supplier-a/pulls/all')).status).toBe(404)
460
+ expect(await importsOf(api)).toEqual([])
461
+ })
462
+
463
+ it('does not follow a next page to an origin that is not permitted, and says the history is partial', async () => {
464
+ const elsewhere = await source(seven())
465
+ const fixture = await source(seven(), { nextOrigin: elsewhere.origin })
466
+ const api = await app({ config: testConfig(sourceSettings(fixture, { EPCIS_SOURCE_SUPPLIER_A_BEARER_TOKEN: '' })) })
467
+ const run = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
468
+ expect(run.body).toMatchObject({ outcome: 'partial-history', reason: 'pagination-target-refused', completion: 'failed', exhausted: false, events: { total: 2 } })
469
+ // The first page is retained. The second was never asked for, anywhere.
470
+ expect(run.body.pages).toHaveLength(1)
471
+ expect(fixture.requests).toHaveLength(1)
472
+ expect(elsewhere.requests).toEqual([])
473
+ })
474
+
475
+ it('names a sign-in page as what it is, and a source that wants another credential', async () => {
476
+ const page = await source([], { answer: { status: 200, mediaType: 'text/html', body: '<!doctype html><title>Sign in</title>' } })
477
+ const api = await app({ config: testConfig(sourceSettings(page)) })
478
+ expect((await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })).body).toMatchObject({ outcome: 'unexpected-media-type', completion: 'failed', pages: [] })
479
+ const guarded = await source(seven(), { requireAuthorization: 'Bearer another-secret-entirely' })
480
+ const other = await app({ config: testConfig(sourceSettings(guarded)) })
481
+ const refused = await other.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })
482
+ expect(refused.body).toMatchObject({ outcome: 'source-authentication-required', reason: 'http-401', pages: [] })
483
+ expect(refused.text).not.toContain(SECRET)
484
+ })
485
+
486
+ it('refuses plain http and private addresses unless the local-test option is set for the source', async () => {
487
+ expect(() => testConfig({ EPCIS_SOURCES: 'supplier-a', EPCIS_SOURCE_SUPPLIER_A_URL: 'http://127.0.0.1:9/epcis' })).toThrow(/EPCIS_SOURCE_SUPPLIER_A_URL is a plain http address/)
488
+ // An https address on a private network passes configuration and is refused by the pull, which asks nothing of it.
489
+ const api = await app({ config: testConfig({ EPCIS_SOURCES: 'supplier-a', EPCIS_SOURCE_SUPPLIER_A_URL: 'https://10.0.0.5/epcis' }) })
490
+ expect((await api.get('/api/epcis/sources')).body[0]).toMatchObject({ localTest: false, credentialConfigured: false })
491
+ expect((await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })).body).toMatchObject({ outcome: 'source-unavailable', reason: 'target-refused', localTest: false, pages: [] })
492
+ })
493
+ })
494
+
495
+ describe('every event type, a class of items and corrections', () => {
496
+ /** A document written by hand around the events given, so an export that had been parsed and written out again would differ from it. */
497
+ const written = (events: Json[]): Uint8Array =>
498
+ utf8(`{\r\n\t"type":"EPCISDocument", "schemaVersion":"2.0",\n "@context": ${JSON.stringify(epcisDocument([])['@context'])},\n"creationDate":"2026-03-03T07:00:00.000Z" ,\n "epcisBody" : { "eventList": [\n${events.map((event) => `\t${JSON.stringify(event)}`).join(' ,\r\n')}\n ] }\n}\n\n`)
499
+ const entries = async (api: TestApp, identifier: string, query = ''): Promise<Json[]> => (await api.get(`/api/epcis/events?identifier=${ref(identifier)}${query}`)).body.events as Json[]
500
+ const roles = async (api: TestApp, identifier: string, query = ''): Promise<unknown[]> => (await entries(api, identifier, query)).map((entry) => [(entry.association as Json).eventType, (entry.association as Json).role])
501
+
502
+ it('imports one document that holds all five event types, exports it unchanged, and finds each item and each class under the role it has', async () => {
503
+ const api = await app()
504
+ const events = fiveEventTypes()
505
+ const bytes = written(events)
506
+ const imported = await api.upload('/api/epcis/imports?requestId=five-1&sourceId=assembly-line&filename=assembly.jsonld', bytes)
507
+ expect(imported.status).toBe(201)
508
+ const record = imported.body.record
509
+ expect(record).toMatchObject({ sourceId: 'assembly-line', documentValidity: 'valid', state: 'evaluated', sha256: sha256(bytes), byteLength: bytes.byteLength })
510
+ expect(record.events.map((event: Json) => [event.eventType, event.identity, event.arrival])).toEqual([
511
+ ['TransformationEvent', eventId(31), 'new'],
512
+ ['ObjectEvent', eventId(32), 'new'],
513
+ ['AssociationEvent', eventId(33), 'new'],
514
+ ['AggregationEvent', eventId(34), 'new'],
515
+ ['TransactionEvent', eventId(35), 'new'],
516
+ ])
517
+ expect([...record.findings, ...record.events.flatMap((event: Json) => (event.validation as { findings: Json[] }).findings)].filter((finding: Json) => finding.severity === 'error')).toEqual([])
518
+
519
+ // The bytes that arrived are the bytes that leave, whatever event types they hold.
520
+ const exported = await api.get(`/api/epcis/imports/${ref(record.importId)}/original`)
521
+ expect(Buffer.from(exported.bytes).equals(Buffer.from(bytes))).toBe(true)
522
+ expect(sha256(JSON.stringify(JSON.parse(exported.text)))).not.toBe(sha256(bytes))
523
+ expect(exported.headers.get('x-content-sha256')).toBe(sha256(bytes))
524
+
525
+ // Each individual item is found under every event that names it, with the role it has there.
526
+ expect(await roles(api, PACK)).toEqual([['ObjectEvent', 'object'], ['AssociationEvent', 'association-parent'], ['AggregationEvent', 'aggregation-child'], ['TransactionEvent', 'transaction-object']])
527
+ expect(await roles(api, MODULE)).toEqual([['TransformationEvent', 'transformation-output'], ['AssociationEvent', 'association-child']])
528
+ expect(await roles(api, CELL_A)).toEqual([['TransformationEvent', 'transformation-input']])
529
+ expect(await roles(api, PALLET)).toEqual([['AggregationEvent', 'aggregation-parent']])
530
+ // And each event is shown as the retained document holds it.
531
+ for (const entry of await entries(api, PACK)) expect(entry.body).toEqual(events.find((event) => event.eventID === (entry.event as Json).identity))
532
+
533
+ // A class-level lookup: a lot and a pattern, each named with a quantity, are found as classes.
534
+ const lot = await api.get(`/api/epcis/events?identifier=${ref(ELECTROLYTE_LOT)}&granularity=class`)
535
+ expect(lot.status).toBe(200)
536
+ expect(lot.body).toMatchObject({ identifier: ELECTROLYTE_LOT, granularity: 'class', nature: 'supplied-data' })
537
+ expect(lot.body.events).toHaveLength(1)
538
+ expect(lot.body.events[0]).toMatchObject({
539
+ association: { identifier: ELECTROLYTE_LOT, granularity: 'class', role: 'transformation-input-quantity', eventType: 'TransformationEvent', quantity: 4, uom: 'EA', sourceId: 'assembly-line', errorDeclared: false },
540
+ source: { importId: record.importId, documentValidity: 'valid' },
541
+ event: { identity: eventId(31), arrival: 'new' },
542
+ })
543
+ expect(lot.body.events[0].body).toEqual(events[0])
544
+ expect((await entries(api, SCRAP_CLASS, '&granularity=class')).map((entry) => entry.association)).toMatchObject([{ granularity: 'class', role: 'transformation-output-quantity', quantity: 0.5, uom: 'KGM' }])
545
+ // A class is never answered as an individual item taking part, and an item is never answered as a class.
546
+ expect(await entries(api, ELECTROLYTE_LOT)).toEqual([])
547
+ expect(await entries(api, ELECTROLYTE_LOT, '&granularity=instance')).toEqual([])
548
+ expect(await entries(api, SCRAP_CLASS, '&granularity=instance')).toEqual([])
549
+ for (const one of [PACK, MODULE, CELL_A, CELL_B, PALLET]) expect(await entries(api, one, '&granularity=class'), one).toEqual([])
550
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
551
+ })
552
+
553
+ it('keeps an error declaration and a changed observation beside the event they are about, replaces nothing, and resolves a correction only within its source', async () => {
554
+ const api = await app()
555
+ const [transformation, commissioning, , , transaction] = fiveEventTypes() as [Json, Json, Json, Json, Json]
556
+ const firstBytes = written(fiveEventTypes())
557
+ const first = await api.upload('/api/epcis/imports?requestId=corrections-1&sourceId=assembly-line', firstBytes)
558
+ expect(first.status).toBe(201)
559
+
560
+ // The source later declares the commissioning in error, and names the event that corrects it, which arrives in the same document.
561
+ const declaration = { declarationTime: minute(50), reason: 'incorrect_data', correctiveEventIDs: [eventId(40)] }
562
+ const declared = { ...commissioning, recordTime: minute(50), errorDeclaration: declaration }
563
+ const corrective = objectEvent(40, [PACK], { action: 'ADD', bizStep: 'commissioning', disposition: 'active' })
564
+ const second = await api.upload('/api/epcis/imports?requestId=corrections-2&sourceId=assembly-line', utf8(JSON.stringify(epcisDocument([declared, corrective]))))
565
+ expect(second.status).toBe(201)
566
+ expect(second.body.record).toMatchObject({ documentValidity: 'valid', state: 'evaluated' })
567
+ // A further observation of the same event: the second under its identity, beside the first.
568
+ expect(second.body.record.events[0]).toMatchObject({ identity: eventId(32), arrival: 'new-observation', observation: { sequence: 2 }, errorDeclaration: { correctiveEventIDs: [eventId(40)], resolution: 'resolved' } })
569
+ expect(second.body.record.events[0].conflict).toBeUndefined()
570
+ expect(second.body.record.events[1]).toMatchObject({ identity: eventId(40), arrival: 'new' })
571
+
572
+ // The repository records the transformation again at another time, with the same body. And it declares the shipment in error, naming an event it never sent.
573
+ const reobserved = { ...transformation, recordTime: minute(55) }
574
+ const orphan = { ...transaction, recordTime: minute(56), errorDeclaration: { declarationTime: minute(56), reason: 'did_not_occur', correctiveEventIDs: [eventId(99)] } }
575
+ const third = await api.upload('/api/epcis/imports?requestId=corrections-3&sourceId=assembly-line', utf8(JSON.stringify(epcisDocument([reobserved, orphan]))))
576
+ expect(third.status).toBe(201)
577
+ expect(third.body.record.events[0]).toMatchObject({ identity: eventId(31), arrival: 'new-observation', observation: { sequence: 2 } })
578
+ expect(third.body.record.events[0].errorDeclaration).toBeUndefined()
579
+ expect(third.body.record.events[1]).toMatchObject({ identity: eventId(35), arrival: 'new-observation', errorDeclaration: { correctiveEventIDs: [eventId(99)], resolution: 'unresolved', missing: [eventId(99)] } })
580
+ // Another source scope that names the same corrective event does not hold it: a correction is never resolved across sources.
581
+ const elsewhere = await api.upload('/api/epcis/imports?requestId=corrections-4&sourceId=another-line', utf8(JSON.stringify(epcisDocument([declared]))))
582
+ expect(elsewhere.body.record.events[0]).toMatchObject({ arrival: 'new', errorDeclaration: { resolution: 'unresolved', missing: [eventId(40)] } })
583
+
584
+ // Nothing was replaced. The first import is the record and the bytes it was, and no arrival here is a conflict.
585
+ expect((await api.get(`/api/epcis/imports/${ref(first.body.record.importId)}`)).body).toEqual(first.body.record)
586
+ expect(Buffer.from((await api.get(`/api/epcis/imports/${ref(first.body.record.importId)}/original`)).bytes).equals(Buffer.from(firstBytes))).toBe(true)
587
+ expect((await api.get('/api/epcis/conflicts')).body).toMatchObject({ conflicts: [], importsRead: 4, truncated: false })
588
+ expect((await importsOf(api)).map((entry) => [entry.state, entry.conflicts])).toEqual(Array.from({ length: 4 }, () => ['evaluated', 0]))
589
+
590
+ // The events of the product show both observations of its commissioning: the one first received, and the one that declares it in error.
591
+ // The index answers in the order of its keys, which is not the order of arrival, so the entries are read in the order they were observed.
592
+ const observedOrder = (list: Json[]): Json[] => [...list].sort((a, b) => Number(((a.event as Json).observation as Json).sequence) - Number(((b.event as Json).observation as Json).sequence))
593
+ const commissionings = observedOrder((await entries(api, PACK, '&sourceId=assembly-line')).filter((entry) => (entry.event as Json).identity === eventId(32)))
594
+ expect(commissionings.map((entry) => [(entry.source as Json).importId, (entry.association as Json).errorDeclared, (entry.event as Json).arrival])).toEqual([
595
+ [first.body.record.importId, false, 'new'],
596
+ [second.body.record.importId, true, 'new-observation'],
597
+ ])
598
+ expect((commissionings[0]!.body as Json).errorDeclaration).toBeUndefined()
599
+ expect((commissionings[1]!.body as Json).errorDeclaration).toEqual(declaration)
600
+ // The transformation observed twice is listed twice for an item it took in, with neither observation marked in error.
601
+ expect(observedOrder(await entries(api, CELL_A, '&sourceId=assembly-line')).map((entry) => [(entry.source as Json).importId, (entry.association as Json).errorDeclared, ((entry.body as Json).recordTime)])).toEqual([
602
+ [first.body.record.importId, false, transformation.recordTime],
603
+ [third.body.record.importId, false, minute(55)],
604
+ ])
605
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
606
+ })
607
+ })
608
+
609
+ describe('a store that fails', () => {
610
+ /** What the failing store says. It names a host, as a database driver's error does, so a test can show that a caller is never told it. */
611
+ const CAUSE = 'connection to db-internal-7.example.internal:27017 was reset'
612
+ /**
613
+ * A store whose durable call fails once, the given number of calls after
614
+ * it is armed, in a process that carries on with the same store. `before`:
615
+ * the call never reached the store. `after`: it was applied and its answer
616
+ * was lost.
617
+ */
618
+ function failingOnce(inner: EpcisExchangeStorage): { storage: EpcisExchangeStorage; calls(): number; arm(at: number, when: 'before' | 'after'): void } {
619
+ let made = 0
620
+ let plan: { at: number; when: 'before' | 'after' } | undefined
621
+ const durable = async <T>(run: () => Promise<T>): Promise<T> => {
622
+ made += 1
623
+ if (plan == null || made !== plan.at) return run()
624
+ if (plan.when === 'after') await run()
625
+ throw new Error(CAUSE)
626
+ }
627
+ return {
628
+ calls: () => made,
629
+ arm: (at, when) => {
630
+ plan = { at: made + at, when }
631
+ },
632
+ storage: {
633
+ putBytes: (digest, bytes) => durable(() => inner.putBytes(digest, bytes)),
634
+ deleteBytes: (digest) => durable(() => inner.deleteBytes(digest)),
635
+ commit: (writes) => durable(() => inner.commit(writes)),
636
+ getBytes: (digest) => inner.getBytes(digest),
637
+ get: (kind, key) => inner.get(kind, key),
638
+ list: (kind, options) => inner.list(kind, options),
639
+ },
640
+ }
641
+ }
642
+ const STORE_FAILURE = { error: 'storage-unavailable', outcome: 'failed', retryable: true, acknowledged: false }
643
+ /** A run acknowledges page by page, so the answer to one that failed does not say it was not acknowledged: it says the pages acknowledged before the failure are kept. */
644
+ const RUN_FAILURE = { error: 'storage-unavailable', outcome: 'failed', retryable: true }
645
+
646
+ it('answers a write that failed during an upload by name, as a request to send again, loses nothing acknowledged, and takes the same request in the same process', async () => {
647
+ const bytes = utf8(JSON.stringify(valid()))
648
+ const counting = failingOnce(createMemoryEpcisStorage())
649
+ const control = await app({ storage: counting.storage })
650
+ expect((await control.upload('/api/epcis/imports?requestId=flaky', bytes)).status).toBe(201)
651
+ const steps = counting.calls()
652
+ expect(steps).toBeGreaterThanOrEqual(6)
653
+
654
+ for (let at = 1; at <= steps; at += 1) {
655
+ for (const when of ['before', 'after'] as const) {
656
+ const where = `${when} durable call ${at} of ${steps}`
657
+ const failing = failingOnce(createMemoryEpcisStorage())
658
+ const lines: string[] = []
659
+ const api = await app({ storage: failing.storage, lines })
660
+ const earlier = await api.upload('/api/epcis/imports?requestId=earlier', UNUSUAL)
661
+ expect(earlier.status, where).toBe(201)
662
+
663
+ failing.arm(at, when)
664
+ const failed = await api.upload('/api/epcis/imports?requestId=flaky', bytes)
665
+ // Named, and said to be safe to send again. Not the unnamed failure of the API, and not a refusal of the document.
666
+ expect(failed.status, where).toBe(503)
667
+ expect(failed.body, where).toEqual({ ...STORE_FAILURE, description: expect.stringMatching(/did not complete a call\. This upload was not acknowledged\. Send it again with the same requestId/) })
668
+ // The store's own words are for the operator's log and are not in the answer.
669
+ expect(failed.text, where).not.toContain('db-internal-7')
670
+ expect(lines.filter((line) => line.startsWith('EPCIS store:') && line.includes(CAUSE)), where).toHaveLength(1)
671
+
672
+ // What was acknowledged before is held as it was, and the API answers its other requests.
673
+ expect(Buffer.from((await api.get(`/api/epcis/imports/${ref(earlier.body.record.importId)}/original`)).bytes).equals(Buffer.from(UNUSUAL)), where).toBe(true)
674
+ expect((await api.get(`/api/epcis/imports/${ref(earlier.body.record.importId)}`)).body, where).toEqual(earlier.body.record)
675
+ expect((await api.get('/api/epcis/status')).status, where).toBe(200)
676
+
677
+ // The same request again, in the same process, with no restart and no recovery between.
678
+ const again = await api.upload('/api/epcis/imports?requestId=flaky', bytes)
679
+ expect([200, 201], where).toContain(again.status)
680
+ expect(again.body, where).toMatchObject({ outcome: 'retained', record: { requestId: 'flaky', state: 'evaluated', documentValidity: 'valid', sha256: sha256(bytes) } })
681
+ expect((await importsOf(api)).map((entry) => entry.requestId).sort(), where).toEqual(['earlier', 'flaky'])
682
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true }), where).toEqual([])
683
+ // And once more it is a repeat, answered with the same import.
684
+ const repeat = await api.upload('/api/epcis/imports?requestId=flaky', bytes)
685
+ expect(repeat.status, where).toBe(200)
686
+ expect(repeat.body.record, where).toEqual(again.body.record)
687
+ await api.close()
688
+ apps.splice(apps.indexOf(api), 1)
689
+ }
690
+ }
691
+ })
692
+
693
+ it('answers writes another writer keeps winning by name, as a request to send again, and the same request is one import once they stop', async () => {
694
+ // The event results of an import always lose to another writer, as if one kept taking the same event identities, until the test stops it.
695
+ const inner = createMemoryEpcisStorage()
696
+ let contended = true
697
+ let lost = 0
698
+ const storage: EpcisExchangeStorage = {
699
+ putBytes: (digest, bytes) => inner.putBytes(digest, bytes),
700
+ getBytes: (digest) => inner.getBytes(digest),
701
+ deleteBytes: (digest) => inner.deleteBytes(digest),
702
+ get: (kind, key) => inner.get(kind, key),
703
+ list: (kind, options) => inner.list(kind, options),
704
+ commit: async (writes) => {
705
+ const observation = writes.find((write) => write.kind === EPCIS_RECORD_KINDS.observation)
706
+ if (!contended || observation == null) return inner.commit(writes)
707
+ lost += 1
708
+ return { committed: false, failed: { kind: observation.kind, key: observation.key, expected: 'absent', found: 1 } }
709
+ },
710
+ }
711
+ const api = await app({ storage })
712
+ const bytes = utf8(JSON.stringify(valid()))
713
+ const failed = await api.upload('/api/epcis/imports?requestId=contended', bytes)
714
+ expect(failed.status).toBe(503)
715
+ expect(failed.body).toEqual({ error: 'storage-contention', description: expect.stringMatching(/gave up after a bounded number of attempts\. This upload was not acknowledged\. Send it again with the same requestId/), outcome: 'failed', retryable: true, acknowledged: false })
716
+ // The bound the module states, and no more: the request did not hang on a writer that never stops.
717
+ expect(lost).toBe(8)
718
+
719
+ contended = false
720
+ const again = await api.upload('/api/epcis/imports?requestId=contended', bytes)
721
+ expect([200, 201]).toContain(again.status)
722
+ expect(again.body).toMatchObject({ outcome: 'retained', record: { requestId: 'contended', state: 'evaluated', documentValidity: 'valid', sha256: sha256(bytes) } })
723
+ expect((await importsOf(api)).map((entry) => entry.requestId)).toEqual(['contended'])
724
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
725
+ })
726
+
727
+ it('answers a write that failed during a pull by name, and the same query run again finishes with no page lost and no event held twice', async () => {
728
+ const seven = (): Json[] => Array.from({ length: 7 }, (_, index) => objectEvent(index + 1, [item(`PULL-${index + 1}`)]))
729
+ const body = { queryId: 'all', query: { perPage: 2 } }
730
+ const counting = failingOnce(createMemoryEpcisStorage())
731
+ const control = await app({ config: testConfig(sourceSettings(await source(seven()))), storage: counting.storage })
732
+ expect((await control.post('/api/epcis/sources/supplier-a/pulls', body)).body).toMatchObject({ outcome: 'ok', events: { total: 7, new: 7 } })
733
+ const steps = counting.calls()
734
+ expect(steps).toBeGreaterThan(20)
735
+
736
+ for (let at = 1; at <= steps; at += 1) {
737
+ for (const when of ['before', 'after'] as const) {
738
+ const where = `${when} durable call ${at} of ${steps}`
739
+ const fixture = await source(seven(), { requireAuthorization: `Bearer ${SECRET}` })
740
+ const failing = failingOnce(createMemoryEpcisStorage())
741
+ const api = await app({ config: testConfig(sourceSettings(fixture)), storage: failing.storage })
742
+ failing.arm(at, when)
743
+ const failed = await api.post('/api/epcis/sources/supplier-a/pulls', body)
744
+ expect(failed.status, where).toBe(503)
745
+ expect(failed.body, where).toEqual({ ...RUN_FAILURE, description: expect.stringMatching(/This run did not finish\. The pages it acknowledged before the failure are kept\. Run the same queryId again: it continues after the last page it acknowledged/) })
746
+ expect(failed.text, where).not.toContain('db-internal-7')
747
+ expect(failed.text, where).not.toContain(SECRET)
748
+ // Whatever the run had acknowledged is held, and its checkpoint is not past it.
749
+ const held = await api.get('/api/epcis/sources/supplier-a/pulls/all')
750
+ if (held.status === 200) {
751
+ expect(held.body.pages, where).toHaveLength(held.body.pull.pagesAcknowledged)
752
+ for (const page of held.body.pages as Json[]) expect(sha256((await api.get(`/api/epcis/imports/${ref(String(page.importId))}/original`)).bytes), where).toBe(page.sha256)
753
+ }
754
+
755
+ const again = await api.post('/api/epcis/sources/supplier-a/pulls', body)
756
+ expect(again.status, where).toBe(200)
757
+ expect(again.body, where).toMatchObject({ outcome: 'ok', reason: 'exhausted', exhausted: true })
758
+ const state = (await api.get('/api/epcis/sources/supplier-a/pulls/all')).body
759
+ expect(state.pull, where).toMatchObject({ status: 'exhausted' })
760
+ // The four pages of the history, each acknowledged once, and every event observed once.
761
+ expect((state.pages as Json[]).filter((page) => page.pass === 1).map((page) => page.page), where).toEqual([1, 2, 3, 4])
762
+ const observed = (await api.exchange.storage.list(EPCIS_RECORD_KINDS.observation, { limit: 100 })).map((record) => `${String(record.value.identity)} ${String(record.value.sequence)}`)
763
+ expect(observed.sort(), where).toEqual(Array.from({ length: 7 }, (_, index) => `${eventId(index + 1)} 1`).sort())
764
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true }), where).toEqual([])
765
+ await api.close()
766
+ apps.splice(apps.indexOf(api), 1)
767
+ await fixture.close()
768
+ sources.splice(sources.indexOf(fixture), 1)
769
+ }
770
+ }
771
+ }, 120_000)
772
+
773
+ it('answers by name, within a bounded wait, while the database is away, at the store and at a sign-in kept in the same database, and holds what it had acknowledged when it is back', async () => {
774
+ // A database of this test's own, which it stops and starts. Each API opens it as main.ts does: the platform connects with its own client, and the exchange is opened on the platform's database.
775
+ const mongod = await MongoMemoryServer.create()
776
+ const address = new URL(mongod.getUri()).host
777
+ const fixture = await source(Array.from({ length: 3 }, (_, index) => objectEvent(index + 1, [item(`OUTAGE-${index + 1}`)])))
778
+ const database = (name: string, over: Record<string, string> = {}) => testConfig({ MONGO_URL: mongod.getUri(), MONGO_DB: name, ...over })
779
+ // The sign-in lookup's failure is written to the process's error output, as Better Auth's own report of it is.
780
+ const errorOutput = vi.spyOn(console, 'error').mockImplementation(() => undefined)
781
+ try {
782
+ // The store's own failure: the development session stands in for sign-in, so that a request reaches the EPCIS store.
783
+ const lines: string[] = []
784
+ const api = await app({ mode: 'live', config: database('epcis_outage', sourceSettings(fixture)), lines })
785
+ expect(api.exchange.storageKind).toBe('mongodb')
786
+ // As main.ts runs with a database: sign-in on that same database, looked up before a route reaches the store.
787
+ const signed = await app({ mode: 'live', signIn: true, config: database('epcis_outage_sign_in') })
788
+ const signUp = await fetch(`${signed.base}/api/auth/sign-up/email`, { method: 'POST', headers: { 'content-type': 'application/json', origin: signed.platform.config.publicUrl }, body: JSON.stringify({ email: 'operator@example.com', password: 'outage-test-password-1', name: 'Operator' }) })
789
+ expect(signUp.status).toBe(200)
790
+ signed.headers.cookie = signUp.headers.getSetCookie().map((cookie) => cookie.split(';')[0]).join('; ')
791
+ const earlier = await api.upload('/api/epcis/imports?requestId=before-outage', UNUSUAL)
792
+ expect(earlier.status).toBe(201)
793
+ expect((await signed.upload('/api/epcis/imports?requestId=before-outage', UNUSUAL)).status).toBe(201)
794
+
795
+ await mongod.stop({ doCleanup: false })
796
+ const bytes = utf8(JSON.stringify(valid()))
797
+ const timed = async (ask: () => Promise<Answer>): Promise<Answer & { waited: number }> => {
798
+ const started = Date.now()
799
+ const answer = await ask()
800
+ return { ...answer, waited: Date.now() - started }
801
+ }
802
+ // Bounded by the time the application's own client waits for a server, with room for the driver's one retry. Never an open-ended wait.
803
+ const bound = MONGO_SERVER_SELECTION_TIMEOUT_MS * 4
804
+
805
+ const during = await timed(() => api.upload('/api/epcis/imports?requestId=during-outage', bytes))
806
+ expect(during.status).toBe(503)
807
+ expect(during.body).toMatchObject({ error: 'storage-unavailable', outcome: 'failed', retryable: true, acknowledged: false })
808
+ expect(during.waited).toBeLessThan(bound)
809
+ // A pull is answered the same way, and asks nothing of its source: the record it continues from could not be read.
810
+ const asked = fixture.requests.length
811
+ const pulled = await timed(() => api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} }))
812
+ expect(pulled.status).toBe(503)
813
+ expect(pulled.body).toEqual({ ...RUN_FAILURE, description: expect.stringMatching(/did not complete a call\. This run did not finish/) })
814
+ expect(pulled.waited).toBeLessThan(bound)
815
+ expect(fixture.requests).toHaveLength(asked)
816
+ // Reads are answered the same way: no route hangs and none answers an unnamed failure.
817
+ expect((await api.get('/api/epcis/imports')).body).toMatchObject({ error: 'storage-unavailable', retryable: true })
818
+ expect((await api.get(`/api/epcis/imports/${ref(earlier.body.record.importId)}/original`)).status).toBe(503)
819
+ // The two routes that read no store still answer, and so does the rest of the API.
820
+ expect((await api.get('/api/epcis/status')).status).toBe(200)
821
+ expect((await api.get('/api/epcis/sources')).status).toBe(200)
822
+ expect((await api.get('/api/health')).status).toBe(200)
823
+ // The operator's log names the failure. No answer carried the database's address.
824
+ for (const answer of [during, pulled]) expect(answer.text).not.toContain(address)
825
+ expect(lines.some((line) => line.startsWith('EPCIS store:') && line.includes('did not complete'))).toBe(true)
826
+
827
+ // With sign-in on the same database the lookup of the signed-in user fails first. It is named as well, within the same bound.
828
+ const signedDuring = await timed(() => signed.upload('/api/epcis/imports?requestId=during-outage', bytes))
829
+ expect(signedDuring.status).toBe(503)
830
+ expect(signedDuring.body).toEqual({ error: 'sign-in-unavailable', description: expect.stringMatching(/could not be looked up.*This upload was not acknowledged\. Send it again with the same requestId/), outcome: 'failed', retryable: true, acknowledged: false })
831
+ expect(signedDuring.waited).toBeLessThan(bound)
832
+ expect(signedDuring.text).not.toContain(address)
833
+ expect((await signed.get('/api/epcis/status')).body).toMatchObject({ error: 'sign-in-unavailable', retryable: true })
834
+ expect(errorOutput.mock.calls.some(([line]) => String(line).startsWith('EPCIS route: the signed-in user could not be looked up'))).toBe(true)
835
+ // A request with no session reads nothing from the database, and is still told to sign in.
836
+ expect((await fetch(`${signed.base}/api/epcis/imports`)).status).toBe(401)
837
+
838
+ // The database is back at the same address, with what it held.
839
+ await mongod.start(true)
840
+ const back = await api.get(`/api/epcis/imports/${ref(earlier.body.record.importId)}/original`)
841
+ expect(back.status).toBe(200)
842
+ expect(Buffer.from(back.bytes).equals(Buffer.from(UNUSUAL))).toBe(true)
843
+ expect((await api.get(`/api/epcis/imports/${ref(earlier.body.record.importId)}`)).body).toEqual(earlier.body.record)
844
+ // The requests that were not acknowledged are sent again: each upload is one import, and the pull runs to the end of its history.
845
+ for (const each of [api, signed]) {
846
+ const again = await each.upload('/api/epcis/imports?requestId=during-outage', bytes)
847
+ expect([200, 201]).toContain(again.status)
848
+ expect(again.body).toMatchObject({ outcome: 'retained', record: { state: 'evaluated', sha256: sha256(bytes) } })
849
+ expect((await importsOf(each)).map((entry) => entry.requestId).sort()).toEqual(['before-outage', 'during-outage'])
850
+ }
851
+ expect((await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })).body).toMatchObject({ outcome: 'ok', reason: 'exhausted', events: { total: 3, new: 3 } })
852
+ for (const each of [api, signed]) expect(await checkEpcisExchangeInvariants(each.exchange.storage, { associations: true })).toEqual([])
853
+ } finally {
854
+ errorOutput.mockRestore()
855
+ // Each API's client is closed while its database still answers.
856
+ await Promise.all(apps.splice(0).map((each) => each.close().catch(() => undefined)))
857
+ await mongod.stop().catch(() => undefined)
858
+ }
859
+ }, 120_000)
860
+
861
+ it('answers retained bytes that are altered or gone by name, as something sending the request again will not mend', async () => {
862
+ const store = createMemoryEpcisStorage()
863
+ const api = await app({ storage: store })
864
+ const imported = await api.upload('/api/epcis/imports?requestId=damaged-1', UNUSUAL)
865
+ const other = await api.upload('/api/epcis/imports?requestId=sound-1', utf8(JSON.stringify(valid())))
866
+ const original = `/api/epcis/imports/${ref(imported.body.record.importId)}/original`
867
+ store.state.bytes.get(sha256(UNUSUAL))![0] = 0x20
868
+ const altered = await api.get(original)
869
+ expect(altered.status).toBe(500)
870
+ expect(altered.body).toMatchObject({ error: 'retained-bytes-mismatch', outcome: 'failed', retryable: false })
871
+ // Nothing of the altered bytes is answered.
872
+ expect(altered.headers.get('x-content-sha256')).toBeNull()
873
+ store.state.bytes.delete(sha256(UNUSUAL))
874
+ expect((await api.get(original)).body).toMatchObject({ error: 'retained-bytes-missing', outcome: 'failed', retryable: false })
875
+ // The record is still read, and another import is exported as it was.
876
+ expect((await api.get(`/api/epcis/imports/${ref(imported.body.record.importId)}`)).status).toBe(200)
877
+ expect((await api.get(`/api/epcis/imports/${ref(other.body.record.importId)}/original`)).status).toBe(200)
878
+ })
879
+
880
+ it('answers a record it cannot read, a damaged store and a store no longer open to it by name', async () => {
881
+ // A pull record written by another version of the module: its checkpoint may mean something this version does not know, so it is not guessed at.
882
+ const memory = createMemoryEpcisStorage()
883
+ const fixture = await source([objectEvent(1, [item('UNREAD-1')])])
884
+ const pulling = await app({ config: testConfig(sourceSettings(fixture)), storage: memory })
885
+ const body = { queryId: 'all', query: {} }
886
+ expect((await pulling.post('/api/epcis/sources/supplier-a/pulls', body)).body).toMatchObject({ outcome: 'ok', reason: 'exhausted' })
887
+ for (const held of memory.state.records.get(EPCIS_RECORD_KINDS.pull)!.values()) held.value.recordVersion = '99'
888
+ const asked = fixture.requests.length
889
+ const unread = await pulling.post('/api/epcis/sources/supplier-a/pulls', body)
890
+ expect(unread.status).toBe(500)
891
+ expect(unread.body).toMatchObject({ error: 'record-unreadable', outcome: 'failed', retryable: false })
892
+ // Such a record may be sound, written by another version, so the operator is told to run that version and not only to restore.
893
+ expect(unread.body.description).toMatch(/does not read: it was written by another version, or it is damaged.*run the version that wrote it/)
894
+ expect(fixture.requests).toHaveLength(asked)
895
+
896
+ // The file-system adapter, with the record of an import overwritten on disk by something that is not a record.
897
+ const dir = mkdtempSync(join(tmpdir(), 'dpp-starter-epcis-store-'))
898
+ try {
899
+ const store = await openFileEpcisStorage(dir, { fsync: false })
900
+ const api = await app({ storage: store })
901
+ const imported = await api.upload('/api/epcis/imports?requestId=on-disk', UNUSUAL)
902
+ expect(imported.status).toBe(201)
903
+ const recordFile = readdirSync(join(dir, 'records', EPCIS_RECORD_KINDS.import), { recursive: true, withFileTypes: true })
904
+ .filter((entry) => entry.isFile())
905
+ .map((entry) => join(entry.parentPath, entry.name))
906
+ .filter((path) => (JSON.parse(readFileSync(path, 'utf8')) as { value?: Json }).value?.importId === imported.body.record.importId)
907
+ expect(recordFile).toHaveLength(1)
908
+ writeFileSync(recordFile[0]!, 'not a record')
909
+ const damaged = await api.get(`/api/epcis/imports/${ref(imported.body.record.importId)}`)
910
+ expect(damaged.status).toBe(500)
911
+ expect(damaged.body).toMatchObject({ error: 'storage-corrupt', outcome: 'failed', retryable: false })
912
+ // The adapter's own words name the folder. They are for the log, not the answer.
913
+ expect(damaged.text).not.toContain(dir)
914
+
915
+ // Once the store is closed under the running API, every route answers that it may be asked again, and none hangs.
916
+ await store.close()
917
+ for (const answer of [await api.get('/api/epcis/imports'), await api.upload('/api/epcis/imports?requestId=after-close', utf8(JSON.stringify(valid())))]) {
918
+ expect(answer.status).toBe(503)
919
+ expect(answer.body).toMatchObject({ error: 'storage-unavailable', outcome: 'failed', retryable: true, acknowledged: false })
920
+ expect(answer.body.description).toMatch(/is not open to this process/)
921
+ }
922
+ } finally {
923
+ rmSync(dir, { recursive: true, force: true })
924
+ }
925
+ })
926
+ })
927
+
928
+ describe('the edges of a paged history', () => {
929
+ const offsets = (fixture: FixtureSource): number[] => fixture.requests.map((request) => (request.query.nextPageToken == null ? 0 : Number(Buffer.from(request.query.nextPageToken, 'base64url').toString())))
930
+ /** A partial history is never said to be complete, in the answer or in the record. */
931
+ const partial = (body: Json): void => {
932
+ expect(body.exhausted).toBe(false)
933
+ expect(body.completion).not.toBe('exhausted')
934
+ expect(body.outcome).not.toBe('ok')
935
+ expect((body.pull as Json).status).not.toBe('exhausted')
936
+ expect(((body.pull as Json).pass as Json).exhausted).toBe(false)
937
+ expect((body.completenessLimits as string[])[0]).toMatch(/not the complete history/)
938
+ }
939
+
940
+ it('stops at the page limit, says the history is partial, and finishes it on the next run', async () => {
941
+ // Eleven events at one a page: one page more than a run reads under the default limits, which are the ones this application runs under.
942
+ expect(EPCIS_DEFAULT_LIMITS.maxPullPages).toBe(10)
943
+ const eleven = Array.from({ length: 11 }, (_, index) => objectEvent(index + 1, [item(`EDGE-${index + 1}`)]))
944
+ const fixture = await source(eleven)
945
+ const api = await app({ config: testConfig(sourceSettings(fixture)) })
946
+ const body = { queryId: 'all', query: { perPage: 1 } }
947
+
948
+ const first = await api.post('/api/epcis/sources/supplier-a/pulls', body)
949
+ expect(first.status).toBe(200)
950
+ expect(first.body).toMatchObject({ outcome: 'partial-history', reason: 'page-limit', completion: 'stopped-at-limit', exhausted: false, events: { total: 10, new: 10 }, limits: { maxPullPages: 10 }, limitOverrides: [], run: { pagesAcknowledged: 10 } })
951
+ partial(first.body)
952
+ expect(first.body.pages).toHaveLength(10)
953
+ expect(first.body.completenessLimits.join(' ')).toMatch(/stopped at its page limit/)
954
+ const stopped = (await api.get('/api/epcis/sources/supplier-a/pulls/all')).body
955
+ expect(stopped.pull).toMatchObject({ status: 'stopped-at-limit', pagesAcknowledged: 10, pass: { exhausted: false }, cursor: { afterPage: 10 } })
956
+ expect(stopped.pull.watermark).toBeUndefined()
957
+ // The eleventh event is not held, and nothing says it is.
958
+ expect((await api.get(`/api/epcis/events?identifier=${ref(item('EDGE-11'))}`)).body.events).toEqual([])
959
+ expect(await importsOf(api)).toHaveLength(10)
960
+
961
+ const second = await api.post('/api/epcis/sources/supplier-a/pulls', body)
962
+ expect(second.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', completion: 'exhausted', exhausted: true, run: { run: 2, resumed: true, pagesFetched: 1 }, events: { total: 1, new: 1, duplicate: 0 } })
963
+ // Every page was asked for once, in order: none again, none skipped.
964
+ expect(offsets(fixture)).toEqual(Array.from({ length: 11 }, (_, index) => index))
965
+ const finished = (await api.get('/api/epcis/sources/supplier-a/pulls/all')).body
966
+ expect(finished.pull).toMatchObject({ status: 'exhausted', pagesAcknowledged: 11, runs: 2, totals: { events: { total: 11, new: 11, duplicate: 0, conflict: 0 } } })
967
+ expect(finished.pages.map((page: Json) => [page.sequence, page.page])).toEqual(Array.from({ length: 11 }, (_, index) => [index + 1, index + 1]))
968
+ expect((await api.get(`/api/epcis/events?identifier=${ref(item('EDGE-11'))}`)).body.events).toHaveLength(1)
969
+ expect(await importsOf(api)).toHaveLength(11)
970
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
971
+ })
972
+
973
+ it('takes an empty result as the answer to the query, retains the empty page, and holds no event', async () => {
974
+ const empty = await source([])
975
+ const api = await app({ config: testConfig(sourceSettings(empty)) })
976
+ const run = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'nothing-yet', query: {} })
977
+ expect(run.status).toBe(200)
978
+ expect(run.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', completion: 'exhausted', exhausted: true, events: { total: 0, new: 0 } })
979
+ expect(run.body.pages).toHaveLength(1)
980
+ expect(run.body.pages[0]).toMatchObject({ page: 1, last: true, events: { total: 0 } })
981
+ // The pages were exhausted. That is still not a statement about what the source holds or will hold.
982
+ expect(run.body.completenessLimits[0]).toMatch(/not the complete history/)
983
+ // The empty answer is retained like any page: it is the evidence that the query was answered.
984
+ const listed = await importsOf(api)
985
+ expect(listed).toEqual([expect.objectContaining({ importId: run.body.pages[0].importId, sourceId: 'supplier-a', events: 0, documentValidity: 'valid', state: 'evaluated', provenance: expect.objectContaining({ kind: 'query', page: 1 }) })])
986
+ const original = await api.get(`/api/epcis/imports/${ref(run.body.pages[0].importId)}/original`)
987
+ expect(sha256(original.bytes)).toBe(run.body.pages[0].sha256)
988
+ expect(JSON.parse(original.text).epcisBody.queryResults.resultsBody.eventList).toEqual([])
989
+ const state = (await api.get('/api/epcis/sources/supplier-a/pulls/nothing-yet')).body
990
+ expect(state.pull).toMatchObject({ status: 'exhausted', pagesAcknowledged: 1, pass: { exhausted: true } })
991
+ expect(state.pull.watermark).toBeUndefined()
992
+
993
+ // A source that holds events, asked for a product none of them names, answers the same way.
994
+ const stocked = await source(Array.from({ length: 3 }, (_, index) => objectEvent(index + 1, [item(`HELD-${index + 1}`)])))
995
+ const other = await app({ config: testConfig(sourceSettings(stocked)) })
996
+ const none = await other.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'not-held', query: { matchAnyEPC: [item('NOT-HELD')] } })
997
+ expect(none.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', exhausted: true, events: { total: 0 } })
998
+ expect(stocked.requests.map((request) => request.query.MATCH_anyEPC)).toEqual([item('NOT-HELD')])
999
+ expect((await other.get(`/api/epcis/events?identifier=${ref(item('HELD-1'))}`)).body.events).toEqual([])
1000
+ })
1001
+
1002
+ it('asks again from the bounds of the query when its cursor has expired, never sends the expired cursor, and holds no event twice', async () => {
1003
+ let now = Date.parse('2026-03-10T00:00:00.000Z')
1004
+ const clock = (): string => new Date(now).toISOString()
1005
+ const seven = Array.from({ length: 7 }, (_, index) => objectEvent(index + 1, [item(`EXPIRY-${index + 1}`)]))
1006
+ // Every cursor the source names is good for one minute. Its third page request is answered 503, once.
1007
+ const fixture = await source(seven, { failRequest: (n) => (n === 3 ? 503 : undefined), tokenExpires: () => new Date(now + 60_000).toISOString() })
1008
+ const api = await app({ config: testConfig(sourceSettings(fixture)), now: clock })
1009
+ const body = { queryId: 'all', query: { perPage: 2 } }
1010
+
1011
+ const stopped = await api.post('/api/epcis/sources/supplier-a/pulls', body)
1012
+ expect(stopped.body).toMatchObject({ outcome: 'source-unavailable', reason: 'http-error', status: 503, completion: 'failed', events: { total: 4, new: 4 } })
1013
+ partial(stopped.body)
1014
+ expect(stopped.body.pull.cursor).toMatchObject({ afterPage: 2, expiresAt: new Date(now + 60_000).toISOString() })
1015
+
1016
+ // Two minutes later the cursor is past the time the source gave it.
1017
+ now += 120_000
1018
+ const resumed = await api.post('/api/epcis/sources/supplier-a/pulls', body)
1019
+ expect(resumed.status).toBe(200)
1020
+ expect(resumed.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', exhausted: true, replay: { reason: 'cursor-expired', pagesAcknowledgedBefore: 2 }, run: { run: 2, replays: 1 }, events: { total: 7, new: 3, duplicate: 4, conflict: 0 } })
1021
+ expect(resumed.body.completenessLimits.join(' ')).toMatch(/replayed from its bounds/)
1022
+ // The first run asked for offsets 0, 2 and 4. The second began again at 0: the expired cursor, which names offset 4, was not what it sent first.
1023
+ expect(offsets(fixture)).toEqual([0, 2, 4, 0, 2, 4, 6])
1024
+ // The same query and the same pass, traversed a second time. Every event is held once, and nothing is in conflict.
1025
+ const state = (await api.get('/api/epcis/sources/supplier-a/pulls/all')).body
1026
+ expect(state.pull).toMatchObject({ status: 'exhausted', pass: { number: 1, attempt: 2, exhausted: true } })
1027
+ const observed = (await api.exchange.storage.list(EPCIS_RECORD_KINDS.observation, { limit: 100 })).map((record) => `${String(record.value.identity)} ${String(record.value.sequence)}`)
1028
+ expect(observed.sort()).toEqual(seven.map((event) => `${String(event.eventID)} 1`).sort())
1029
+ expect((await api.get('/api/epcis/conflicts')).body.conflicts).toEqual([])
1030
+ expect(await checkEpcisExchangeInvariants(api.exchange.storage, { associations: true })).toEqual([])
1031
+ })
1032
+ })
1033
+
1034
+ describe('the pinned GS1 files at start-up', () => {
1035
+ const emptyFolder = (): string => {
1036
+ const dir = mkdtempSync(join(tmpdir(), 'dpp-starter-gs1-'))
1037
+ folders.push(dir)
1038
+ return dir
1039
+ }
1040
+ const bytes = utf8(JSON.stringify(valid()))
1041
+
1042
+ it('starts without them, says so in one line, and refuses every import and pull with how to provide them', async () => {
1043
+ const dir = emptyFolder()
1044
+ const fixture = await source([objectEvent(1, [item('GS1-1')])])
1045
+ const lines: string[] = []
1046
+ const api = await app({ config: testConfig({ ...sourceSettings(fixture), DPP_GS1_ARTEFACTS_DIR: dir }), lines })
1047
+ const line = lines.filter((entry) => entry.startsWith('GS1 files for EPCIS validation:'))
1048
+ expect(line).toHaveLength(1)
1049
+ expect(line[0]).toMatch(/unavailable in .*epcis-json-schema-2\.0\.1\.json \(offline\).*The API runs, and every EPCIS import and pull is refused until they are provided\./)
1050
+ expect(line[0]).toContain(`npx dpp-gs1-artefacts fetch --dir ${dir}`)
1051
+ // The API did start: its other routes answer.
1052
+ expect((await api.get('/api/health')).status).toBe(200)
1053
+ const status = (await api.get('/api/epcis/status')).body
1054
+ expect(status.artefacts).toMatchObject({ dir, state: 'unavailable' })
1055
+ expect(status.artefacts.remedy).toContain('https://ref.gs1.org')
1056
+
1057
+ const refused = await api.upload('/api/epcis/imports?requestId=no-schema', bytes)
1058
+ expect(refused.status).toBe(503)
1059
+ expect(refused.body).toMatchObject({ error: 'gs1-artefact-unavailable', outcome: 'refused', kept: false })
1060
+ expect(refused.body.remedy).toMatch(/dpp-gs1-artefacts fetch/)
1061
+ expect(await api.exchange.storage.getBytes(sha256(bytes))).toBeUndefined()
1062
+ const pull = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: {} })
1063
+ expect(pull.status).toBe(503)
1064
+ expect(pull.body).toMatchObject({ error: 'gs1-artefact-unavailable', outcome: 'refused', requested: false })
1065
+ expect(pull.body.remedy).toMatch(/dpp-gs1-artefacts fetch/)
1066
+ expect(fixture.requests).toEqual([])
1067
+ expect(await importsOf(api)).toEqual([])
1068
+
1069
+ // An operator places the files GS1 publishes in the folder. The next import is read against them, with no restart.
1070
+ for (const name of readdirSync(gs1Dir())) copyFileSync(join(gs1Dir(), name), join(dir, name))
1071
+ expect((await api.get('/api/epcis/status')).body.artefacts).toMatchObject({ state: 'present' })
1072
+ expect((await api.upload('/api/epcis/imports?requestId=no-schema', bytes)).status).toBe(201)
1073
+ })
1074
+
1075
+ it('fetches them into the configured folder when it may, checks them, and says so', async () => {
1076
+ const dir = emptyFolder()
1077
+ const asked: string[] = []
1078
+ // A transport that answers what GS1 publishes, from the folder the test set-up provisioned. Nothing leaves this machine.
1079
+ const fromCache: typeof globalThis.fetch = async (input) => {
1080
+ const url = String(input)
1081
+ asked.push(url)
1082
+ const artefact = EPCIS_GS1_ARTEFACTS.find((entry) => entry.uri === url)
1083
+ return artefact == null ? new Response('', { status: 404 }) : new Response(new Uint8Array(readFileSync(join(gs1Dir(), artefact.fileName))), { status: 200 })
1084
+ }
1085
+ const lines: string[] = []
1086
+ const api = await app({ config: testConfig({ DPP_GS1_ARTEFACTS_DIR: dir, DPP_GS1_ARTEFACTS_OFFLINE: 'false' }), fetch: fromCache, lines })
1087
+ expect(lines.filter((entry) => entry.startsWith('GS1 files for EPCIS validation:'))).toEqual([`GS1 files for EPCIS validation: fetched from GS1 into ${dir} and checked against their pinned digests.`])
1088
+ expect(asked.sort()).toEqual(EPCIS_GS1_ARTEFACTS.map((entry) => entry.uri).sort())
1089
+ expect(readdirSync(dir).sort()).toEqual(EPCIS_GS1_ARTEFACTS.map((entry) => entry.fileName).sort())
1090
+ expect((await api.upload('/api/epcis/imports?requestId=fetched', bytes)).status).toBe(201)
1091
+
1092
+ // The next start finds them and asks GS1 for nothing.
1093
+ const again: string[] = []
1094
+ await app({ config: testConfig({ DPP_GS1_ARTEFACTS_DIR: dir, DPP_GS1_ARTEFACTS_OFFLINE: 'false' }), fetch: fromCache, lines: again })
1095
+ expect(again.filter((entry) => entry.startsWith('GS1 files for EPCIS validation:'))).toEqual([`GS1 files for EPCIS validation: present in ${dir}.`])
1096
+ expect(asked).toHaveLength(EPCIS_GS1_ARTEFACTS.length)
1097
+ })
1098
+
1099
+ it('starts when GS1 cannot be reached or answers other bytes, and keeps no file it could not check', async () => {
1100
+ for (const [what, transport, reason] of [
1101
+ ['no network', (async () => { throw new Error('getaddrinfo ENOTFOUND ref.gs1.org') }) as typeof globalThis.fetch, 'network'],
1102
+ ['other bytes', (async () => new Response('{"not":"the schema"}', { status: 200 })) as typeof globalThis.fetch, 'length-mismatch'],
1103
+ ] as const) {
1104
+ const dir = emptyFolder()
1105
+ const lines: string[] = []
1106
+ const api = await app({ config: testConfig({ DPP_GS1_ARTEFACTS_DIR: dir, DPP_GS1_ARTEFACTS_OFFLINE: 'false' }), fetch: transport, lines })
1107
+ expect(lines.find((entry) => entry.startsWith('GS1 files for EPCIS validation:')), what).toContain(`(${reason})`)
1108
+ expect(readdirSync(dir), what).toEqual([])
1109
+ expect((await api.upload('/api/epcis/imports?requestId=unreachable', bytes)).status, what).toBe(503)
1110
+ }
1111
+ })
1112
+ })
1113
+
1114
+ describe('recovery at start-up', () => {
1115
+ it('finishes an import a stopped process left, before a request is accepted, and says what it did', async () => {
1116
+ const db = mongo.database()
1117
+ const bytes = utf8(JSON.stringify(valid()))
1118
+ // A process that stopped after it had written the receipt of an upload, which is its third durable call.
1119
+ const dying = await app({ storage: faultInjectingEpcisStorage(await openMongoEpcisStorage(db, { journal: false }), { at: 3, when: 'after' }).storage })
1120
+ const died = await dying.upload('/api/epcis/imports?requestId=interrupted', bytes)
1121
+ expect(died.status).toBe(503)
1122
+ expect(died.body).toMatchObject({ error: 'storage-unavailable', outcome: 'failed', retryable: true, acknowledged: false })
1123
+
1124
+ const lines: string[] = []
1125
+ const restarted = await app({ db, lines })
1126
+ expect(lines).toContain('EPCIS recovery: import-finished x1; 0 left unfinished.')
1127
+ expect((await restarted.get('/api/epcis/status')).body.recovery).toMatchObject({ actions: [{ action: 'import-finished', from: 'received', state: 'evaluated' }], remaining: 0 })
1128
+ const listed = await importsOf(restarted)
1129
+ expect(listed).toEqual([expect.objectContaining({ requestId: 'interrupted', state: 'evaluated', sha256: sha256(bytes) })])
1130
+ // The upload sent again is the import recovery finished, not a second one.
1131
+ const retried = await restarted.upload('/api/epcis/imports?requestId=interrupted', bytes)
1132
+ expect(retried.status).toBe(200)
1133
+ expect(retried.body).toMatchObject({ replayed: true, record: { importId: listed[0]!.importId } })
1134
+ expect(await importsOf(restarted)).toHaveLength(1)
1135
+ })
1136
+
1137
+ it('discards an upload that never reached its receipt, bytes included', async () => {
1138
+ const db = mongo.database()
1139
+ const bytes = utf8(JSON.stringify(valid()))
1140
+ const dying = await app({ storage: faultInjectingEpcisStorage(await openMongoEpcisStorage(db, { journal: false }), { at: 2, when: 'after' }).storage })
1141
+ expect((await dying.upload('/api/epcis/imports?requestId=never-held', bytes)).body).toMatchObject({ error: 'storage-unavailable', retryable: true })
1142
+ const lines: string[] = []
1143
+ const restarted = await app({ db, lines })
1144
+ expect(lines).toContain('EPCIS recovery: intake-discarded x1; 0 left unfinished.')
1145
+ expect(await importsOf(restarted)).toEqual([])
1146
+ expect(await restarted.exchange.storage.getBytes(sha256(bytes))).toBeUndefined()
1147
+ })
1148
+
1149
+ it('answers a document whose record is larger than the MongoDB store keeps as a refusal, and leaves no import of it', async () => {
1150
+ const db = mongo.database()
1151
+ const api = await app({ db })
1152
+ // Hundreds of thousands of very short identifiers: a document within the size limit whose import record is far larger than it.
1153
+ const many = Array.from({ length: 260_000 }, (_, index) => `a:${(index % 36).toString(36)}`)
1154
+ const bytes = utf8(JSON.stringify(epcisDocument([objectEvent(1, many)])))
1155
+ expect(bytes.byteLength).toBeLessThan(EPCIS_DEFAULT_LIMITS.maxDocumentBytes)
1156
+ const refused = await api.upload('/api/epcis/imports?requestId=too-large', bytes)
1157
+ expect(refused.status).toBe(413)
1158
+ expect(refused.body).toMatchObject({ error: 'record-too-large', outcome: 'refused', kept: false })
1159
+ expect(await importsOf(api)).toEqual([])
1160
+ expect((await api.get(`/api/epcis/events?identifier=${ref('a:0')}`)).body.events).toEqual([])
1161
+ // Other uploads go on as before, and the next start discards what the refused one had put down.
1162
+ expect((await api.upload('/api/epcis/imports?requestId=after-large', utf8(JSON.stringify(valid())))).status).toBe(201)
1163
+ await api.close()
1164
+ apps.splice(apps.indexOf(api), 1)
1165
+ const lines: string[] = []
1166
+ const restarted = await app({ db, lines })
1167
+ expect(lines).toContain('EPCIS recovery: intake-discarded x1; 0 left unfinished.')
1168
+ expect(await restarted.exchange.storage.getBytes(sha256(bytes))).toBeUndefined()
1169
+ expect(await importsOf(restarted)).toHaveLength(1)
1170
+ expect(await checkEpcisExchangeInvariants(restarted.exchange.storage, { associations: true })).toEqual([])
1171
+ })
1172
+
1173
+ it('says which store it runs on', async () => {
1174
+ const lines: string[] = []
1175
+ const memory = await app({ lines })
1176
+ expect(memory.exchange.storageKind).toBe('memory')
1177
+ expect(lines).toContain('EPCIS store: no MongoDB, so imports are held in memory and are gone when this process ends.')
1178
+ })
1179
+ })