prepare-listing.ts (18032B)
1 import { 2 reviewNewListing, 3 listingReviewSnapshot, 4 reserveNewListing 5 } from '../../../src/lib/publishing/prepare-listing.ts'; 6 import { 7 createPublicPublicationRepository, 8 publicPublicationDraftRepository, 9 readPublicListingIntent 10 } from '../../../src/lib/persistence/public-publications.ts'; 11 import { captureNewListingReadiness } from '../../../src/lib/publishing/new-listing-readiness.ts'; 12 import { 13 createInboxSetupView, 14 checkInboxSetupView, 15 unlockInboxSetupView, 16 stopInboxSetupView, 17 closeInboxSetupView 18 } from '../../../src/lib/messaging/inbox-setup-view.ts'; 19 import { 20 openBrowserDatabase, 21 closeBrowserDatabase, 22 browserDatabaseTransaction 23 } from '../../../src/lib/persistence/database.ts'; 24 import { 25 createPublicDraftController, 26 editPublicDraft, 27 flushPublicDraft, 28 publicDraftControllerSnapshot, 29 closePublicDraftController 30 } from '../../../src/lib/publishing/draft-controller.ts'; 31 import { publicRecordSnapshot } from '../../../src/lib/persistence/records.ts'; 32 import { inspectLocalTemplate } from '../../../src/lib/nostr/local-template.ts'; 33 import { makeSetupFixture, fixturePolicy, inbox } from './inbox-setup.ts'; 34 export async function createFixture() { 35 const f = await makeSetupFixture([['relay', inbox]]); 36 // HC_TEST_ONLY_QUALIFICATION_PORT: genuine original owners with exercised 37 // controlled observations, never actual operator/relay qualification. 38 const setup = createInboxSetupView({ 39 identity: f.identity, 40 policy: fixturePolicy(), 41 lookup: () => Promise.resolve(f.resolve().resolver), 42 observeAccess: (context) => ({ 43 ...context, 44 readTargets: context.readTargets.slice(), 45 archiveTargets: context.archiveTargets.slice(), 46 receive: 'qualified_exercised', 47 archive: 'qualified_exercised', 48 current: () => true 49 }) 50 }); 51 if (!setup) throw Error('original setup missing'); 52 await checkInboxSetupView(setup); 53 await unlockInboxSetupView(setup); 54 const ready = captureNewListingReadiness( 55 f.identity, 56 setup, 57 'reviewed_new_listing_inbox' 58 ); 59 if (!ready) throw Error('original readiness missing'); 60 const originalReady = ready; 61 const opened = await openBrowserDatabase(); 62 if (opened.state !== 'ready') throw Error(opened.reason); 63 const database = opened.owner; 64 const repository = createPublicPublicationRepository(database, f.owner); 65 const drafts = repository && publicPublicationDraftRepository(repository); 66 if (!repository || !drafts) 67 throw Error('original publication repository missing'); 68 const originalRepository = repository; 69 const form = { 70 title: 'Carrots', 71 description: 'First complete description', 72 location: 'Local farm', 73 amount: '2', 74 currency: 'USD', 75 unit: 'kg', 76 quantity: '', 77 contactType: '' as const, 78 contactValue: '' 79 }; 80 const controller = await createPublicDraftController(drafts, form); 81 if (!controller) throw Error('original controller missing'); 82 const originalController = controller; 83 const command = '3d030bf5-901d-45e1-8251-41cbdf805e96'; 84 async function review() { 85 const result = await reviewNewListing( 86 originalRepository, 87 originalController, 88 originalReady, 89 command, 90 'reviewed_new_listing' 91 ); 92 if (result.status !== 'review') throw Error(result.reason); 93 return result.review; 94 } 95 function operations(): Promise<number> { 96 return new Promise((resolve, reject) => { 97 const tx = browserDatabaseTransaction( 98 database, 99 ['public_operations'], 100 'readonly' 101 ); 102 const count = tx 103 .objectStore('public_operations') 104 .index('by_owner') 105 .count(IDBKeyRange.only(f.owner)); 106 tx.addEventListener('complete', () => resolve(count.result)); 107 tx.addEventListener('abort', () => reject(Error('actual count aborted'))); 108 }); 109 } 110 return { 111 async unknown(mode: 'exact' | 'unavailable' | 'mismatch') { 112 const original = await review(), 113 preview = listingReviewSnapshot(original); 114 if (!preview) throw Error('original preview missing'); 115 const put = Object.getOwnPropertyDescriptor( 116 IDBObjectStore.prototype, 117 'put' 118 ), 119 abort = Object.getOwnPropertyDescriptor( 120 IDBTransaction.prototype, 121 'abort' 122 ), 123 get = Object.getOwnPropertyDescriptor(IDBObjectStore.prototype, 'get'); 124 if (!put || !abort || !get) throw Error('native descriptors missing'); 125 const nativePut = put.value as IDBObjectStore['put'], 126 nativeGet = get.value as IDBObjectStore['get']; 127 let nativePuts = 0; 128 const different = JSON.parse(preview.templateWire) as { 129 pubkey: string; 130 kind: number; 131 created_at: number; 132 tags: string[][]; 133 content: string; 134 }; 135 different.tags = different.tags.map((tag) => 136 tag[0] === 'd' ? ['d', 'f04a1fd7-e3c7-4e75-8949-4fdc8a6b2246'] : tag 137 ); 138 const wire = JSON.stringify(different), 139 template = inspectLocalTemplate(wire, f.owner, 30402); 140 if (!template) throw Error('actual changed template invalid'); 141 const changed = { 142 schema: 1, 143 family: 'public_operation', 144 owner: f.owner, 145 id: command, 146 revision: 0, 147 source: { 148 type: 'draft', 149 id: preview.draftId, 150 revision: preview.draftRevision 151 }, 152 capture: { 153 kind: 30402, 154 wire, 155 hash: template.hash, 156 targets: preview.targets, 157 policyFingerprint: preview.policyFingerprint 158 }, 159 artifact: null, 160 receipts: [] 161 }; 162 Object.defineProperty(IDBObjectStore.prototype, 'put', { 163 ...put, 164 value: function ( 165 this: IDBObjectStore, 166 ...args: Parameters<IDBObjectStore['put']> 167 ) { 168 const request = nativePut.apply(this, args); 169 if (this.name === 'public_operations') nativePuts++; 170 if (this.name === 'public_operations' && nativePuts === 1) { 171 if (mode === 'mismatch') 172 request.addEventListener('success', () => { 173 nativePut.call(this, { 174 owner: f.owner, 175 id: command, 176 wire: JSON.stringify(changed) 177 }); 178 nativePuts++; 179 }); 180 throw Error( 181 'HC_TEST_ONLY lost acknowledgement after actual native put' 182 ); 183 } 184 return request; 185 } 186 }); 187 Object.defineProperty(IDBTransaction.prototype, 'abort', { 188 ...abort, 189 value() { 190 throw Error('HC_TEST_ONLY unavailable abort channel'); 191 } 192 }); 193 if (mode === 'unavailable') 194 Object.defineProperty(IDBObjectStore.prototype, 'get', { 195 ...get, 196 value: function ( 197 this: IDBObjectStore, 198 ...args: Parameters<IDBObjectStore['get']> 199 ) { 200 if (this.name === 'public_operations') 201 throw new DOMException( 202 'HC_TEST_ONLY read setup unavailable', 203 'InvalidStateError' 204 ); 205 return nativeGet.apply(this, args); 206 } 207 }); 208 let result; 209 try { 210 result = await reserveNewListing(original, 'publish_reviewed_listing'); 211 } finally { 212 Object.defineProperty(IDBObjectStore.prototype, 'put', put); 213 Object.defineProperty(IDBTransaction.prototype, 'abort', abort); 214 Object.defineProperty(IDBObjectStore.prototype, 'get', get); 215 } 216 const observed = await readPublicListingIntent( 217 originalRepository, 218 command 219 ); 220 const row = 221 observed.status === 'found' 222 ? publicRecordSnapshot(observed.record, f.owner, command) 223 : undefined; 224 Object.defineProperty(IDBObjectStore.prototype, 'put', { 225 ...put, 226 value: function ( 227 this: IDBObjectStore, 228 ...args: Parameters<IDBObjectStore['put']> 229 ) { 230 if (this.name === 'public_operations') nativePuts++; 231 return nativePut.apply(this, args); 232 } 233 }); 234 let retry; 235 try { 236 retry = await reserveNewListing(original, 'publish_reviewed_listing'); 237 } finally { 238 Object.defineProperty(IDBObjectStore.prototype, 'put', put); 239 } 240 return { 241 status: result.status, 242 nativePuts, 243 originalCapture: 244 row?.family === 'public_operation' && 245 row.source.type === 'draft' && 246 row.source.id === preview.draftId && 247 row.source.revision === preview.draftRevision && 248 row.capture.wire === preview.templateWire && 249 row.capture.hash === preview.expectedHash && 250 JSON.stringify(row.capture.targets) === 251 JSON.stringify(preview.targets) && 252 row.capture.policyFingerprint === preview.policyFingerprint && 253 listingReviewSnapshot(original)?.identifier === preview.identifier, 254 operations: await operations(), 255 retry: retry.status, 256 signatures: f.counts().signs 257 }; 258 }, 259 async failedRead() { 260 const descriptor = Object.getOwnPropertyDescriptor( 261 IDBObjectStore.prototype, 262 'get' 263 ); 264 if (!descriptor) throw Error('native get descriptor missing'); 265 Object.defineProperty(IDBObjectStore.prototype, 'get', { 266 ...descriptor, 267 value() { 268 throw new DOMException( 269 'HC_TEST_ONLY native read setup failure', 270 'InvalidStateError' 271 ); 272 } 273 }); 274 let status: string; 275 try { 276 status = (await readPublicListingIntent(originalRepository, command)) 277 .status; 278 } catch { 279 status = 'rejected'; 280 } finally { 281 Object.defineProperty(IDBObjectStore.prototype, 'get', descriptor); 282 } 283 return { 284 status, 285 operations: await operations(), 286 signatures: f.counts().signs 287 }; 288 }, 289 async concurrentReviews() { 290 const [first, second] = await Promise.all([review(), review()]); 291 const firstPreview = listingReviewSnapshot(first), 292 secondPreview = listingReviewSnapshot(second); 293 const firstSave = await reserveNewListing( 294 first, 295 'publish_reviewed_listing' 296 ); 297 const secondSave = await reserveNewListing( 298 second, 299 'publish_reviewed_listing' 300 ); 301 return { 302 sameReview: first === second, 303 sameTemplate: 304 firstPreview?.templateWire === secondPreview?.templateWire, 305 first: firstSave.status, 306 second: secondSave.status, 307 operations: await operations(), 308 signatures: f.counts().signs 309 }; 310 }, 311 async doubleSubmit() { 312 const original = await review(), 313 preview = listingReviewSnapshot(original); 314 if (!preview) throw Error('preview missing'); 315 const first = reserveNewListing(original, 'publish_reviewed_listing'), 316 second = reserveNewListing(original, 'publish_reviewed_listing'); 317 const samePromise = first === second; 318 const results = await Promise.all([first, second]); 319 if (results[0].status !== 'saved' || results[1].status !== 'saved') 320 throw Error('original double submit did not save'); 321 const repeatedReview = await review(); 322 const repeatedPreview = listingReviewSnapshot(repeatedReview); 323 const repeated = await reserveNewListing( 324 repeatedReview, 325 'publish_reviewed_listing' 326 ); 327 editPublicDraft(controller, { 328 ...form, 329 description: 'Changed future description' 330 }); 331 await flushPublicDraft(controller); 332 const retry = await reserveNewListing( 333 original, 334 'publish_reviewed_listing' 335 ); 336 const stored = 337 retry.status === 'existing' 338 ? publicRecordSnapshot(retry.record, f.owner, command) 339 : undefined; 340 return { 341 same: samePromise && results[0].record === results[1].record, 342 repeatReview: repeated.status, 343 repeatCaptureUnchanged: 344 repeatedPreview?.identifier === preview.identifier && 345 repeatedPreview?.createdAtSeconds === preview.createdAtSeconds && 346 repeatedPreview?.expectedHash === preview.expectedHash, 347 operations: await operations(), 348 futureCaptureUnchanged: 349 stored?.family === 'public_operation' && 350 stored.capture.wire === preview.templateWire && 351 listingReviewSnapshot(original)?.templateWire === 352 preview.templateWire, 353 retry: retry.status, 354 signatures: f.counts().signs 355 }; 356 }, 357 async commandConflict() { 358 const original = await review(), 359 before = listingReviewSnapshot(original); 360 if (!before) throw Error('preview missing'); 361 const saved = await reserveNewListing( 362 original, 363 'publish_reviewed_listing' 364 ); 365 if (saved.status !== 'saved') throw Error('original save missing'); 366 editPublicDraft(controller, { ...form, title: 'Different carrots' }); 367 const other = await reviewNewListing( 368 originalRepository, 369 originalController, 370 originalReady, 371 command, 372 'reviewed_new_listing' 373 ); 374 const conflict = 375 other.status === 'blocked' 376 ? { status: other.reason } 377 : await reserveNewListing(other.review, 'publish_reviewed_listing'); 378 return { 379 conflict: conflict.status, 380 identifierRandom: 381 /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test( 382 before.identifier 383 ) && !before.identifier.includes(form.title), 384 identifierStable: 385 listingReviewSnapshot(original)?.identifier === before.identifier, 386 operations: await operations(), 387 signatures: f.counts().signs 388 }; 389 }, 390 async exactRevision() { 391 await flushPublicDraft(controller); 392 editPublicDraft(controller, { 393 ...form, 394 description: 'Second complete description' 395 }); 396 const original = await review(), 397 preview = listingReviewSnapshot(original), 398 savedDraft = publicDraftControllerSnapshot(controller)?.draft; 399 if (!preview || !savedDraft) throw Error('exact draft missing'); 400 const targets = preview.targets.slice(); 401 (preview.targets as string[]).push('wss://unapproved.foodtrace.net'); 402 const result = await reserveNewListing( 403 original, 404 'publish_reviewed_listing' 405 ); 406 if (result.status !== 'saved') throw Error('exact reservation failed'); 407 const row = publicRecordSnapshot(result.record, f.owner, command); 408 return { 409 exact: 410 row?.family === 'public_operation' && 411 row.source.type === 'draft' && 412 row.source.id === savedDraft.id && 413 row.source.revision === savedDraft.revision && 414 savedDraft.revision === 1 && 415 row.capture.hash === preview.expectedHash && 416 row.owner === f.owner && 417 row.capture.wire === preview.templateWire, 418 description: savedDraft.form.description, 419 targetsFrozen: 420 row?.family === 'public_operation' && 421 JSON.stringify(row.capture.targets) === JSON.stringify(targets), 422 signatures: f.counts().signs 423 }; 424 }, 425 async stale() { 426 const original = await review(), 427 saved = publicDraftControllerSnapshot(controller)?.draft; 428 if (!saved) throw Error('saved draft missing'); 429 const other = await createPublicDraftController(drafts, form, saved.id); 430 if (!other) throw Error('other original controller missing'); 431 editPublicDraft(other, { 432 ...form, 433 description: 'Actual other tab revision' 434 }); 435 await flushPublicDraft(other); 436 const changedDraft = await reserveNewListing( 437 original, 438 'publish_reviewed_listing' 439 ); 440 closePublicDraftController(other); 441 stopInboxSetupView(setup); 442 const retired = await reserveNewListing( 443 original, 444 'publish_reviewed_listing' 445 ); 446 return { 447 changedDraft: changedDraft.status, 448 retired: retired.status, 449 operations: await operations(), 450 signatures: f.counts().signs 451 }; 452 }, 453 async abort() { 454 const original = await review(), 455 preview = listingReviewSnapshot(original); 456 const descriptor = Object.getOwnPropertyDescriptor( 457 IDBObjectStore.prototype, 458 'put' 459 ); 460 if (!descriptor) throw Error('native put descriptor missing'); 461 const nativePut = descriptor.value as IDBObjectStore['put']; 462 let armed = true; 463 IDBObjectStore.prototype.put = function ( 464 ...args: Parameters<typeof nativePut> 465 ) { 466 const request = nativePut.apply(this, args); 467 if (armed && this.name === 'public_operations') { 468 armed = false; 469 request.addEventListener('success', () => this.transaction.abort()); 470 } 471 return request; 472 }; 473 let result; 474 try { 475 result = await reserveNewListing(original, 'publish_reviewed_listing'); 476 } finally { 477 Object.defineProperty(IDBObjectStore.prototype, 'put', descriptor); 478 } 479 const beforeRetry = await operations(); 480 const retry = await reserveNewListing( 481 original, 482 'publish_reviewed_listing' 483 ); 484 const row = 485 retry.status === 'saved' 486 ? publicRecordSnapshot(retry.record, f.owner, command) 487 : undefined; 488 return { 489 aborted: result.status, 490 beforeRetry, 491 retry: retry.status, 492 operations: await operations(), 493 originalCapture: 494 row?.family === 'public_operation' && 495 row.capture.wire === preview?.templateWire && 496 row.capture.hash === preview?.expectedHash, 497 signatures: f.counts().signs 498 }; 499 }, 500 close() { 501 closePublicDraftController(controller); 502 closeInboxSetupView(setup); 503 closeBrowserDatabase(database); 504 f.close(); 505 } 506 }; 507 }