@mistriwork/mistri 1.0.0-rc.52 → 1.0.0-rc.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/docs/status.md +3 -3
  4. package/dist/embed/react/headless.js +1 -1
  5. package/dist/embed/react/index.js +1 -1
  6. package/dist/server/app/appSearchRuntime.d.ts +9 -0
  7. package/dist/server/app/appSearchRuntime.js +21 -3
  8. package/dist/server/cli/apps.d.ts +2 -0
  9. package/dist/server/cli/apps.js +14 -0
  10. package/dist/server/cli/mistriMain.js +13 -1
  11. package/dist/server/cli/reindex.js +15 -2
  12. package/dist/server/stores/commandStores.d.ts +6 -1
  13. package/dist/server/stores/commandStores.js +2 -1
  14. package/dist/server/tenant/tenantAdministration.js +2 -1
  15. package/dist/server/tenant/tenantAuthenticatedHttp.js +3 -1
  16. package/dist/server/tenant/tenantBackstopOwner.d.ts +20 -0
  17. package/dist/server/tenant/tenantBackstopOwner.js +37 -0
  18. package/dist/server/tenant/tenantConnections.d.ts +23 -2
  19. package/dist/server/tenant/tenantConnections.js +39 -3
  20. package/dist/server/tenant/tenantEnrollment.d.ts +8 -0
  21. package/dist/server/tenant/tenantEnrollment.js +40 -4
  22. package/dist/server/tenant/tenantLive.d.ts +6 -0
  23. package/dist/server/tenant/tenantLive.js +18 -1
  24. package/dist/server/tenant/tenantLocalAccess.js +16 -2
  25. package/dist/server/tenant/tenantNames.d.ts +1 -1
  26. package/dist/server/tenant/tenantPostgresCatalog.d.ts +14 -0
  27. package/dist/server/tenant/tenantPostgresCatalog.js +45 -0
  28. package/dist/server/tenant/tenantReadSource.d.ts +4 -187
  29. package/dist/server/tenant/tenantReadSource.js +110 -693
  30. package/dist/server/tenant/tenantReadSourceShared.d.ts +213 -0
  31. package/dist/server/tenant/tenantReadSourceShared.js +176 -0
  32. package/dist/server/tenant/tenantReadSourceSqlite.d.ts +6 -0
  33. package/dist/server/tenant/tenantReadSourceSqlite.js +498 -0
  34. package/dist/server/tenant/tenantSearch.d.ts +2 -30
  35. package/dist/server/tenant/tenantSearch.js +17 -2
  36. package/dist/server/tenant/tenantStartup.js +13 -2
  37. package/dist/server/tenant/tenantSupportOperations.js +2 -1
  38. package/dist/server/tenant/tenantValidationRecord.js +2 -0
  39. package/dist/server/tenant/tenantWriteSource.d.ts +8 -1
  40. package/dist/server/tenant/tenantWriteSource.js +79 -14
  41. package/dist/ssr/render.js +1 -1
  42. package/package.json +4 -4
@@ -1,6 +1,6 @@
1
1
  import { type TenantOwnershipSnapshot } from './tenantOwnership.js';
2
2
  import { type TenantStoreBinding } from './tenantStore.js';
3
- import { type TenantWriteAudit } from './tenantWriteKindContract.js';
3
+ import { type TenantWriteAudit, type TenantWriteEvidence, type TenantWriteKind } from './tenantWriteKindContract.js';
4
4
  import { type TenantWriteMethods } from './tenantWriteKinds.js';
5
5
  import type { RecordHistoryBinding } from '../../adapters/history/recordHistory.js';
6
6
  import { type InboxMark, type NoticeBinding } from '../../adapters/inbox/inbox.js';
@@ -51,6 +51,13 @@ export declare function observeTenantCommits(owner: {
51
51
  readonly id: string;
52
52
  };
53
53
  }, observer: CommitObserver): () => void;
54
+ /**
55
+ * The tenant the pinned policy reads for a write under the row-security backstop: the journal's (a member, a link,
56
+ * an intake, support, service all name one), the platform-tenant kind's named tenant (its scope narrows every
57
+ * tenant table to it), and undefined for the platform realm's own command, which runs on the owner's writer.
58
+ * Without a backstop the engine ignores it.
59
+ */
60
+ export declare function backstopTenantOf<Evidence extends TenantWriteEvidence>(kind: TenantWriteKind<Evidence, object>, owner: TenantStoreBinding, evidence: Evidence): string | undefined;
54
61
  export declare function captureTenantWriteSource(input: TenantWriteSource): TenantWriteSource;
