drafts.ts (14919B)
1 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; 2 import { canonicalPublicKey } from '../contracts/public-key.ts'; 3 import { 4 exactLocalFields, 5 type PublicDraftRecord, 6 type PublicDraftForm 7 } from '../contracts/local-records.ts'; 8 import { canonicalLocalId, newLocalId } from '../private-handles.ts'; 9 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; 10 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; 11 import { 12 browserDatabaseState, 13 browserDatabaseTransaction, 14 type BrowserDatabase 15 } from './database.ts'; 16 import { decodePublicRecord, publicRecordSnapshot } from './records.ts'; 17 18 declare const repositoryBrand: unique symbol; 19 export type PublicDraftRepository = Readonly<{ [repositoryBrand]: true }>; 20 type Scope = Readonly<{ database: BrowserDatabase; owner: string }>; 21 const repositories = new WeakMap<PublicDraftRepository, Scope>(); 22 export type DraftFailure = 23 | 'invalid_scope' 24 | 'invalid_id' 25 | 'invalid_form' 26 | 'invalid_revision' 27 | 'unavailable' 28 | 'not_found' 29 | 'conflict' 30 | 'cap_reached' 31 | 'corrupt_record' 32 | 'aborted' 33 | 'unknown_completion'; 34 export type DraftResult<T> = 35 | Readonly<{ ok: true; value: T }> 36 | Readonly<{ ok: false; reason: DraftFailure }>; 37 function failed(reason: DraftFailure): DraftResult<never> { 38 return { ok: false, reason }; 39 } 40 function scopeOf(repository: PublicDraftRepository): Scope | undefined { 41 const scope = repositories.get(repository); 42 try { 43 return scope && browserDatabaseState(scope.database).state === 'ready' 44 ? scope 45 : undefined; 46 } catch { 47 return undefined; 48 } 49 } 50 // Explicit acquisition only. A canonical owner is a namespace, not proof of 51 // installed identity; account workflows retain that separate authority. 52 export function createPublicDraftRepository( 53 database: BrowserDatabase, 54 expectedOwner: unknown 55 ): PublicDraftRepository | undefined { 56 const owner = canonicalPublicKey(expectedOwner); 57 try { 58 if (!owner || browserDatabaseState(database).state !== 'ready') 59 return undefined; 60 const handle = Object.freeze({}) as PublicDraftRepository; 61 repositories.set(handle, { database, owner }); 62 return handle; 63 } catch { 64 return undefined; 65 } 66 } 67 export function publicDraftRepositoryOwner( 68 repository: PublicDraftRepository 69 ): string | undefined { 70 return scopeOf(repository)?.owner; 71 } 72 73 // This copy is form admission only: no ID/time capture, storage or effect. 74 export function publicDraftFormSnapshot( 75 form: unknown 76 ): PublicDraftForm | undefined { 77 try { 78 if ( 79 !exactLocalFields(form, [ 80 'title', 81 'description', 82 'location', 83 'amount', 84 'currency', 85 'unit', 86 'quantity', 87 'contactType', 88 'contactValue' 89 ]) 90 ) 91 return undefined; 92 const copy = { 93 title: form.title, 94 description: form.description, 95 location: form.location, 96 amount: form.amount, 97 currency: form.currency, 98 unit: form.unit, 99 quantity: form.quantity, 100 contactType: form.contactType, 101 contactValue: form.contactValue 102 }; 103 if ( 104 typeof copy.title !== 'string' || 105 typeof copy.description !== 'string' || 106 typeof copy.location !== 'string' || 107 typeof copy.amount !== 'string' || 108 typeof copy.currency !== 'string' || 109 typeof copy.unit !== 'string' || 110 typeof copy.quantity !== 'string' || 111 typeof copy.contactValue !== 'string' || 112 (copy.contactType !== '' && 113 copy.contactType !== 'email' && 114 copy.contactType !== 'phone' && 115 copy.contactType !== 'https') 116 ) 117 return undefined; 118 let bytes = 0; 119 for (const text of [ 120 copy.title, 121 copy.description, 122 copy.location, 123 copy.amount, 124 copy.currency, 125 copy.unit, 126 copy.quantity, 127 copy.contactType, 128 copy.contactValue 129 ]) { 130 if (!boundedUtf8(text, LOCAL_PERSISTENCE_BUDGETS.draftComposedBytes)) 131 return undefined; 132 bytes += new TextEncoder().encode(text).length; 133 if (bytes > LOCAL_PERSISTENCE_BUDGETS.draftComposedBytes) 134 return undefined; 135 } 136 return { 137 title: copy.title, 138 description: copy.description, 139 location: copy.location, 140 amount: copy.amount, 141 currency: copy.currency, 142 unit: copy.unit, 143 quantity: copy.quantity, 144 contactType: copy.contactType, 145 contactValue: copy.contactValue 146 }; 147 } catch { 148 return undefined; 149 } 150 } 151 function proposed( 152 owner: string, 153 id: string, 154 revision: number, 155 form: unknown 156 ): PublicDraftRecord | undefined { 157 try { 158 const captured = publicDraftFormSnapshot(form); 159 if (!captured) return undefined; 160 const row = { 161 schema: 1, 162 family: 'public_draft', 163 owner, 164 id, 165 revision, 166 savedAtMilliseconds: Date.now(), 167 form: captured 168 }; 169 const admitted = decodePublicRecord(JSON.stringify(row), owner, id); 170 if (!admitted.ok) return undefined; 171 const snapshot = publicRecordSnapshot(admitted.value, owner, id); 172 return snapshot?.family === 'public_draft' ? snapshot : undefined; 173 } catch { 174 return undefined; 175 } 176 } 177 function stored( 178 value: unknown, 179 owner: string, 180 id: string 181 ): PublicDraftRecord | undefined { 182 if ( 183 !exactLocalFields(value, ['owner', 'id', 'wire']) || 184 value.owner !== owner || 185 value.id !== id 186 ) 187 return undefined; 188 const admitted = decodePublicRecord(value.wire, owner, id); 189 if (!admitted.ok) return undefined; 190 const snapshot = publicRecordSnapshot(admitted.value, owner, id); 191 return snapshot?.family === 'public_draft' ? snapshot : undefined; 192 } 193 function transaction<T>( 194 scope: Scope, 195 mode: 'readonly' | 'readwrite', 196 run: ( 197 store: IDBObjectStore, 198 decide: (result: DraftResult<T>) => void, 199 refuse: (reason: DraftFailure) => void 200 ) => void 201 ): Promise<DraftResult<T>> { 202 let active: IDBTransaction; 203 try { 204 active = browserDatabaseTransaction( 205 scope.database, 206 ['public_drafts'], 207 mode 208 ); 209 } catch { 210 return Promise.resolve(failed('unavailable')); 211 } 212 return new Promise((resolve) => { 213 let decision: DraftResult<T> | undefined; 214 function refuse(reason: DraftFailure): void { 215 decision = failed(reason); 216 try { 217 active.abort(); 218 } catch { 219 decision = failed('unknown_completion'); 220 } 221 } 222 active.addEventListener('complete', () => 223 resolve(decision ?? failed('unknown_completion')) 224 ); 225 active.addEventListener('abort', () => 226 resolve(decision && !decision.ok ? decision : failed('aborted')) 227 ); 228 // A request success never acknowledges a save. Only the transaction's 229 // complete event returns its captured payload; abort overrides any success. 230 try { 231 run( 232 active.objectStore('public_drafts'), 233 (result) => { 234 decision = result; 235 }, 236 refuse 237 ); 238 } catch { 239 refuse('aborted'); 240 } 241 }); 242 } 243 export function createPublicDraft( 244 repository: PublicDraftRepository, 245 form: unknown 246 ): Promise<DraftResult<PublicDraftRecord>> { 247 const captured = capturePublicDraftCreate(repository, form); 248 return captured.ok 249 ? commitPublicDraftWrite(repository, captured.value) 250 : Promise.resolve(captured); 251 } 252 export function readPublicDraft( 253 repository: PublicDraftRepository, 254 expectedId: unknown 255 ): Promise<DraftResult<PublicDraftRecord>> { 256 const scope = scopeOf(repository), 257 id = canonicalLocalId(expectedId); 258 if (!scope) return Promise.resolve(failed('invalid_scope')); 259 if (!id) return Promise.resolve(failed('invalid_id')); 260 return transaction(scope, 'readonly', (store, decide, refuse) => { 261 const request = store.get([scope.owner, id]); 262 request.addEventListener('success', () => { 263 if (request.result === undefined) { 264 decide(failed('not_found')); 265 return; 266 } 267 const row = stored(request.result, scope.owner, id); 268 if (!row) { 269 refuse('corrupt_record'); 270 return; 271 } 272 decide({ ok: true, value: row }); 273 }); 274 }); 275 } 276 export function savePublicDraft( 277 repository: PublicDraftRepository, 278 expectedId: unknown, 279 expectedRevision: unknown, 280 form: unknown 281 ): Promise<DraftResult<PublicDraftRecord>> { 282 const captured = capturePublicDraftSave( 283 repository, 284 expectedId, 285 expectedRevision, 286 form 287 ); 288 return captured.ok 289 ? commitPublicDraftWrite(repository, captured.value) 290 : Promise.resolve(captured); 291 } 292 export function listPublicDrafts( 293 repository: PublicDraftRepository 294 ): Promise<DraftResult<readonly PublicDraftRecord[]>> { 295 const scope = scopeOf(repository); 296 if (!scope) return Promise.resolve(failed('invalid_scope')); 297 return transaction(scope, 'readonly', (store, decide, refuse) => { 298 let rows = Array.from<PublicDraftRecord>([]); 299 const request = store 300 .index('by_owner') 301 .openCursor(IDBKeyRange.only(scope.owner)); 302 request.addEventListener('success', () => { 303 const cursor = request.result; 304 if (!cursor) { 305 decide({ ok: true, value: rows }); 306 return; 307 } 308 if (rows.length >= LOCAL_PERSISTENCE_BUDGETS.publicDrafts) { 309 refuse('cap_reached'); 310 return; 311 } 312 const key = cursor.primaryKey; 313 if (!Array.isArray(key) || key.length !== 2 || key[0] !== scope.owner) { 314 refuse('corrupt_record'); 315 return; 316 } 317 const id = canonicalLocalId(key[1]); 318 const row = id && stored(cursor.value, scope.owner, id); 319 if (!row) { 320 refuse('corrupt_record'); 321 return; 322 } 323 rows = rows.concat(row); 324 cursor.continue(); 325 }); 326 }); 327 } 328 329 // Immutable attempted local writes retain their original ID, revision, time and 330 // full form. They authorize only this repository's bounded local transaction. 331 declare const writeBrand: unique symbol; 332 export type PublicDraftWrite = Readonly<{ [writeBrand]: true }>; 333 type Write = Readonly<{ 334 repository: PublicDraftRepository; 335 wire: string; 336 expectedRevision: number | null; 337 }>; 338 const writes = new WeakMap<PublicDraftWrite, Write>(); 339 function capture( 340 repository: PublicDraftRepository, 341 id: string, 342 expectedRevision: number | null, 343 form: unknown 344 ): DraftResult<PublicDraftWrite> { 345 const scope = scopeOf(repository); 346 if (!scope) return failed('invalid_scope'); 347 const row = proposed( 348 scope.owner, 349 id, 350 expectedRevision === null ? 0 : expectedRevision + 1, 351 form 352 ); 353 if (!row) return failed('invalid_form'); 354 const handle = Object.freeze({}) as PublicDraftWrite; 355 writes.set(handle, { 356 repository, 357 wire: JSON.stringify(row), 358 expectedRevision 359 }); 360 return { ok: true, value: handle }; 361 } 362 export function capturePublicDraftCreate( 363 repository: PublicDraftRepository, 364 form: unknown 365 ): DraftResult<PublicDraftWrite> { 366 if (!scopeOf(repository)) return failed('invalid_scope'); 367 const id = newLocalId(); 368 return id ? capture(repository, id, null, form) : failed('invalid_id'); 369 } 370 export function capturePublicDraftSave( 371 repository: PublicDraftRepository, 372 expectedId: unknown, 373 expectedRevision: unknown, 374 form: unknown 375 ): DraftResult<PublicDraftWrite> { 376 if (!scopeOf(repository)) return failed('invalid_scope'); 377 const id = canonicalLocalId(expectedId), 378 revision = safeUnsignedInteger(expectedRevision); 379 if (!id) return failed('invalid_id'); 380 if (revision === undefined || revision === Number.MAX_SAFE_INTEGER) 381 return failed('invalid_revision'); 382 return capture(repository, id, revision, form); 383 } 384 function writeOf( 385 repository: PublicDraftRepository, 386 handle: PublicDraftWrite 387 ): Write | undefined { 388 const write = writes.get(handle); 389 return scopeOf(repository) && write?.repository === repository 390 ? write 391 : undefined; 392 } 393 export function publicDraftWriteSnapshot( 394 repository: PublicDraftRepository, 395 handle: PublicDraftWrite 396 ): PublicDraftRecord | undefined { 397 const write = writeOf(repository, handle); 398 return write ? (JSON.parse(write.wire) as PublicDraftRecord) : undefined; 399 } 400 export function commitPublicDraftWrite( 401 repository: PublicDraftRepository, 402 handle: PublicDraftWrite 403 ): Promise<DraftResult<PublicDraftRecord>> { 404 const write = writeOf(repository, handle), 405 scope = scopeOf(repository); 406 if (!write || !scope) return Promise.resolve(failed('invalid_scope')); 407 const row = JSON.parse(write.wire) as PublicDraftRecord; 408 return transaction(scope, 'readwrite', (store, decide, refuse) => { 409 const request = store.get([scope.owner, row.id]); 410 request.addEventListener('success', () => { 411 if (request.result !== undefined) { 412 const previous = stored(request.result, scope.owner, row.id); 413 if (!previous) { 414 refuse('corrupt_record'); 415 return; 416 } 417 if (JSON.stringify(previous) === write.wire) { 418 decide({ ok: true, value: row }); 419 return; 420 } 421 if ( 422 write.expectedRevision === null || 423 previous.revision !== write.expectedRevision 424 ) { 425 refuse('conflict'); 426 return; 427 } 428 const put = store.put({ 429 owner: scope.owner, 430 id: row.id, 431 wire: write.wire 432 }); 433 put.addEventListener('success', () => decide({ ok: true, value: row })); 434 return; 435 } 436 if (write.expectedRevision !== null) { 437 refuse('not_found'); 438 return; 439 } 440 const count = store 441 .index('by_owner') 442 .count(IDBKeyRange.only(scope.owner)); 443 count.addEventListener('success', () => { 444 if (count.result >= LOCAL_PERSISTENCE_BUDGETS.publicDrafts) { 445 refuse('cap_reached'); 446 return; 447 } 448 const put = store.put({ 449 owner: scope.owner, 450 id: row.id, 451 wire: write.wire 452 }); 453 put.addEventListener('success', () => decide({ ok: true, value: row })); 454 }); 455 }); 456 }); 457 } 458 export type DraftWriteObservation = 459 | Readonly<{ state: 'committed'; value: PublicDraftRecord }> 460 | Readonly<{ state: 'base_observed' }> 461 | Readonly<{ state: 'conflict' }> 462 | Readonly<{ state: 'unavailable'; reason: DraftFailure }>; 463 export async function observePublicDraftWrite( 464 repository: PublicDraftRepository, 465 handle: PublicDraftWrite 466 ): Promise<DraftWriteObservation> { 467 const write = writeOf(repository, handle); 468 if (!write) return { state: 'unavailable', reason: 'invalid_scope' }; 469 const expected = JSON.parse(write.wire) as PublicDraftRecord; 470 const read = await readPublicDraft(repository, expected.id); 471 if (!read.ok) 472 return read.reason === 'not_found' && write.expectedRevision === null 473 ? { state: 'base_observed' } 474 : { state: 'unavailable', reason: read.reason }; 475 if (JSON.stringify(read.value) === write.wire) 476 return { state: 'committed', value: read.value }; 477 return read.value.revision === write.expectedRevision 478 ? { state: 'base_observed' } 479 : { state: 'conflict' }; 480 }