quota.ts (25863B)
1 import { canonicalPublicKey } from '../contracts/public-key.ts'; 2 import { 3 exactLocalFields, 4 type PublicRecord, 5 type PublicDraftRecord 6 } from '../contracts/local-records.ts'; 7 import { canonicalLocalId } from '../private-handles.ts'; 8 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; 9 import { 10 browserDatabaseState, 11 browserDatabaseTransaction, 12 type BrowserDatabase 13 } from './database.ts'; 14 import { 15 decodePublicRecord, 16 publicRecordSnapshot, 17 publicRecordWire, 18 type PublicRecordHandle 19 } from './records.ts'; 20 import { 21 publicInventoryRow, 22 PUBLIC_CLEANUP_CONSEQUENCES, 23 type PublicInventoryRow 24 } from './local-inventory.ts'; 25 26 import { 27 publicTransitionIdentity, 28 publicTransitionSnapshot, 29 type PublicOperationTransition 30 } from './artifact-records.ts'; 31 import { decideFrozenTransition } from './operation-transactions.ts'; 32 import { inspectLocalTemplate } from '../nostr/local-template.ts'; 33 34 declare const repositoryBrand: unique symbol; 35 declare const inventoryBrand: unique symbol; 36 declare const cleanupBrand: unique symbol; 37 export type PublicQuotaRepository = Readonly<{ [repositoryBrand]: true }>; 38 export type PublicInventory = Readonly<{ [inventoryBrand]: true }>; 39 export type PublicCleanup = Readonly<{ [cleanupBrand]: true }>; 40 export type PublicQuotaFailure = 41 | 'invalid_scope' 42 | 'invalid_record' 43 | 'invalid_selection' 44 | 'protected' 45 | 'conflict' 46 | 'capacity' 47 | 'corrupt_record' 48 | 'unavailable' 49 | 'aborted' 50 | 'unknown_completion'; 51 export type PublicQuotaResult<T> = 52 | Readonly<{ ok: true; value: T }> 53 | Readonly<{ ok: false; reason: PublicQuotaFailure }>; 54 type Scope = Readonly<{ database: BrowserDatabase; owner: string }>; 55 type Store = 'public_drafts' | 'public_operations' | 'preference_operations'; 56 type Row = Readonly<{ 57 store: Store; 58 wire: string; 59 record: PublicRecord; 60 bytes: number; 61 }>; 62 type Inspection = Readonly<{ 63 repository: PublicQuotaRepository; 64 rows: readonly Row[]; 65 }>; 66 type Cleanup = Readonly<{ inventory: Inspection; selected: readonly string[] }>; 67 const repositories = new WeakMap<PublicQuotaRepository, Scope>(); 68 const inventories = new WeakMap<PublicInventory, Inspection>(); 69 const cleanups = new WeakMap<PublicCleanup, Cleanup>(); 70 const stores: readonly Store[] = [ 71 'public_drafts', 72 'public_operations', 73 'preference_operations' 74 ]; 75 function failed(reason: PublicQuotaFailure): PublicQuotaResult<never> { 76 return { ok: false, reason }; 77 } 78 function scopeOf(repository: PublicQuotaRepository): Scope | undefined { 79 const scope = repositories.get(repository); 80 try { 81 return scope && browserDatabaseState(scope.database).state === 'ready' 82 ? scope 83 : undefined; 84 } catch { 85 return undefined; 86 } 87 } 88 // Metadata only; this does not grant installed-account or effect authority. 89 export function publicQuotaOwner( 90 repository: PublicQuotaRepository 91 ): string | undefined { 92 return scopeOf(repository)?.owner; 93 } 94 // A namespace capability only; installed-account authorization belongs to the 95 // account workflow. This repository never acquires any private store. 96 export function createPublicQuotaRepository( 97 database: BrowserDatabase, 98 expectedOwner: unknown 99 ): PublicQuotaRepository | undefined { 100 const owner = canonicalPublicKey(expectedOwner); 101 try { 102 if (!owner || browserDatabaseState(database).state !== 'ready') 103 return undefined; 104 const handle = Object.freeze({}) as PublicQuotaRepository; 105 repositories.set(handle, { database, owner }); 106 return handle; 107 } catch { 108 return undefined; 109 } 110 } 111 function stored( 112 value: unknown, 113 store: Store, 114 owner: string, 115 id: string 116 ): Row | undefined { 117 if ( 118 !exactLocalFields(value, ['owner', 'id', 'wire']) || 119 value.owner !== owner || 120 value.id !== id || 121 typeof value.wire !== 'string' 122 ) 123 return undefined; 124 const admitted = decodePublicRecord(value.wire, owner, id); 125 if (!admitted.ok) return undefined; 126 const record = publicRecordSnapshot(admitted.value, owner, id); 127 const family = 128 store === 'public_drafts' 129 ? 'public_draft' 130 : store === 'public_operations' 131 ? 'public_operation' 132 : 'preference_operation'; 133 return record?.family === family 134 ? { 135 store, 136 record, 137 wire: value.wire, 138 bytes: new TextEncoder().encode(value.wire).length 139 } 140 : undefined; 141 } 142 function transaction<T>( 143 scope: Scope, 144 mode: 'readonly' | 'readwrite', 145 finish: ( 146 rows: readonly Row[], 147 transaction: IDBTransaction, 148 refuse: (reason: PublicQuotaFailure) => void 149 ) => PublicQuotaResult<T> | undefined, 150 signal?: AbortSignal 151 ): Promise<PublicQuotaResult<T>> { 152 if (signal?.aborted) return Promise.resolve(failed('aborted')); 153 let active: IDBTransaction; 154 try { 155 active = browserDatabaseTransaction(scope.database, stores, mode); 156 } catch { 157 return Promise.resolve(failed('unavailable')); 158 } 159 return new Promise((resolve) => { 160 let result: PublicQuotaResult<T> | undefined; 161 let rows = Array.from<Row>([]), 162 draftCount = 0, 163 operationCount = 0, 164 operationBytes = 0; 165 function refuse(reason: PublicQuotaFailure) { 166 result = failed(reason); 167 try { 168 active.abort(); 169 } catch { 170 result = failed('unknown_completion'); 171 } 172 } 173 const cancel = () => refuse('aborted'); 174 signal?.addEventListener('abort', cancel, { once: true }); 175 active.addEventListener('complete', () => { 176 signal?.removeEventListener('abort', cancel); 177 resolve(result ?? failed('unknown_completion')); 178 }); 179 active.addEventListener('abort', () => { 180 signal?.removeEventListener('abort', cancel); 181 resolve(result && !result.ok ? result : failed('aborted')); 182 }); 183 if (signal?.aborted) { 184 cancel(); 185 return; 186 } 187 function scan(index: number): void { 188 try { 189 const store = stores[index]; 190 if (store === undefined) { 191 const finished = finish(rows, active, refuse); 192 if (finished !== undefined) result = finished; 193 return; 194 } 195 const request = active 196 .objectStore(store) 197 .index('by_owner') 198 .openCursor(IDBKeyRange.only(scope.owner)); 199 request.addEventListener('success', () => { 200 try { 201 const cursor = request.result; 202 if (!cursor) { 203 scan(index + 1); 204 return; 205 } 206 const key = cursor.primaryKey; 207 const id = 208 Array.isArray(key) && key.length === 2 && key[0] === scope.owner 209 ? canonicalLocalId(key[1]) 210 : undefined; 211 const row = id && stored(cursor.value, store, scope.owner, id); 212 if (!row) { 213 refuse('corrupt_record'); 214 return; 215 } 216 if (row.record.family === 'public_draft') draftCount++; 217 else { 218 operationCount++; 219 operationBytes += row.bytes; 220 } 221 if ( 222 draftCount > LOCAL_PERSISTENCE_BUDGETS.publicDrafts || 223 operationCount > LOCAL_PERSISTENCE_BUDGETS.publicOperations || 224 operationBytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes 225 ) { 226 refuse('capacity'); 227 return; 228 } 229 rows = rows.concat(row); 230 cursor.continue(); 231 } catch { 232 refuse('aborted'); 233 } 234 }); 235 } catch { 236 refuse('aborted'); 237 } 238 } 239 scan(0); 240 }); 241 } 242 // Explicit new-row admission only. Artifact/CAS transitions retain HCP050. 243 // Logical bytes include the exact stored record wire, not browser disk/heap use. 244 export function admitPublicOperation( 245 repository: PublicQuotaRepository, 246 expectedId: unknown, 247 handle: PublicRecordHandle 248 ): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> { 249 const scope = scopeOf(repository), 250 id = canonicalLocalId(expectedId); 251 if (!scope) return Promise.resolve(failed('invalid_scope')); 252 if (!id) return Promise.resolve(failed('invalid_record')); 253 const record = publicRecordSnapshot(handle, scope.owner, id), 254 wire = publicRecordWire(handle, scope.owner, id); 255 if ( 256 !record || 257 !wire || 258 record.family === 'public_draft' || 259 record.revision !== 0 260 ) 261 return Promise.resolve(failed('invalid_record')); 262 const store: Store = 263 record.family === 'public_operation' 264 ? 'public_operations' 265 : 'preference_operations'; 266 const bytes = new TextEncoder().encode(wire).length; 267 return transaction(scope, 'readwrite', (rows, active, refuse) => { 268 const previous = rows.find( 269 (row) => row.store === store && row.record.id === id 270 ); 271 if (previous) 272 return previous.wire === wire 273 ? { ok: true, value: { id, revision: 0 } } 274 : (refuse('conflict'), undefined); 275 const operations = rows.filter( 276 (row) => row.record.family !== 'public_draft' 277 ); 278 if ( 279 operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations || 280 operations.reduce((sum, row) => sum + row.bytes, bytes) > 281 LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes 282 ) { 283 refuse('capacity'); 284 return; 285 } 286 active.objectStore(store).put({ owner: scope.owner, id, wire }); 287 return { ok: true, value: { id, revision: 0 } }; 288 }); 289 } 290 // Claim under the caller's origin/author Web Lock. A previous capture is never 291 // overwritten or automatically signed again, even after a page lost its lock. 292 // No extension/network await occurs inside the short transaction. 293 export function claimPublicOperation( 294 repository: PublicQuotaRepository, 295 expectedId: unknown, 296 handle: PublicRecordHandle 297 ): Promise< 298 PublicQuotaResult< 299 Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> 300 > 301 > { 302 return claimOperation(repository, expectedId, handle); 303 } 304 type DraftAdmission = Readonly<{ 305 expected: PublicDraftRecord; 306 current(this: void): boolean; 307 draftCurrent(this: void): boolean; 308 revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>; 309 }>; 310 // Storage-only atomic draft/CAS reservation. Current original account/review 311 // ownership is supplied by the public listing command owner, never a UI flag. 312 // Existing commands retain their original capture even after future draft edits. 313 export function claimPublicDraftOperation( 314 repository: PublicQuotaRepository, 315 expectedId: unknown, 316 handle: PublicRecordHandle, 317 admission: DraftAdmission 318 ): Promise< 319 PublicQuotaResult< 320 Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> 321 > 322 > { 323 return claimOperation(repository, expectedId, handle, admission); 324 } 325 function claimOperation( 326 repository: PublicQuotaRepository, 327 expectedId: unknown, 328 handle: PublicRecordHandle, 329 draft?: DraftAdmission 330 ): Promise< 331 PublicQuotaResult< 332 Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> 333 > 334 > { 335 const scope = scopeOf(repository), 336 id = canonicalLocalId(expectedId); 337 if (!scope) return Promise.resolve(failed('invalid_scope')); 338 if (!id) return Promise.resolve(failed('invalid_record')); 339 const record = publicRecordSnapshot(handle, scope.owner, id), 340 wire = publicRecordWire(handle, scope.owner, id); 341 if ( 342 !record || 343 !wire || 344 record.family === 'public_draft' || 345 record.revision !== 0 || 346 record.artifact !== null 347 ) 348 return Promise.resolve(failed('invalid_record')); 349 const store: Store = 350 record.family === 'public_operation' 351 ? 'public_operations' 352 : 'preference_operations'; 353 const bytes = new TextEncoder().encode(wire).length; 354 return transaction< 355 Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }> 356 >(scope, 'readwrite', (rows, active, refuse) => { 357 if (draft && !draft.current()) { 358 refuse('unavailable'); 359 return; 360 } 361 const previous = rows.find( 362 (row) => row.record.family !== 'public_draft' && row.record.id === id 363 ); 364 if (previous) { 365 const original = previous.record; 366 if ( 367 original.family === 'public_draft' || 368 original.family !== record.family || 369 JSON.stringify(original.source) !== JSON.stringify(record.source) || 370 JSON.stringify(original.capture) !== JSON.stringify(record.capture) || 371 ('consent' in original ? original.consent : null) !== 372 ('consent' in record ? record.consent : null) 373 ) { 374 refuse('conflict'); 375 return; 376 } 377 const decoded = decodePublicRecord(previous.wire, scope.owner, id); 378 if (!decoded.ok) { 379 refuse('corrupt_record'); 380 return; 381 } 382 return { ok: true, value: { state: 'existing', record: decoded.value } }; 383 } 384 if (draft) { 385 if (draft.revisionBase) { 386 const revisionBase = draft.revisionBase; 387 const witness = publicRecordSnapshot( 388 revisionBase.record, 389 scope.owner, 390 revisionBase.command 391 ); 392 const base = rows.find( 393 (row) => 394 row.record.family === 'public_operation' && 395 row.record.id === revisionBase.command 396 )?.record; 397 const oldTemplate = 398 witness?.family === 'public_operation' && 399 inspectLocalTemplate(witness.capture.wire, scope.owner, 30402); 400 const nextTemplate = 401 record.family === 'public_operation' && 402 inspectLocalTemplate( 403 record.capture.wire, 404 scope.owner, 405 record.capture.kind 406 ); 407 const tag = ( 408 template: NonNullable<ReturnType<typeof inspectLocalTemplate>>, 409 key: string 410 ) => template.tags.find((value) => value[0] === key)?.[1]; 411 if ( 412 !witness || 413 witness.family !== 'public_operation' || 414 !witness.artifact || 415 !base || 416 base.family !== 'public_operation' || 417 !oldTemplate || 418 !nextTemplate || 419 JSON.stringify(base.source) !== JSON.stringify(witness.source) || 420 JSON.stringify(base.capture) !== JSON.stringify(witness.capture) || 421 JSON.stringify(base.artifact) !== JSON.stringify(witness.artifact) || 422 (nextTemplate.kind === 5 423 ? record.family !== 'public_operation' || 424 record.source.type !== 'public_head' || 425 record.source.wire !== witness.artifact.wire || 426 JSON.stringify(nextTemplate.tags) !== 427 JSON.stringify([ 428 ['e', witness.artifact.eventId], 429 ['a', `30402:${scope.owner}:${tag(oldTemplate, 'd')}`], 430 ['k', '30402'] 431 ]) || 432 nextTemplate.content !== '' 433 : tag(oldTemplate, 'd') !== tag(nextTemplate, 'd') || 434 tag(oldTemplate, 'published_at') !== 435 tag(nextTemplate, 'published_at')) || 436 nextTemplate.created_at <= oldTemplate.created_at || 437 rows.some((row) => { 438 if ( 439 row.record.family !== 'public_operation' || 440 row.record.id === base.id 441 ) 442 return false; 443 const other = inspectLocalTemplate( 444 row.record.capture.wire, 445 scope.owner, 446 row.record.capture.kind 447 ); 448 return ( 449 !!other && 450 (other.kind === 5 451 ? other.tags.some( 452 (value) => 453 (value[0] === 'e' && 454 value[1] === witness.artifact!.eventId) || 455 (value[0] === 'a' && 456 value[1] === 457 `30402:${scope.owner}:${tag(oldTemplate, 'd')}`) 458 ) && other.created_at >= oldTemplate.created_at 459 : tag(other, 'd') === tag(oldTemplate, 'd') && 460 other.created_at >= oldTemplate.created_at) 461 ); 462 }) 463 ) { 464 refuse('conflict'); 465 return; 466 } 467 } 468 const source = 469 record.family === 'public_operation' ? record.source : undefined; 470 const previousDraft = rows.find( 471 (row) => 472 row.record.family === 'public_draft' && 473 row.record.id === draft.expected.id 474 ); 475 if ( 476 !source || 477 (source.type !== 'draft' && 478 !( 479 source.type === 'public_head' && 480 record.family === 'public_operation' && 481 record.capture.kind === 5 && 482 draft.revisionBase 483 )) || 484 draft.expected.owner !== scope.owner || 485 (source.type === 'draft' && 486 (source.id !== draft.expected.id || 487 source.revision !== draft.expected.revision)) || 488 !previousDraft || 489 JSON.stringify(previousDraft.record) !== 490 JSON.stringify(draft.expected) || 491 !draft.draftCurrent() 492 ) { 493 refuse('conflict'); 494 return; 495 } 496 } 497 const operations = rows.filter( 498 (row) => row.record.family !== 'public_draft' 499 ); 500 if ( 501 operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations || 502 operations.reduce((sum, row) => sum + row.bytes, bytes) > 503 LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes 504 ) { 505 refuse('capacity'); 506 return; 507 } 508 if (draft && (!draft.current() || !draft.draftCurrent())) { 509 refuse('conflict'); 510 return; 511 } 512 active.objectStore(store).put({ owner: scope.owner, id, wire }); 513 return { ok: true, value: { state: 'created', record: handle } }; 514 }); 515 } 516 export function inspectPublicStorage( 517 repository: PublicQuotaRepository 518 ): Promise<PublicQuotaResult<PublicInventory>> { 519 const scope = scopeOf(repository); 520 if (!scope) return Promise.resolve(failed('invalid_scope')); 521 return transaction(scope, 'readonly', (rows) => { 522 const handle = Object.freeze({}) as PublicInventory; 523 inventories.set(handle, { repository, rows }); 524 return { ok: true, value: handle }; 525 }); 526 } 527 export function publicInventorySnapshot( 528 repository: PublicQuotaRepository, 529 handle: PublicInventory 530 ): 531 | Readonly<{ rows: readonly PublicInventoryRow[]; consequences: string }> 532 | undefined { 533 const inventory = inventories.get(handle); 534 return scopeOf(repository) && inventory?.repository === repository 535 ? { 536 rows: inventory.rows.map((row) => 537 publicInventoryRow(row.record, row.bytes) 538 ), 539 consequences: PUBLIC_CLEANUP_CONSEQUENCES 540 } 541 : undefined; 542 } 543 export function reviewPublicCleanup( 544 repository: PublicQuotaRepository, 545 handle: PublicInventory, 546 selection: unknown 547 ): PublicQuotaResult<PublicCleanup> { 548 const inventory = inventories.get(handle); 549 if (!scopeOf(repository) || inventory?.repository !== repository) 550 return failed('invalid_scope'); 551 try { 552 if (!Array.isArray(selection)) return failed('invalid_selection'); 553 const length = selection.length; 554 if ( 555 !Number.isSafeInteger(length) || 556 length <= 0 || 557 length > 558 LOCAL_PERSISTENCE_BUDGETS.publicDrafts + 559 LOCAL_PERSISTENCE_BUDGETS.publicOperations 560 ) 561 return failed('invalid_selection'); 562 let selected = Array.from<string>([]); 563 for (let index = 0; index < length; index++) { 564 const key: unknown = selection[index]; 565 if (typeof key !== 'string' || selected.includes(key)) 566 return failed('invalid_selection'); 567 const row = inventory.rows.find( 568 (row) => publicInventoryRow(row.record, row.bytes).key === key 569 ); 570 if (!row) return failed('invalid_selection'); 571 if (publicInventoryRow(row.record, row.bytes).state !== 'settled') 572 return failed('protected'); 573 selected = selected.concat(key); 574 } 575 if (!scopeOf(repository)) return failed('invalid_scope'); 576 const token = Object.freeze({}) as PublicCleanup; 577 cleanups.set(token, { inventory, selected }); 578 return { ok: true, value: token }; 579 } catch { 580 return failed('invalid_selection'); 581 } 582 } 583 export function publicCleanupSnapshot( 584 repository: PublicQuotaRepository, 585 handle: PublicCleanup 586 ): 587 | Readonly<{ 588 selected: readonly PublicInventoryRow[]; 589 logicalBytesRemoved: number; 590 consequences: string; 591 }> 592 | undefined { 593 const cleanup = cleanups.get(handle); 594 if (!scopeOf(repository) || cleanup?.inventory.repository !== repository) 595 return undefined; 596 const selected = cleanup.inventory.rows 597 .map((row) => publicInventoryRow(row.record, row.bytes)) 598 .filter((row) => cleanup.selected.includes(row.key)); 599 return { 600 selected, 601 logicalBytesRemoved: selected.reduce( 602 (sum, row) => sum + row.logicalBytes, 603 0 604 ), 605 consequences: PUBLIC_CLEANUP_CONSEQUENCES 606 }; 607 } 608 export function commitPublicCleanup( 609 repository: PublicQuotaRepository, 610 handle: PublicCleanup, 611 signal?: AbortSignal 612 ): Promise<PublicQuotaResult<readonly string[]>> { 613 const cleanup = cleanups.get(handle), 614 scope = scopeOf(repository); 615 if (!scope || cleanup?.inventory.repository !== repository) 616 return Promise.resolve(failed('invalid_scope')); 617 return transaction( 618 scope, 619 'readwrite', 620 (rows, active, refuse) => { 621 const before = cleanup.inventory.rows; 622 if ( 623 rows.length !== before.length || 624 rows.some( 625 (row, i) => 626 row.store !== before[i].store || 627 row.record.id !== before[i].record.id || 628 row.wire !== before[i].wire 629 ) 630 ) { 631 refuse('conflict'); 632 return; 633 } 634 const selected = rows.filter((row) => 635 cleanup.selected.includes(publicInventoryRow(row.record, row.bytes).key) 636 ); 637 if ( 638 selected.length !== cleanup.selected.length || 639 selected.some( 640 (row) => publicInventoryRow(row.record, row.bytes).state !== 'settled' 641 ) 642 ) { 643 refuse('protected'); 644 return; 645 } 646 for (const row of selected) 647 active.objectStore(row.store).delete([scope.owner, row.record.id]); 648 return { ok: true, value: Array.from(cleanup.selected) }; 649 }, 650 signal 651 ); 652 } 653 654 // No signer/network await exists inside this transaction. It consumes only a 655 // genuine immutable typed transition captured before storage acquisition. 656 // Exact owner-scoped actual stored preference, not a caller's structural row. 657 // Read is bounded by the same complete quota/codec scan and transaction ack. 658 export function loadPreferenceOperation( 659 repository: PublicQuotaRepository, 660 expectedId: unknown 661 ): Promise<PublicQuotaResult<PublicRecordHandle>> { 662 const scope = scopeOf(repository), 663 id = canonicalLocalId(expectedId); 664 if (!scope) return Promise.resolve(failed('invalid_scope')); 665 if (!id) return Promise.resolve(failed('invalid_record')); 666 return transaction(scope, 'readonly', (rows) => { 667 const row = rows.find( 668 (row) => row.store === 'preference_operations' && row.record.id === id 669 ); 670 if (!row) return failed('invalid_record'); 671 const decoded = decodePublicRecord(row.wire, scope.owner, id); 672 return decoded.ok ? decoded : failed('corrupt_record'); 673 }); 674 } 675 export function commitPublicOperationTransition( 676 repository: PublicQuotaRepository, 677 handle: PublicOperationTransition 678 ): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> { 679 const scope = scopeOf(repository); 680 if (!scope) return Promise.resolve(failed('invalid_scope')); 681 const identity = publicTransitionIdentity(handle); 682 const command = 683 identity && publicTransitionSnapshot(handle, scope.owner, identity.id); 684 if (!command) return Promise.resolve(failed('invalid_record')); 685 const store: Store = 686 command.family === 'public_operation' 687 ? 'public_operations' 688 : 'preference_operations'; 689 return transaction(scope, 'readwrite', (rows, active, refuse) => { 690 const previous = rows.find( 691 (row) => row.store === store && row.record.id === command.id 692 ); 693 const decision = decideFrozenTransition( 694 previous?.wire, 695 command.baseWire, 696 command.nextWire 697 ); 698 if (decision === 'conflict') { 699 refuse('conflict'); 700 return; 701 } 702 if (decision === 'committed') 703 return { 704 ok: true, 705 value: { id: command.id, revision: command.revision } 706 }; 707 const operations = rows.filter( 708 (row) => row.record.family !== 'public_draft' 709 ); 710 const bytes = 711 operations.reduce((sum, row) => sum + row.bytes, 0) - 712 (previous?.bytes ?? 0) + 713 new TextEncoder().encode(command.nextWire).length; 714 if (bytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes) { 715 refuse('capacity'); 716 return; 717 } 718 active 719 .objectStore(store) 720 .put({ owner: scope.owner, id: command.id, wire: command.nextWire }); 721 return { ok: true, value: { id: command.id, revision: command.revision } }; 722 }); 723 } 724 export async function observePublicOperationTransition( 725 repository: PublicQuotaRepository, 726 handle: PublicOperationTransition 727 ): Promise< 728 | Readonly<{ state: 'committed'; id: string; revision: number }> 729 | Readonly<{ state: 'base_observed' | 'conflict' | 'unavailable' }> 730 > { 731 const scope = scopeOf(repository), 732 identity = publicTransitionIdentity(handle); 733 const command = 734 scope && 735 identity && 736 publicTransitionSnapshot(handle, scope.owner, identity.id); 737 if (!scope || !command) return { state: 'unavailable' }; 738 const store: Store = 739 command.family === 'public_operation' 740 ? 'public_operations' 741 : 'preference_operations'; 742 const read = await transaction(scope, 'readonly', (rows) => ({ 743 ok: true, 744 value: decideFrozenTransition( 745 rows.find((row) => row.store === store && row.record.id === command.id) 746 ?.wire, 747 command.baseWire, 748 command.nextWire 749 ) 750 })); 751 if (!read.ok || !scopeOf(repository)) return { state: 'unavailable' }; 752 return read.value === 'committed' 753 ? { state: 'committed', id: command.id, revision: command.revision } 754 : { state: read.value }; 755 }