55
62
  /** Explicit private writable acquisition. An empty initial verified transaction
56
63
  * pins and attests the actual writer before publication. It does not migrate or
@@ -6,7 +6,7 @@ import { isPoolBusy } from '@mistriwork/engine/adapters/poolMetrics.js';
6
6
  import { renamedWriteAhead, withWriteAhead, writeAhead } from '@mistriwork/engine/adapters/writeAhead.js';
7
7
  import { commandsOf } from '../stores/commandStores.js';
8
8
  import { cachedStatement, SqliteAdapter } from '@mistriwork/engine/adapters/sqlite.js';
9
- import { tenantAdapter } from './tenantConnections.js';
9
+ import { tenantAdapter, tenantBackstop } from './tenantConnections.js';
10
10
  import { assertSqliteCommandJournal, COMMAND_JOURNAL_TABLES, CommandTransactionFailure, } from '../../adapters/commands/commandJournal.js';
11
11
  import { q as postgresJournalTable } from '../../adapters/commands/postgresCommandJournalSchema.js';
12
12
  import { readSqliteReadCatalog, readSqliteScopeCatalog, } from '@mistriwork/engine/adapters/scoped/sqliteScopeCatalog.js';
@@ -23,7 +23,7 @@ import { TenantWriteFailure, tenantWriteFailed, } from './tenantWriteKindContrac
23
23
  import { tenantWriteMethods } from './tenantWriteKinds.js';
24
24
  import { WriterRetargeted, writerLifecycle } from './tenantWriterLifecycle.js';
25
25
  import { bindTenantRecordHistoryStore } from './tenantRecordHistoryStore.js';
26
- import { bindTenantLive, unbindTenantLive } from './tenantLive.js';
26
+ import { bindTenantLive, shareTenantLive, unbindTenantLive } from './tenantLive.js';
27
27
  import { appStoresOf } from '../stores/appStores.js';
28
28
  import { assertInboxMark } from '../../adapters/inbox/inbox.js';
29
29
  import { physicalRowScope } from './tenantReadScope.js';
@@ -176,6 +176,20 @@ function recording(records, wrote, owned) {
176
176
  });
177
177
  }
178
178
  const sources = new WeakSet();
179
+ /**
180
+ * The tenant the pinned policy reads for a write under the row-security backstop: the journal's (a member, a link,
181
+ * an intake, support, service all name one), the platform-tenant kind's named tenant (its scope narrows every
182
+ * tenant table to it), and undefined for the platform realm's own command, which runs on the owner's writer.
183
+ * Without a backstop the engine ignores it.
184
+ */
185
+ export function backstopTenantOf(kind, owner, evidence) {
186
+ const journal = kind.journalOwner(owner, evidence);
187
+ if (!('realm' in journal))
188
+ return journal.tenantId;
189
+ if (kind.realm === 'platform-tenant')
190
+ return evidence.tenantId;
191
+ return undefined;
192
+ }
179
193
  export function captureTenantWriteSource(input) {
180
194
  if (!sources.has(input))
181
195
  throw new TenantWriteFailure('not_applied');
@@ -604,7 +618,7 @@ export async function openSqliteTenantWriteSource(existingPath, ownership, store
604
618
  * scope catalog did not already pin before comparing.
605
619
  */
606
620
  export async function openPostgresTenantWriteSource(url, ownership, store, now = Date.now, audit, history, notices, branding = false, readAudit = false) {
607
- let adapter;
621
+ let adapter, platformAdapter;
608
622
  try {
609
623
  const owned = captureTenantOwnership(ownership);
610
624
  const owner = captureTenantData(store);
@@ -617,6 +631,10 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
617
631
  !/^postgres(ql)?:\/\//i.test(url))
618
632
  return denyTenant();
619
633
  const locator = postgresTenantLocator(url);
634
+ /* Under the row-security backstop (tenantConnections.ts) this writer runs as the runtime role, which the pinned
635
+ policy binds, so every write says its tenant (backstopTenantOf); the platform realm's own commands, whose scope
636
+ crosses tenants by design (composePlatformReadScope), run on a second writer as the owner. */
637
+ const backstop = tenantBackstop(url);
620
638
  const first = (adapter = tenantAdapter(url, 'Private tenant writer'));
621
639
  const physical = new Map(Object.entries(owned.resources));
622
640
  const ids = new Set(physical.values());
@@ -653,7 +671,7 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
653
671
  await assertPostgresTenantStore(client, owner);
654
672
  await assertPostgresTenantUniqueKeys(client, owned);
655
673
  const state = JSON.stringify({
656
- definitions: await attestPostgresTenantRelations(client, owned),
674
+ definitions: await attestPostgresTenantRelations(client, owned, backstop ? { rowSecurity: { role: backstop.role } } : {}),
657
675
  writable: [...ids].filter((id) => catalog.writable.has(id)).sort(),
658
676
  });
659
677
  if (baseline !== undefined && state !== baseline)
@@ -664,7 +682,8 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
664
682
  const verifier = (verify, ahead) => Object.assign(verify, ahead ? { pin, ahead } : { pin });
665
683
  const empty = Object.fromEntries([...ids].map((id) => [id, false]));
666
684
  // As on SQLite: at opening, and again at each reopen after an uncertain write.
667
- const prepare = async (dbAdapter, receipt) => {
685
+ /* `shared`: the owner's writer, which records live changes for the runtime writer's one hub (shareTenantLive). */
686
+ const prepare = async (dbAdapter, receipt, shared = false) => {
668
687
  let committed;
669
688
  await dbAdapter.scopeVerifiedTransaction(empty, verifier(async (client, catalog, describe, epoch) => {
670
689
  await attest(client, catalog, describe, epoch);
@@ -672,7 +691,9 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
672
691
  committed =
673
692
  (await client.query(`SELECT 1 FROM ${postgresJournalTable(COMMAND_JOURNAL_TABLES.receipt)} WHERE id = $1`, [receipt])).rows
674
693
  .length > 0;
675
- }), async () => { });
694
+ }), async () => { },
695
+ // Every tenant table is false here, and the journal and store carry no policy: no tenant to name.
696
+ { tenant: null });
676
697
  if (history)
677
698
  await bindTenantRecordHistoryStore(dbAdapter, history, 'postgres');
678
699
  if (notices)
@@ -681,7 +702,10 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
681
702
  await bindTenantBrandingStore(dbAdapter, 'postgres');
682
703
  if (readAudit)
683
704
  await bindTenantReadAuditStore(dbAdapter);
684
- await bindTenantLive(dbAdapter, owned, url);
705
+ if (shared)
706
+ await shareTenantLive(dbAdapter, owned);
707
+ else
708
+ await bindTenantLive(dbAdapter, owned, url);
685
709
  return committed;
686
710
  };
687
711
  await prepare(first);
@@ -713,11 +737,42 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
713
737
  }
714
738
  },
