app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

operation-transactions.spec.ts (19848B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { createHash, randomUUID } from 'node:crypto';
      5 import { finalizeEvent, getEventHash } from 'applesauce-core/helpers';
      6 import { createStaticHarness } from '../integration/harness/static.ts';
      7 import type * as Database from '../../src/lib/persistence/database.ts';
      8 import type * as Records from '../../src/lib/persistence/records.ts';
      9 import type * as Quota from '../../src/lib/persistence/quota.ts';
     10 import type * as Artifacts from '../../src/lib/persistence/artifact-records.ts';
     11 import type {
     12   PublicOperationRecord,
     13   PublicTargetReceipt
     14 } from '../../src/lib/contracts/local-records.ts';
     15 declare global {
     16   interface Window {
     17     hcp050: typeof Database & typeof Records & typeof Quota & typeof Artifacts;
     18     hcp050Database: Database.BrowserDatabase;
     19     hcp050Quota: Quota.PublicQuotaRepository;
     20     hcp050Transition: Artifacts.PublicOperationTransition;
     21   }
     22 }
     23 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
     24 test.beforeAll(async () => {
     25   server = await createStaticHarness();
     26   const source = (name: string) =>
     27     fileURLToPath(
     28       new URL('../../src/lib/persistence/' + name, import.meta.url)
     29     );
     30   const result = await build({
     31     configFile: false,
     32     logLevel: 'silent',
     33     plugins: [
     34       {
     35         name: 'hcp050-test-entry',
     36         resolveId(id) {
     37           if (id === 'virtual:hcp050') return '\0hcp050';
     38         },
     39         load(id) {
     40           if (id === '\0hcp050')
     41             return [
     42               'database.ts',
     43               'records.ts',
     44               'quota.ts',
     45               'artifact-records.ts'
     46             ]
     47               .map((n) => `export * from ${JSON.stringify(source(n))};`)
     48               .join('');
     49         }
     50       }
     51     ],
     52     build: {
     53       write: false,
     54       minify: false,
     55       rolldownOptions: { input: 'virtual:hcp050' },
     56       lib: { entry: 'virtual:hcp050', name: 'hcp050', formats: ['iife'] }
     57     }
     58   });
     59   const output = Array.isArray(result) ? result[0] : result;
     60   if (!('output' in output)) throw new Error('missing bundle');
     61   const chunks = output.output.filter((item) => item.type === 'chunk');
     62   expect(chunks).toHaveLength(1);
     63   bundle = chunks[0].code;
     64   console.log(
     65     JSON.stringify({
     66       fixture: 'HCP050_ACTUAL_MODULES_REAL_IDB',
     67       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
     68       exposure: 'test-only virtual entry'
     69     })
     70   );
     71 });
     72 test.afterAll(async () => server.close());
     73 function fixture(content = 'public operation transition fixture') {
     74   const key = crypto.getRandomValues(new Uint8Array(32));
     75   try {
     76     const event = finalizeEvent(
     77       {
     78         kind: 30402,
     79         created_at: 100,
     80         tags: [
     81           ['d', 'transition'],
     82           ['published_at', '100']
     83         ],
     84         content
     85       },
     86       key
     87     );
     88     const id = randomUUID();
     89     const template = {
     90       pubkey: event.pubkey,
     91       kind: 30402,
     92       created_at: 100,
     93       tags: event.tags,
     94       content
     95     };
     96     const row: PublicOperationRecord = {
     97       schema: 1,
     98       family: 'public_operation',
     99       owner: event.pubkey,
    100       id,
    101       revision: 0,
    102       source: { type: 'draft', id, revision: 0 },
    103       capture: {
    104         kind: 30402,
    105         wire: JSON.stringify(template),
    106         hash: getEventHash(template),
    107         targets: ['wss://one.example.org'],
    108         policyFingerprint: 'a'.repeat(64)
    109       },
    110       artifact: null,
    111       receipts: []
    112     };
    113     return { row, wire: JSON.stringify(event) };
    114   } finally {
    115     key.fill(0);
    116   }
    117 }
    118 async function load(page: Page, owner: string) {
    119   await page.goto(server.url + '/search');
    120   await page.addScriptTag({ content: bundle });
    121   await page.evaluate(async (owner) => {
    122     const api = window.hcp050;
    123     const opened = await api.openBrowserDatabase();
    124     if (opened.state !== 'ready') throw new Error(opened.reason);
    125     const repo = api.createPublicQuotaRepository(opened.owner, owner);
    126     if (!repo) throw new Error('missing quota');
    127     window.hcp050Database = opened.owner;
    128     window.hcp050Quota = repo;
    129   }, owner);
    130 }
    131 async function admit(page: Page, row: PublicOperationRecord) {
    132   return page.evaluate(async (row) => {
    133     const api = window.hcp050;
    134     const record = api.decodePublicRecord(
    135       JSON.stringify(row),
    136       row.owner,
    137       row.id
    138     );
    139     if (!record.ok) throw new Error(record.reason);
    140     return api.admitPublicOperation(window.hcp050Quota, row.id, record.value);
    141   }, row);
    142 }
    143 async function prepare(page: Page, f: ReturnType<typeof fixture>) {
    144   return page.evaluate((f) => {
    145     const api = window.hcp050;
    146     const record = api.decodePublicRecord(
    147       JSON.stringify(f.row),
    148       f.row.owner,
    149       f.row.id
    150     );
    151     if (!record.ok) throw new Error(record.reason);
    152     const artifact = api.bindCapturedArtifact(
    153       f.wire,
    154       f.row.owner,
    155       30402,
    156       f.row.capture.hash
    157     );
    158     if (!artifact.ok) throw new Error(artifact.reason);
    159     const transition = api.preparePublicArtifactTransition(
    160       record.value,
    161       f.row.owner,
    162       f.row.id,
    163       artifact.value
    164     );
    165     if (!transition.ok) throw new Error(transition.reason);
    166     window.hcp050Transition = transition.value;
    167     return api.publicTransitionSnapshot(
    168       transition.value,
    169       f.row.owner,
    170       f.row.id
    171     );
    172   }, f);
    173 }
    174 async function commit(page: Page) {
    175   return page.evaluate(() =>
    176     window.hcp050.commitPublicOperationTransition(
    177       window.hcp050Quota,
    178       window.hcp050Transition
    179     )
    180   );
    181 }
    182 async function observe(page: Page) {
    183   return page.evaluate(() =>
    184     window.hcp050.observePublicOperationTransition(
    185       window.hcp050Quota,
    186       window.hcp050Transition
    187     )
    188   );
    189 }
    190 function receipt(row: PublicOperationRecord): PublicTargetReceipt {
    191   return {
    192     actionId: randomUUID(),
    193     origin: row.capture.targets[0],
    194     role: 'publication',
    195     attempt: 1,
    196     eventId: row.capture.hash,
    197     status: 'accepted',
    198     observedAtMilliseconds: 1000,
    199     readbackWire: null
    200   };
    201 }
    202 async function prepareReceipt(
    203   page: Page,
    204   row: PublicOperationRecord,
    205   fact: PublicTargetReceipt
    206 ) {
    207   await page.evaluate(
    208     ({ row, fact }) => {
    209       const api = window.hcp050;
    210       const base = api.decodePublicRecord(
    211         JSON.stringify(row),
    212         row.owner,
    213         row.id
    214       );
    215       if (!base.ok) throw new Error(base.reason);
    216       const next = api.preparePublicReceiptTransition(
    217         base.value,
    218         row.owner,
    219         row.id,
    220         JSON.stringify(fact)
    221       );
    222       if (!next.ok) throw new Error(next.reason);
    223       window.hcp050Transition = next.value;
    224     },
    225     { row, fact }
    226   );
    227 }
    228 test('signed artifact commits exactly once and original full-wire observation distinguishes base and committed', async ({
    229   page
    230 }) => {
    231   const f = fixture();
    232   await load(page, f.row.owner);
    233   expect((await admit(page, f.row)).ok).toBe(true);
    234   const capture = await prepare(page, f);
    235   expect(await observe(page)).toEqual({ state: 'base_observed' });
    236   expect(await commit(page)).toEqual({
    237     ok: true,
    238     value: { id: f.row.id, revision: 1 }
    239   });
    240   expect(await commit(page)).toEqual({
    241     ok: true,
    242     value: { id: f.row.id, revision: 1 }
    243   });
    244   expect(await observe(page)).toEqual({
    245     state: 'committed',
    246     id: f.row.id,
    247     revision: 1
    248   });
    249   expect(capture?.baseWire).toBe(JSON.stringify(f.row));
    250 });
    251 test('two genuine tabs race distinct receipts at one revision; stale request conflicts and winning exact replay is idempotent', async ({
    252   page,
    253   context
    254 }) => {
    255   const f = fixture();
    256   await load(page, f.row.owner);
    257   await admit(page, f.row);
    258   const capture = await prepare(page, f);
    259   await commit(page);
    260   const row = JSON.parse(capture?.nextWire ?? 'null') as PublicOperationRecord;
    261   const other = await context.newPage();
    262   await load(other, row.owner);
    263   await prepareReceipt(page, row, receipt(row));
    264   await prepareReceipt(other, row, receipt(row));
    265   const results = await Promise.all([commit(page), commit(other)]);
    266   expect(results.filter((r) => r.ok)).toHaveLength(1);
    267   expect(results.filter((r) => !r.ok)).toEqual([
    268     { ok: false, reason: 'conflict' }
    269   ]);
    270   const winner = results[0].ok ? page : other,
    271     loser = results[0].ok ? other : page;
    272   expect((await commit(winner)).ok).toBe(true);
    273   expect(await observe(loser)).toEqual({ state: 'conflict' });
    274   await other.close();
    275 });
    276 test('changed capture or targets cannot replace the already captured operation', async ({
    277   page
    278 }) => {
    279   const f = fixture();
    280   await load(page, f.row.owner);
    281   await admit(page, f.row);
    282   const changed = {
    283     row: {
    284       ...f.row,
    285       capture: { ...f.row.capture, targets: ['wss://other.example.org'] }
    286     },
    287     wire: f.wire
    288   };
    289   await prepare(page, changed);
    290   expect(await commit(page)).toEqual({ ok: false, reason: 'conflict' });
    291   expect(await observe(page)).toEqual({ state: 'conflict' });
    292 });
    293 test('native put request success followed by abort is never a durable artifact acknowledgment', async ({
    294   page
    295 }) => {
    296   const f = fixture();
    297   await load(page, f.row.owner);
    298   await admit(page, f.row);
    299   await prepare(page, f);
    300   const result = await page.evaluate(async () => {
    301     const descriptor = Object.getOwnPropertyDescriptor(
    302       IDBObjectStore.prototype,
    303       'put'
    304     );
    305     if (!descriptor || typeof descriptor.value !== 'function')
    306       throw new Error('missing put');
    307     const original = descriptor.value as IDBObjectStore['put'];
    308     let successes = 0;
    309     Object.defineProperty(IDBObjectStore.prototype, 'put', {
    310       ...descriptor,
    311       value: function (
    312         this: IDBObjectStore,
    313         ...args: Parameters<IDBObjectStore['put']>
    314       ) {
    315         const request = Reflect.apply(original, this, args) as IDBRequest;
    316         const transaction = this.transaction;
    317         request.addEventListener(
    318           'success',
    319           () => {
    320             successes++;
    321             transaction.abort();
    322           },
    323           { once: true }
    324         );
    325         return request;
    326       }
    327     });
    328     try {
    329       return {
    330         result: await window.hcp050.commitPublicOperationTransition(
    331           window.hcp050Quota,
    332           window.hcp050Transition
    333         ),
    334         successes
    335       };
    336     } finally {
    337       Object.defineProperty(IDBObjectStore.prototype, 'put', descriptor);
    338     }
    339   });
    340   expect(result).toEqual({
    341     result: { ok: false, reason: 'aborted' },
    342     successes: 1
    343   });
    344   expect(await observe(page)).toEqual({ state: 'base_observed' });
    345 });
    346 test('unknown completion reconciles original expected payload after real native commit without another write', async ({
    347   page
    348 }) => {
    349   const f = fixture();
    350   await load(page, f.row.owner);
    351   await admit(page, f.row);
    352   await prepare(page, f);
    353   const result = await page.evaluate(async () => {
    354     const put = Object.getOwnPropertyDescriptor(
    355         IDBObjectStore.prototype,
    356         'put'
    357       ),
    358       abort = Object.getOwnPropertyDescriptor(
    359         IDBTransaction.prototype,
    360         'abort'
    361       );
    362     if (!put || !abort || typeof put.value !== 'function')
    363       throw new Error('missing methods');
    364     const original = put.value as IDBObjectStore['put'];
    365     let requests = 0;
    366     Object.defineProperty(IDBObjectStore.prototype, 'put', {
    367       ...put,
    368       value: function (
    369         this: IDBObjectStore,
    370         ...args: Parameters<IDBObjectStore['put']>
    371       ) {
    372         Reflect.apply(original, this, args);
    373         requests++;
    374         throw new Error('controlled delivery loss after native request queued');
    375       }
    376     });
    377     Object.defineProperty(IDBTransaction.prototype, 'abort', {
    378       ...abort,
    379       value() {
    380         throw new Error('controlled unavailable abort channel');
    381       }
    382     });
    383     try {
    384       return {
    385         result: await window.hcp050.commitPublicOperationTransition(
    386           window.hcp050Quota,
    387           window.hcp050Transition
    388         ),
    389         requests
    390       };
    391     } finally {
    392       Object.defineProperty(IDBObjectStore.prototype, 'put', put);
    393       Object.defineProperty(IDBTransaction.prototype, 'abort', abort);
    394     }
    395   });
    396   expect(result).toEqual({
    397     result: { ok: false, reason: 'unknown_completion' },
    398     requests: 1
    399   });
    400   expect(await observe(page)).toEqual({
    401     state: 'committed',
    402     id: f.row.id,
    403     revision: 1
    404   });
    405 });
    406 test('artifact replacement rechecks aggregate8MiB and preserves every original row on refusal', async ({
    407   page
    408 }) => {
    409   const f = fixture('p'.repeat(120000));
    410   await load(page, f.row.owner);
    411   const size = Buffer.byteLength(JSON.stringify(f.row));
    412   const count = Math.floor(8388608 / size);
    413   const rows: PublicOperationRecord[] = Array.from({ length: count }, () => ({
    414     ...f.row,
    415     id: randomUUID()
    416   }));
    417   rows[0] = f.row;
    418   await page.evaluate(async (rows) => {
    419     const api = window.hcp050;
    420     for (const row of rows) {
    421       const decoded = api.decodePublicRecord(
    422         JSON.stringify(row),
    423         row.owner,
    424         row.id
    425       );
    426       if (!decoded.ok) throw new Error(decoded.reason);
    427     }
    428     const transaction = api.browserDatabaseTransaction(
    429       window.hcp050Database,
    430       ['public_operations'],
    431       'readwrite'
    432     );
    433     for (const row of rows)
    434       transaction
    435         .objectStore('public_operations')
    436         .put({ owner: row.owner, id: row.id, wire: JSON.stringify(row) });
    437     await new Promise<void>((resolve, reject) => {
    438       transaction.addEventListener('complete', () => resolve());
    439       transaction.addEventListener('abort', () =>
    440         reject(new Error('seed aborted'))
    441       );
    442     });
    443   }, rows);
    444   await prepare(page, f);
    445   expect(await commit(page)).toEqual({ ok: false, reason: 'capacity' });
    446   expect(await observe(page)).toEqual({ state: 'base_observed' });
    447   const inventory = await page.evaluate(async () => {
    448     const api = window.hcp050;
    449     const result = await api.inspectPublicStorage(window.hcp050Quota);
    450     if (!result.ok) throw new Error(result.reason);
    451     return api.publicInventorySnapshot(window.hcp050Quota, result.value);
    452   });
    453   expect(inventory?.rows).toHaveLength(count);
    454 });
    455 test('unknown stored row aborts artifact transition and owner lifetime closes admission', async ({
    456   page
    457 }) => {
    458   const f = fixture();
    459   await load(page, f.row.owner);
    460   await admit(page, f.row);
    461   await prepare(page, f);
    462   await page.evaluate(async (row) => {
    463     const transaction = window.hcp050.browserDatabaseTransaction(
    464       window.hcp050Database,
    465       ['preference_operations'],
    466       'readwrite'
    467     );
    468     transaction.objectStore('preference_operations').put({
    469       owner: row.owner,
    470       id: '3d030bf5-901d-45e1-8251-41cbdf805e96',
    471       wire: 'unknown schema'
    472     });
    473     await new Promise<void>((resolve, reject) => {
    474       transaction.addEventListener('complete', () => resolve());
    475       transaction.addEventListener('abort', () =>
    476         reject(new Error('seed aborted'))
    477       );
    478     });
    479   }, f.row);
    480   expect(await commit(page)).toEqual({ ok: false, reason: 'corrupt_record' });
    481   expect(await observe(page)).toEqual({ state: 'unavailable' });
    482   await page.evaluate(() =>
    483     window.hcp050.closeBrowserDatabase(window.hcp050Database)
    484   );
    485   expect(await commit(page)).toEqual({ ok: false, reason: 'invalid_scope' });
    486 });
    487 
    488 test('genuine preference artifact and receipt CAS preserves source, consent, target role and public aggregate store', async ({
    489   page
    490 }) => {
    491   const key = crypto.getRandomValues(new Uint8Array(32));
    492   let event: ReturnType<typeof finalizeEvent>;
    493   try {
    494     event = finalizeEvent(
    495       {
    496         kind: 10050,
    497         created_at: 100,
    498         tags: [['relay', 'wss://inbox.example.org']],
    499         content: ''
    500       },
    501       key
    502     );
    503   } finally {
    504     key.fill(0);
    505   }
    506   const id = randomUUID();
    507   const template = {
    508     pubkey: event.pubkey,
    509     kind: 10050,
    510     created_at: 100,
    511     tags: event.tags,
    512     content: event.content
    513   };
    514   const row = {
    515     schema: 1 as const,
    516     family: 'preference_operation' as const,
    517     owner: event.pubkey,
    518     id,
    519     revision: 0,
    520     source: { type: 'inbox_head' as const, wire: null },
    521     consent: 'explicit_review' as const,
    522     capture: {
    523       kind: 10050 as const,
    524       wire: JSON.stringify(template),
    525       hash: getEventHash(template),
    526       targets: ['wss://one.example.org'],
    527       policyFingerprint: 'a'.repeat(64)
    528     },
    529     artifact: null,
    530     receipts: []
    531   };
    532   await load(page, row.owner);
    533   const result = await page.evaluate(
    534     async ({ row, wire, actionId }) => {
    535       const api = window.hcp050;
    536       const record = api.decodePublicRecord(
    537         JSON.stringify(row),
    538         row.owner,
    539         row.id
    540       );
    541       if (!record.ok) throw new Error(record.reason);
    542       const admitted = await api.admitPublicOperation(
    543         window.hcp050Quota,
    544         row.id,
    545         record.value
    546       );
    547       if (!admitted.ok) throw new Error(admitted.reason);
    548       const artifact = api.bindCapturedArtifact(
    549         wire,
    550         row.owner,
    551         10050,
    552         row.capture.hash
    553       );
    554       if (!artifact.ok) throw new Error(artifact.reason);
    555       const prepared = api.preparePublicArtifactTransition(
    556         record.value,
    557         row.owner,
    558         row.id,
    559         artifact.value
    560       );
    561       if (!prepared.ok) throw new Error(prepared.reason);
    562       const committed = await api.commitPublicOperationTransition(
    563         window.hcp050Quota,
    564         prepared.value
    565       );
    566       if (!committed.ok) throw new Error(committed.reason);
    567       const capture = api.publicTransitionSnapshot(
    568         prepared.value,
    569         row.owner,
    570         row.id
    571       );
    572       const signed = api.decodePublicRecord(
    573         capture?.nextWire,
    574         row.owner,
    575         row.id
    576       );
    577       if (!signed.ok) throw new Error(signed.reason);
    578       const fact = {
    579         actionId,
    580         origin: row.capture.targets[0],
    581         role: 'preference',
    582         attempt: 1,
    583         eventId: row.capture.hash,
    584         status: 'accepted',
    585         observedAtMilliseconds: 1000,
    586         readbackWire: wire
    587       };
    588       const receipt = api.preparePublicReceiptTransition(
    589         signed.value,
    590         row.owner,
    591         row.id,
    592         JSON.stringify(fact)
    593       );
    594       if (!receipt.ok) throw new Error(receipt.reason);
    595       const receiptCommit = await api.commitPublicOperationTransition(
    596         window.hcp050Quota,
    597         receipt.value
    598       );
    599       if (!receiptCommit.ok) throw new Error(receiptCommit.reason);
    600       const observed = await api.observePublicOperationTransition(
    601         window.hcp050Quota,
    602         receipt.value
    603       );
    604       const state = api.publicTransitionSnapshot(
    605         receipt.value,
    606         row.owner,
    607         row.id
    608       );
    609       const final = api.decodePublicRecord(state?.nextWire, row.owner, row.id);
    610       if (!final.ok) throw new Error(final.reason);
    611       const duplicate = api.preparePublicReceiptTransition(
    612         final.value,
    613         row.owner,
    614         row.id,
    615         JSON.stringify(fact)
    616       );
    617       if (!duplicate.ok) throw new Error(duplicate.reason);
    618       return {
    619         committed,
    620         receiptCommit,
    621         observed,
    622         duplicate: await api.commitPublicOperationTransition(
    623           window.hcp050Quota,
    624           duplicate.value
    625         ),
    626         record: api.publicRecordSnapshot(final.value, row.owner, row.id)
    627       };
    628     },
    629     { row, wire: JSON.stringify(event), actionId: randomUUID() }
    630   );
    631   expect(result.committed).toEqual({ ok: true, value: { id, revision: 1 } });
    632   expect(result.receiptCommit).toEqual({
    633     ok: true,
    634     value: { id, revision: 2 }
    635   });
    636   expect(result.observed).toEqual({ state: 'committed', id, revision: 2 });
    637   expect(result.duplicate).toEqual({ ok: true, value: { id, revision: 2 } });
    638   expect(result.record).toMatchObject({
    639     ...row,
    640     revision: 2,
    641     artifact: { eventId: event.id, wire: JSON.stringify(event) },
    642     receipts: [{ role: 'preference', readbackWire: JSON.stringify(event) }]
    643   });
    644 });