app

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

idb-faults.spec.ts (10451B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { createHash } from 'node:crypto';
      4 import { fileURLToPath } from 'node:url';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 import type * as Database from '../../src/lib/persistence/database.ts';
      7 import type * as Drafts from '../../src/lib/persistence/drafts.ts';
      8 declare global {
      9   interface Window {
     10     hcp134: typeof Database & typeof Drafts;
     11     hcp134Database: Database.BrowserDatabase;
     12     hcp134Repository: Drafts.PublicDraftRepository;
     13     hcp134ExtensionReads: number;
     14   }
     15 }
     16 const owner =
     17   '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
     18 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
     19 test.beforeAll(async () => {
     20   server = await createStaticHarness();
     21   const source = (name: string) =>
     22     fileURLToPath(
     23       new URL('../../src/lib/persistence/' + name, import.meta.url)
     24     );
     25   const result = await build({
     26     configFile: false,
     27     logLevel: 'silent',
     28     plugins: [
     29       {
     30         name: 'hcp134-real-idb-entry',
     31         resolveId(id) {
     32           if (id === 'virtual:hcp134') return '\0hcp134';
     33         },
     34         load(id) {
     35           if (id === '\0hcp134')
     36             return ['database.ts', 'drafts.ts']
     37               .map((name) => `export * from ${JSON.stringify(source(name))};`)
     38               .join('');
     39         }
     40       }
     41     ],
     42     build: {
     43       write: false,
     44       minify: false,
     45       rolldownOptions: { input: 'virtual:hcp134' },
     46       lib: { entry: 'virtual:hcp134', name: 'hcp134', formats: ['iife'] }
     47     }
     48   });
     49   const output = Array.isArray(result) ? result[0] : result;
     50   if (!('output' in output))
     51     throw Error('missing real IDB qualification bundle');
     52   const chunks = output.output.filter((entry) => entry.type === 'chunk');
     53   expect(chunks).toHaveLength(1);
     54   bundle = chunks[0].code;
     55   console.log(
     56     JSON.stringify({
     57       fixture: 'HCP134_ACTUAL_DRAFT_IDB_FAULT_AND_PAGE_RELOAD',
     58       bundle_sha256: createHash('sha256').update(bundle).digest('hex'),
     59       modules: Object.keys(chunks[0].modules),
     60       scope:
     61         'Actual original database/draft modules in a test-only virtual entry; injected native-write faults, not physical host quota exhaustion or pipeline publication proof'
     62     })
     63   );
     64 });
     65 test.afterAll(async () => server.close());
     66 async function load(page: Page, navigate = true) {
     67   if (navigate) await page.goto(server.url + '/search');
     68   await page.addScriptTag({ content: bundle });
     69   await page.evaluate(async (owner) => {
     70     const api = window.hcp134,
     71       opened = await api.openBrowserDatabase();
     72     if (opened.state !== 'ready') throw Error(opened.reason);
     73     const repository = api.createPublicDraftRepository(opened.owner, owner);
     74     if (!repository) throw Error('missing original owner draft repository');
     75     window.hcp134Database = opened.owner;
     76     window.hcp134Repository = repository;
     77   }, owner);
     78 }
     79 for (const boundary of ['create', 'save'] as const)
     80   for (const fault of ['abort', 'quota', 'unknown'] as const)
     81     test(`HCP134 real draft ${boundary} ${fault} preserves one exact original write through explicit retry and actual page reload`, async ({
     82       page
     83     }) => {
     84       let sockets = 0;
     85       page.on('websocket', () => sockets++);
     86       await page.addInitScript(() => {
     87         window.hcp134ExtensionReads = 0;
     88         Object.defineProperty(window, 'nostr', {
     89           configurable: true,
     90           get() {
     91             window.hcp134ExtensionReads++;
     92             throw Error('HCP134 unsolicited extension access');
     93           }
     94         });
     95       });
     96       await load(page);
     97       const result = await page.evaluate(
     98         async ({ boundary, fault }) => {
     99           const api = window.hcp134,
    100             repository = window.hcp134Repository;
    101           const form = {
    102             title: 'Public partial draft',
    103             description: 'HCP134_PUBLIC_DRAFT_UNFINISHED_STRINGS',
    104             location: '',
    105             amount: '.',
    106             currency: '',
    107             unit: '',
    108             quantity: '',
    109             contactType: '' as const,
    110             contactValue: ''
    111           };
    112           const base =
    113             boundary === 'save'
    114               ? await api.createPublicDraft(repository, form)
    115               : undefined;
    116           if (base && !base.ok) throw Error(base.reason);
    117           const next = {
    118             ...form,
    119             title: 'Acknowledged public edit',
    120             description: 'HCP134_PUBLIC_EXACT_CAPTURE_é😀',
    121             amount: '3.5'
    122           };
    123           const captured = base?.ok
    124             ? api.capturePublicDraftSave(
    125                 repository,
    126                 base.value.id,
    127                 base.value.revision,
    128                 next
    129               )
    130             : api.capturePublicDraftCreate(repository, next);
    131           if (!captured.ok) throw Error(captured.reason);
    132           const expected = api.publicDraftWriteSnapshot(
    133             repository,
    134             captured.value
    135           );
    136           if (!expected) throw Error('missing immutable original write');
    137           const nativePut = Reflect.get<IDBObjectStore, 'put'>(
    138               IDBObjectStore.prototype,
    139               'put'
    140             ),
    141             nativeAbort = Reflect.get<IDBTransaction, 'abort'>(
    142               IDBTransaction.prototype,
    143               'abort'
    144             );
    145           let hits = 0;
    146           IDBObjectStore.prototype.put = function (
    147             value: unknown,
    148             key?: IDBValidKey
    149           ) {
    150             if (this.name !== 'public_drafts' || hits > 0)
    151               return key === undefined
    152                 ? nativePut.call(this, value)
    153                 : nativePut.call(this, value, key);
    154             hits++;
    155             if (fault === 'quota')
    156               throw new DOMException(
    157                 'Controlled native-write quota refusal',
    158                 'QuotaExceededError'
    159               );
    160             const request =
    161               key === undefined
    162                 ? nativePut.call(this, value)
    163                 : nativePut.call(this, value, key);
    164             if (fault === 'abort')
    165               request.addEventListener(
    166                 'success',
    167                 () => nativeAbort.call(this.transaction),
    168                 { once: true }
    169               );
    170             else
    171               return new Proxy(request, {
    172                 get(target, property) {
    173                   if (property === 'addEventListener')
    174                     return (
    175                       ...args: Parameters<IDBRequest['addEventListener']>
    176                     ) => {
    177                       // Lose only the producer request-success callback. The real
    178                       // queued write and native transaction still complete normally.
    179                       if (args[0] !== 'success')
    180                         target.addEventListener(...args);
    181                     };
    182                   return Reflect.get(target, property, target) as unknown;
    183                 }
    184               });
    185             return request;
    186           };
    187           let first: Awaited<ReturnType<typeof api.commitPublicDraftWrite>>;
    188           try {
    189             first = await api.commitPublicDraftWrite(
    190               repository,
    191               captured.value
    192             );
    193           } finally {
    194             IDBObjectStore.prototype.put = nativePut;
    195           }
    196           const observed = await api.observePublicDraftWrite(
    197             repository,
    198             captured.value
    199           );
    200           const beforeRetry = await api.listPublicDrafts(repository);
    201           let retryPuts = 0;
    202           IDBObjectStore.prototype.put = function (
    203             value: unknown,
    204             key?: IDBValidKey
    205           ) {
    206             if (this.name === 'public_drafts') retryPuts++;
    207             return key === undefined
    208               ? nativePut.call(this, value)
    209               : nativePut.call(this, value, key);
    210           };
    211           let retry: Awaited<ReturnType<typeof api.commitPublicDraftWrite>>;
    212           try {
    213             retry = await api.commitPublicDraftWrite(
    214               repository,
    215               captured.value
    216             );
    217           } finally {
    218             IDBObjectStore.prototype.put = nativePut;
    219           }
    220           const retained = await api.readPublicDraft(repository, expected.id),
    221             rows = await api.listPublicDrafts(repository);
    222           api.closeBrowserDatabase(window.hcp134Database);
    223           return {
    224             first,
    225             hits,
    226             expected,
    227             base: base?.ok ? base.value : null,
    228             observed,
    229             beforeRetry,
    230             retry,
    231             retryPuts,
    232             retained,
    233             rows
    234           };
    235         },
    236         { boundary, fault }
    237       );
    238       expect(result.hits).toBe(1);
    239       expect(result.first).toEqual({
    240         ok: false,
    241         reason: fault === 'unknown' ? 'unknown_completion' : 'aborted'
    242       });
    243       if (fault === 'unknown') {
    244         expect(result.observed).toEqual({
    245           state: 'committed',
    246           value: result.expected
    247         });
    248         expect(result.beforeRetry).toEqual({
    249           ok: true,
    250           value: [result.expected]
    251         });
    252         expect(result.retryPuts).toBe(0);
    253       } else {
    254         expect(result.observed).toEqual({ state: 'base_observed' });
    255         expect(result.beforeRetry).toEqual({
    256           ok: true,
    257           value: result.base ? [result.base] : []
    258         });
    259         expect(result.retryPuts).toBe(1);
    260       }
    261       expect(result.retry).toEqual({ ok: true, value: result.expected });
    262       expect(result.retained).toEqual(result.retry);
    263       expect(result.rows).toEqual({ ok: true, value: [result.expected] });
    264       expect(await page.evaluate(() => window.hcp134ExtensionReads)).toBe(0);
    265       await page.reload();
    266       await load(page, false);
    267       const reopened = await page.evaluate(async (id) => {
    268         const api = window.hcp134,
    269           repository = window.hcp134Repository;
    270         try {
    271           return {
    272             row: await api.readPublicDraft(repository, id),
    273             rows: await api.listPublicDrafts(repository)
    274           };
    275         } finally {
    276           api.closeBrowserDatabase(window.hcp134Database);
    277         }
    278       }, result.expected.id);
    279       expect(reopened.row).toEqual({ ok: true, value: result.expected });
    280       expect(reopened.rows).toEqual({ ok: true, value: [result.expected] });
    281       expect(sockets).toBe(0);
    282       expect(await page.evaluate(() => window.hcp134ExtensionReads)).toBe(0);
    283     });