715
739
  });
740
+ /* The owner's writer, under the backstop only: its own lifecycle, so an uncertain platform write pauses it and
741
+ not the tenants' writer, and the same queue, so shutdown drains both behind every admitted write. */
742
+ let ownerLife;
743
+ if (backstop) {
744
+ const ownerFirst = (platformAdapter = tenantAdapter(url, 'Private tenant platform writer', false, 'owner'));
745
+ await prepare(ownerFirst, undefined, true);
746
+ ownerLife = writerLifecycle({
747
+ owner,
748
+ name: `${owner.appId}'s tenant platform writer (source "${owner.source.id}")`,
749
+ paused: `${owner.appId}/${owner.source.id}/owner`,
750
+ initial: ownerFirst,
751
+ drain: (work) => queue.run('all', work),
752
+ release: (handle) => unbindTenantLive(handle, owned),
753
+ reopen: async (receipt) => {
754
+ const next = tenantAdapter(url, 'Private tenant platform writer', false, 'owner');
755
+ standing = undefined;
756
+ try {
757
+ return { handle: next, committed: await prepare(next, receipt, true) };
758
+ }
759
+ catch (error) {
760
+ await next.close().catch(() => { });
761
+ throw error;
762
+ }
763
+ },
764
+ });
765
+ }
716
766
  const closing = life.closing;
717
- const close = life.close;
767
+ /* One promise for every caller, as the lifecycle's own close is: a second close waits on the first. */
768
+ const both = ownerLife;
769
+ let closingBoth;
770
+ const close = both ? () => (closingBoth ??= Promise.all([life.close(), both.close()]).then(() => { })) : life.close;
718
771
  const transaction = (kind, command, evidence, rows, run, assertActive, operation, footprint) => {
719
772
  let input;
720
773
  let tables;
774
+ let tenant;
775
+ let lane;
721
776
  try {
722
777
  if (closing())
723
778
  return paused();
@@ -725,19 +780,25 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
725
780
  return denyTenant();
726
781
  input = kind.capture(evidence, rows, owned);
727
782
  tables = footprintOf(owned, command, footprint);
783
+ tenant = backstopTenantOf(kind, owner, input.evidence);
784
+ lane = tenant === undefined && ownerLife ? ownerLife : life;
785
+ if (lane.closing())
786
+ return paused();
728
787
  }
729
788
  catch (error) {
730
789
  return Promise.reject(tenantWriteFailed('not_applied', error));
731
790
  }
791
+ // Left out where undefined: the owner's writer bypasses the policy, and without a backstop nothing reads it.
792
+ const scoped = tenant !== undefined ? { tenant } : {};
732
793
  return queue.run([], async () => {
733
- const dbAdapter = life.handle();
794
+ const dbAdapter = lane.handle();
734
795
  let receipt;
735
796
  let fenced;
736
797
  let entered = false, attested = false, completed = false, attempted = false, moved = false, started = false;
737
798
  // Shape validation happens inside the classified failure boundary.
738
799
  let lastTime = input.evidence?.verifiedAt;
739
800
  const live = () => {
740
- if (closing())
801
+ if (lane.closing())
741
802
  return paused();
742
803
  if (assertActive)
743
804
  synchronous(assertActive());
@@ -747,7 +808,7 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
747
808
  // The source's clock can synchronously retire the request owner.
748
809
  if (assertActive)
749
810
  synchronous(assertActive());
750
- if (closing())
811
+ if (lane.closing())
751
812
  return paused();
752
813
  if (typeof instant !== 'number' ||
753
814
  !Number.isSafeInteger(instant) ||
@@ -954,8 +1015,8 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
954
1015
  // What the transaction opens with, told in the App's tables, said in this source's (writeAhead.ts).
955
1016
  const ahead = renamedWriteAhead(writeAhead(), (table) => physical.get(table));
956
1017
  const result = await withWriteAhead(ahead, () => command
957
- ? commandsOf(dbAdapter).scopeVerifiedCommandTransaction(physicalScope, verify, kind.journalOwner(owner, input.evidence), work, physicalBound)
958
- : dbAdapter.scopeVerifiedTransaction(physicalScope, verify, (records) => work(records)));
1018
+ ? commandsOf(dbAdapter).scopeVerifiedCommandTransaction(physicalScope, verify, kind.journalOwner(owner, input.evidence), work, physicalBound, scoped)
1019
+ : dbAdapter.scopeVerifiedTransaction(physicalScope, verify, (records) => work(records), scoped));
959
1020
  completed = true;
960
1021
  committed(owner, wrote);
961
1022
  // A late lifetime refusal after confirmed COMMIT is never not_applied.
@@ -972,7 +1033,7 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
972
1033
  if (error instanceof TransactionOutcomeUnknown ||
973
1034
  (error instanceof CommandTransactionFailure && error.outcome === 'unknown') ||
974
1035
  (attempted && !entered && !refusedCheckout(error)))
975
- life.pause(receipt);
1036
+ lane.pause(receipt);
976
1037
  if (moved && !completed && kind.moved)
977
1038
  throw kind.moved();
978
1039
  throw tenantWriteFailed(unknown ? 'unknown' : 'not_applied', error);
@@ -1046,6 +1107,10 @@ export async function openPostgresTenantWriteSource(url, ownership, store, now =
1046
1107
  }
1047
1108
  catch (error) {
1048
1109
  try {
1110
+ // The owner's writer opens after the runtime's has bound live sync: let that go with it.
1111
+ if (platformAdapter && adapter)
1112
+ await unbindTenantLive(adapter, ownership);
1113
+ await platformAdapter?.close();
1049
1114
  await adapter?.close();
1050
1115
  }
1051
1116
  catch {