@mistriwork/mistri 1.0.0-rc.51 → 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.
- package/CHANGELOG.md +16 -0
- package/README.md +1 -1
- package/dist/docs/status.md +3 -3
- package/dist/embed/react/headless.js +1 -1
- package/dist/embed/react/index.js +1 -1
- package/dist/server/app/appSearchRuntime.d.ts +9 -0
- package/dist/server/app/appSearchRuntime.js +21 -3
- package/dist/server/cli/apps.d.ts +2 -0
- package/dist/server/cli/apps.js +14 -0
- package/dist/server/cli/mistriMain.js +13 -1
- package/dist/server/cli/reindex.js +15 -2
- package/dist/server/stores/commandStores.d.ts +6 -1
- package/dist/server/stores/commandStores.js +2 -1
- package/dist/server/tenant/tenantAdministration.js +2 -1
- package/dist/server/tenant/tenantAuthenticatedHttp.js +3 -1
- package/dist/server/tenant/tenantBackstopOwner.d.ts +20 -0
- package/dist/server/tenant/tenantBackstopOwner.js +37 -0
- package/dist/server/tenant/tenantConnections.d.ts +23 -2
- package/dist/server/tenant/tenantConnections.js +39 -3
- package/dist/server/tenant/tenantEnrollment.d.ts +8 -0
- package/dist/server/tenant/tenantEnrollment.js +40 -4
- package/dist/server/tenant/tenantLive.d.ts +6 -0
- package/dist/server/tenant/tenantLive.js +18 -1
- package/dist/server/tenant/tenantLocalAccess.js +16 -2
- package/dist/server/tenant/tenantNames.d.ts +1 -1
- package/dist/server/tenant/tenantPostgresCatalog.d.ts +30 -1
- package/dist/server/tenant/tenantPostgresCatalog.js +138 -3
- package/dist/server/tenant/tenantReadSource.d.ts +4 -187
- package/dist/server/tenant/tenantReadSource.js +110 -693
- package/dist/server/tenant/tenantReadSourceShared.d.ts +213 -0
- package/dist/server/tenant/tenantReadSourceShared.js +176 -0
- package/dist/server/tenant/tenantReadSourceSqlite.d.ts +6 -0
- package/dist/server/tenant/tenantReadSourceSqlite.js +498 -0
- package/dist/server/tenant/tenantSearch.d.ts +2 -30
- package/dist/server/tenant/tenantSearch.js +17 -2
- package/dist/server/tenant/tenantStartup.js +13 -2
- package/dist/server/tenant/tenantSupportOperations.js +2 -1
- package/dist/server/tenant/tenantValidationRecord.js +2 -0
- package/dist/server/tenant/tenantWriteSource.d.ts +8 -1
- package/dist/server/tenant/tenantWriteSource.js +79 -14
- package/package.json +4 -4
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
// The SQLite tenant read source: one file, opened read-only beside the App's writer, answering the same interface as
|
|
2
|
+
// the PostgreSQL source (tenantReadSourceShared.ts) for development and the single-file deployments.
|
|
3
|
+
import { sandboxRows, sandboxStorePresent, sqliteSandboxSession } from './tenantSandboxStore.js';
|
|
4
|
+
import { realpathSync, statSync } from 'node:fs';
|
|
5
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
6
|
+
import { ANSI_STYLE, Serial } from '@mistriwork/engine/adapters/adapter.js';
|
|
7
|
+
import { createScopedReads } from '@mistriwork/engine/adapters/scoped/scopedReads.js';
|
|
8
|
+
import { schemaFingerprint, sqliteParams, toJsonSafe, withBytes } from '@mistriwork/engine/adapters/sqlite.js';
|
|
9
|
+
import { readSqliteReadCatalog } from '@mistriwork/engine/adapters/scoped/sqliteScopeCatalog.js';
|
|
10
|
+
import { mapScopeCatalog } from '@mistriwork/engine/shared/scopeCatalog.js';
|
|
11
|
+
import { snapshotRowScope } from '@mistriwork/engine/shared/rowScope.js';
|
|
12
|
+
import { mapAppScopedReads } from '../app/appResources.js';
|
|
13
|
+
import { captureTenantData, denyTenant, denyTenantFor, TenantContextError } from '@mistriwork/engine/server/evidence.js';
|
|
14
|
+
import { parseTenantSelector } from './tenantMembership.js';
|
|
15
|
+
import { assertTenantOwnership, captureTenantOwnership } from './tenantOwnership.js';
|
|
16
|
+
import { assertServiceReadCurrent, captureServiceEvidence, composeServiceScope } from './tenantServiceModel.js';
|
|
17
|
+
import { AppAccessDenied } from '../app/appAccess.js';
|
|
18
|
+
import { composePlatformReadScope, composePublicReadScope, composeTenantReadScope, physicalRowScope } from './tenantReadScope.js';
|
|
19
|
+
import { assertPublicResolved, capturePublicEvidence, capturePublicLookup, intakeVisitor, publicLookupOf, publicResolution, publicTenantOf, } from './tenantPublicRead.js';
|
|
20
|
+
import { assertSupportEvidenceObserved, supportAsMember } from './tenantSupportMembership.js';
|
|
21
|
+
import { observeSqliteSupportMembership } from './tenantSupportMembershipSqlite.js';
|
|
22
|
+
import { registerTenantSourceIdentity } from './tenantSourceIdentity.js';
|
|
23
|
+
import { assertSqlitePlatformMembershipSnapshot, assertSqliteTenantMembershipSnapshot, assertSqliteTenantStore, readSqlitePlatformMembershipSnapshot, readSqliteTenantMembershipSnapshot, readSqliteTenantMembershipsSnapshot, } from './tenantStore.js';
|
|
24
|
+
import { captureAddressesLookup, captureIntakeEvidence, captureIntakeLookup, captureIntakeTenantLookup, heldAddress, intakeAddressQuery, intakePlace, intakeTenantOf, tenantAddressQuery, tenantOwnAddress, captureProfileLookup, activeTenantsZone, activeWithColumn, heldProfile, tenantProfileColumnQuery, tenantProfileQuery, } from './tenantIntakeModel.js';
|
|
25
|
+
import { PLATFORM_TENANT_ID } from './tenantPlatform.js';
|
|
26
|
+
import { findSqliteLink, readSqliteLink } from '../../adapters/commands/commandLinks.js';
|
|
27
|
+
import { assertLinkReadCurrent, assertLinkRowCurrent, captureLinkEvidence, captureLinkLookup, composeLinkScope, linkResolution, } from './tenantLinkModel.js';
|
|
28
|
+
import { readSqliteActiveTenants, readSqliteIntakeAnchor } from './tenantStore.js';
|
|
29
|
+
import { dueTimersPlan } from './tenantDueTimers.js';
|
|
30
|
+
import { tenantNamesOf, tenantNamesQuery } from './tenantNames.js';
|
|
31
|
+
import { assertActivityQuery, assertHistoryQuery, } from '../../adapters/history/recordHistory.js';
|
|
32
|
+
import { readSqliteRecordActivity, readSqliteRecordHistory } from '../../adapters/history/sqliteRecordHistory.js';
|
|
33
|
+
import { assertInboxQuery } from '../../adapters/inbox/inbox.js';
|
|
34
|
+
import { assertBrandingLogoQuery, assertBrandingQuery, } from '../../adapters/branding/branding.js';
|
|
35
|
+
import { readSqliteBranding, readSqliteBrandingLogo } from '../../adapters/branding/sqliteBranding.js';
|
|
36
|
+
import { readSqliteInbox, sqliteInboxMail } from '../../adapters/inbox/sqliteInbox.js';
|
|
37
|
+
import { assertEmailSwitchQuery, sandboxLookup, intakeResolution, intakeResolutionByTenant, namesLookup, sources, refusedBefore, readBatch, } from './tenantReadSourceShared.js';
|
|
38
|
+
/** Opens once, read-only. Every operation owns a serialized read snapshot on
|
|
39
|
+
* that exact handle; no registry lookup, request-time migration or writer exists. */
|
|
40
|
+
export function openSqliteTenantReadSource(existingPath, ownership, store, now = Date.now) {
|
|
41
|
+
let opened;
|
|
42
|
+
try {
|
|
43
|
+
const captured = captureTenantOwnership(ownership);
|
|
44
|
+
// Ordinary SQLite catalogs omit engine internals. Apply exactly that
|
|
45
|
+
// normalization to both sides, never private/business dependency filtering.
|
|
46
|
+
const owned = captureTenantOwnership({
|
|
47
|
+
...captured,
|
|
48
|
+
physicalSchema: mapScopeCatalog(captured.physicalSchema, new Map(captured.physicalSchema.tables.filter((table) => !/^sqlite_/i.test(table.id)).map((table) => [table.id, table.id]))),
|
|
49
|
+
});
|
|
50
|
+
const owner = captureTenantData(store);
|
|
51
|
+
if (owner.appId !== owned.appId ||
|
|
52
|
+
owner.source.id !== owned.source.id ||
|
|
53
|
+
owner.source.connection !== owned.source.connection ||
|
|
54
|
+
typeof now !== 'function' ||
|
|
55
|
+
typeof existingPath !== 'string' ||
|
|
56
|
+
!statSync(existingPath).isFile())
|
|
57
|
+
return denyTenant();
|
|
58
|
+
const canonicalPath = realpathSync(existingPath);
|
|
59
|
+
const db = (opened = new DatabaseSync(canonicalPath, { readOnly: true, enableForeignKeyConstraints: true }));
|
|
60
|
+
db.exec('PRAGMA query_only = ON; PRAGMA busy_timeout = 1000');
|
|
61
|
+
const physicalIds = new Map(Object.entries(owned.resources).map(([logical, physical]) => [physical, logical]));
|
|
62
|
+
const logicalIds = new Map(Object.entries(owned.resources));
|
|
63
|
+
const toPhysical = (id) => logicalIds.get(id) ?? denyTenant();
|
|
64
|
+
const toLogical = (id) => physicalIds.get(id) ?? denyTenant();
|
|
65
|
+
const physicalSchema = mapScopeCatalog(owned.physicalSchema, new Map([...physicalIds.keys()].map((id) => [id, id])));
|
|
66
|
+
// A snapshot, so every read's composition with it is kept (tenantReadScope.ts).
|
|
67
|
+
const allTrue = snapshotRowScope(owned.schema, Object.fromEntries([...logicalIds.keys()].map((id) => [id, true])));
|
|
68
|
+
let definitions;
|
|
69
|
+
const attestCatalog = () => {
|
|
70
|
+
const actual = readSqliteReadCatalog(db);
|
|
71
|
+
if ([...physicalIds.keys()].some((id) => !actual.readable.has(id)))
|
|
72
|
+
return denyTenant();
|
|
73
|
+
assertTenantOwnership(owned, { ...owned, physicalSchema: actual.schema });
|
|
74
|
+
// Catalog authority intentionally omits collations. Pin actual mapped DDL
|
|
75
|
+
// too: changing a policy column to NOCASE/RTRIM must not widen its filter.
|
|
76
|
+
const ddl = new Map();
|
|
77
|
+
for (const row of db.prepare("SELECT name, sql FROM main.sqlite_schema WHERE type = 'table'").all()) {
|
|
78
|
+
if (typeof row.name === 'string' && physicalIds.has(row.name)) {
|
|
79
|
+
if (typeof row.sql !== 'string')
|
|
80
|
+
return denyTenant();
|
|
81
|
+
ddl.set(row.name, row.sql);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (ddl.size !== physicalIds.size || (definitions && [...definitions].some(([id, sql]) => ddl.get(id) !== sql)))
|
|
85
|
+
return denyTenant();
|
|
86
|
+
definitions ??= ddl;
|
|
87
|
+
};
|
|
88
|
+
/* A field report measured a whole catalog scan inside every read. Any DDL
|
|
89
|
+
on either schema moves its schema_version, so while the pair is the one
|
|
90
|
+
the last full pass judged, nothing it judged can have changed: the scan
|
|
91
|
+
is skipped. Read first, inside the read transaction, it names the
|
|
92
|
+
snapshot the read sees. A refused pass records nothing, so it refuses
|
|
93
|
+
again on every read until the schema moves back to a passing shape. */
|
|
94
|
+
const fingerprint = schemaFingerprint(db);
|
|
95
|
+
let attested;
|
|
96
|
+
const assertCatalog = () => {
|
|
97
|
+
const seen = fingerprint();
|
|
98
|
+
if (seen === attested)
|
|
99
|
+
return;
|
|
100
|
+
attested = undefined;
|
|
101
|
+
attestCatalog();
|
|
102
|
+
attested = seen;
|
|
103
|
+
};
|
|
104
|
+
// Construction must fail before publishing a capability, and close its
|
|
105
|
+
// owned handle even when either catalog or durable store evidence refuses.
|
|
106
|
+
db.exec('BEGIN');
|
|
107
|
+
assertCatalog();
|
|
108
|
+
assertSqliteTenantStore(db, owner);
|
|
109
|
+
db.exec('COMMIT');
|
|
110
|
+
const queue = new Serial();
|
|
111
|
+
let closing = false;
|
|
112
|
+
let closed;
|
|
113
|
+
const active = () => {
|
|
114
|
+
if (closing)
|
|
115
|
+
denyTenant('This tenant read source has closed.');
|
|
116
|
+
};
|
|
117
|
+
const close = () => {
|
|
118
|
+
if (!closed) {
|
|
119
|
+
closing = true;
|
|
120
|
+
closed = queue.run(async () => {
|
|
121
|
+
try {
|
|
122
|
+
db.close();
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return denyTenant();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return closed;
|
|
130
|
+
};
|
|
131
|
+
const snapshot = async (work) => {
|
|
132
|
+
active();
|
|
133
|
+
if (db.isTransaction)
|
|
134
|
+
return denyTenant();
|
|
135
|
+
db.exec('BEGIN');
|
|
136
|
+
try {
|
|
137
|
+
assertCatalog();
|
|
138
|
+
const result = await work();
|
|
139
|
+
active();
|
|
140
|
+
db.exec('COMMIT');
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
if (db.isTransaction) {
|
|
145
|
+
try {
|
|
146
|
+
db.exec('ROLLBACK');
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
void close().catch(() => { });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
// Snapshot all arguments before the first queue wait. Failures are local to
|
|
155
|
+
// this read; the serialized source still drains subsequent accepted work.
|
|
156
|
+
const invoke = (input, work) => {
|
|
157
|
+
let value;
|
|
158
|
+
try {
|
|
159
|
+
active();
|
|
160
|
+
value = captureTenantData(input);
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
return refusedBefore(error);
|
|
164
|
+
}
|
|
165
|
+
return queue.run(async () => {
|
|
166
|
+
try {
|
|
167
|
+
const result = await snapshot(() => work(value));
|
|
168
|
+
active();
|
|
169
|
+
return result;
|
|
170
|
+
}
|
|
171
|
+
// A refusal inside stays one; a database that failed to answer —
|
|
172
|
+
// busy, gone, a statement that could not run — is a fault.
|
|
173
|
+
catch (error) {
|
|
174
|
+
return denyTenantFor(error);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
};
|
|
178
|
+
const current = (evidence) => {
|
|
179
|
+
assertSqliteTenantMembershipSnapshot(db, owner, evidence, () => {
|
|
180
|
+
const instant = now();
|
|
181
|
+
active();
|
|
182
|
+
return instant;
|
|
183
|
+
});
|
|
184
|
+
// A trusted clock can retire the source synchronously. Never run SQL or
|
|
185
|
+
// return a newly bound reader after that retirement.
|
|
186
|
+
active();
|
|
187
|
+
};
|
|
188
|
+
const currentPlatform = (evidence) => {
|
|
189
|
+
assertSqlitePlatformMembershipSnapshot(db, owner, evidence, () => {
|
|
190
|
+
const instant = now();
|
|
191
|
+
active();
|
|
192
|
+
return instant;
|
|
193
|
+
});
|
|
194
|
+
active();
|
|
195
|
+
};
|
|
196
|
+
/* A support session's fence: the support row itself, observed with its
|
|
197
|
+
parent platform membership, `@platform` and the dealer. An operator inside
|
|
198
|
+
a dealer holds no member membership there, so the member check above would
|
|
199
|
+
refuse it; this runs inside the same snapshot, which `snapshot()` has
|
|
200
|
+
already opened as a transaction. */
|
|
201
|
+
const currentSupport = (evidence) => {
|
|
202
|
+
const instant = now();
|
|
203
|
+
active();
|
|
204
|
+
assertSupportEvidenceObserved(observeSqliteSupportMembership(db, owner, {
|
|
205
|
+
supportId: evidence.supportId,
|
|
206
|
+
accountId: evidence.accountId,
|
|
207
|
+
tenantId: evidence.tenantId,
|
|
208
|
+
at: instant,
|
|
209
|
+
}), evidence, instant);
|
|
210
|
+
active();
|
|
211
|
+
};
|
|
212
|
+
/* A visitor's placement in this snapshot: the address read by the policy's
|
|
213
|
+
column, byte for byte, then both anchors. Never a refusal of its own: null. */
|
|
214
|
+
const resolvePublicIn = (lookup) => {
|
|
215
|
+
const value = capturePublicLookup(lookup, owner), sql = intakeAddressQuery(owned, value.column);
|
|
216
|
+
const tenantId = value.address === null ? value.tenant : publicTenantOf(db.prepare(sql).all(value.address));
|
|
217
|
+
return publicResolution(tenantId, (id) => readSqliteIntakeAnchor(db, owner, id));
|
|
218
|
+
};
|
|
219
|
+
// A service's anchors as this snapshot finds them, against the versions its attempt read.
|
|
220
|
+
const currentService = (evidence) => {
|
|
221
|
+
const found = {
|
|
222
|
+
tenantVersion: readSqliteIntakeAnchor(db, owner, evidence.tenantId),
|
|
223
|
+
platformVersion: readSqliteIntakeAnchor(db, owner, PLATFORM_TENANT_ID),
|
|
224
|
+
};
|
|
225
|
+
const instant = now();
|
|
226
|
+
active();
|
|
227
|
+
assertServiceReadCurrent(evidence, found, instant);
|
|
228
|
+
active();
|
|
229
|
+
};
|
|
230
|
+
// A link's anchors and its row as this snapshot finds them, against the versions its request read.
|
|
231
|
+
const currentLink = (evidence) => {
|
|
232
|
+
const found = {
|
|
233
|
+
tenantVersion: readSqliteIntakeAnchor(db, owner, evidence.tenantId),
|
|
234
|
+
platformVersion: readSqliteIntakeAnchor(db, owner, PLATFORM_TENANT_ID),
|
|
235
|
+
};
|
|
236
|
+
const instant = now();
|
|
237
|
+
active();
|
|
238
|
+
assertLinkReadCurrent(evidence, found, instant);
|
|
239
|
+
assertLinkRowCurrent(readSqliteLink(db, owner.appId, evidence.tenantId, evidence.linkId, instant), evidence);
|
|
240
|
+
active();
|
|
241
|
+
};
|
|
242
|
+
const currentPublic = (evidence) => {
|
|
243
|
+
const value = capturePublicEvidence(evidence, owned);
|
|
244
|
+
const resolved = resolvePublicIn(publicLookupOf(value));
|
|
245
|
+
const instant = now();
|
|
246
|
+
active();
|
|
247
|
+
assertPublicResolved(value, resolved, instant);
|
|
248
|
+
active();
|
|
249
|
+
};
|
|
250
|
+
// One compiled reader per admitted scope. Every call first revalidates the
|
|
251
|
+
// principal it was bound for, tenant or platform, in its own snapshot.
|
|
252
|
+
const scoped = (scope) => {
|
|
253
|
+
const physicalScope = physicalRowScope(scope, toPhysical);
|
|
254
|
+
return mapAppScopedReads(createScopedReads(physicalSchema, physicalScope, ANSI_STYLE, async (sql, hint) => {
|
|
255
|
+
const started = performance.now();
|
|
256
|
+
const statement = db.prepare(sql.text);
|
|
257
|
+
statement.setReadBigInts(true);
|
|
258
|
+
const rows = statement.all(...sqliteParams(sql.params));
|
|
259
|
+
return {
|
|
260
|
+
columns: statement.columns().map((column) => column.name),
|
|
261
|
+
rows: rows.map(hint?.binary ? withBytes : toJsonSafe),
|
|
262
|
+
ms: Math.round(performance.now() - started),
|
|
263
|
+
sql,
|
|
264
|
+
};
|
|
265
|
+
}), { schema: owned.schema, toPhysical, toLogical });
|
|
266
|
+
};
|
|
267
|
+
const bind = (scope, revalidate) => {
|
|
268
|
+
const reads = scoped(scope);
|
|
269
|
+
const run = (args, work) => invoke(args, (capturedArgs) => {
|
|
270
|
+
revalidate();
|
|
271
|
+
return work(...capturedArgs);
|
|
272
|
+
});
|
|
273
|
+
return Object.freeze({
|
|
274
|
+
query: (request) => run([request], reads.query),
|
|
275
|
+
count: (table, filter, limit) => run([table, filter, limit], reads.count),
|
|
276
|
+
runView: (view, offset) => run([view, offset], reads.runView),
|
|
277
|
+
// The bound reaches the statement: never counted past it.
|
|
278
|
+
countView: (view, limit) => run([view, limit], reads.countView),
|
|
279
|
+
runBreakdown: (breakdown, offset) => run([breakdown, offset], reads.runBreakdown),
|
|
280
|
+
countBreakdown: (breakdown, limit) => run([breakdown, limit], reads.countBreakdown),
|
|
281
|
+
// Revalidated and bounded by the tenant's rows as `count` is.
|
|
282
|
+
...(reads.aggregate ? { aggregate: (request) => run([request], reads.aggregate) } : {}),
|
|
283
|
+
});
|
|
284
|
+
};
|
|
285
|
+
/* A batch is one queued snapshot: its reads run inside it, on the handle
|
|
286
|
+
directly, never through the queue it already holds. */
|
|
287
|
+
const batch = (input, open, work) => {
|
|
288
|
+
if (typeof work !== 'function')
|
|
289
|
+
return Promise.reject(new TenantContextError());
|
|
290
|
+
let own;
|
|
291
|
+
return invoke(input, (captured) => readBatch(scoped(open(captured)), active, work, (error) => {
|
|
292
|
+
own = { error };
|
|
293
|
+
})).catch((error) => {
|
|
294
|
+
throw own ? own.error : error;
|
|
295
|
+
});
|
|
296
|
+
};
|
|
297
|
+
// Arguments captured now, as `invoke` captures them; no snapshot is opened.
|
|
298
|
+
const bindLater = (input, make) => {
|
|
299
|
+
try {
|
|
300
|
+
active();
|
|
301
|
+
return Promise.resolve(make(captureTenantData(input)));
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
return refusedBefore(error);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
const source = Object.freeze({
|
|
308
|
+
ownership: owned,
|
|
309
|
+
readMembership: (lookup) => invoke(lookup, (query) => readSqliteTenantMembershipSnapshot(db, owner, query)),
|
|
310
|
+
readMemberships: (lookup) => invoke(lookup, (query) => readSqliteTenantMembershipsSnapshot(db, owner, query, () => {
|
|
311
|
+
const instant = now();
|
|
312
|
+
active();
|
|
313
|
+
return instant;
|
|
314
|
+
})),
|
|
315
|
+
assertCurrent: (evidence) => invoke(evidence, current),
|
|
316
|
+
scopeReads: (evidence, rows) => invoke({ evidence, rows }, (captured) => {
|
|
317
|
+
current(captured.evidence);
|
|
318
|
+
return bind(composeTenantReadScope(owned, captured.evidence, captured.rows, allTrue), () => current(captured.evidence));
|
|
319
|
+
}),
|
|
320
|
+
bindReads: (evidence, rows) => bindLater({ evidence, rows }, (captured) => bind(composeTenantReadScope(owned, captured.evidence, captured.rows, allTrue), () => current(captured.evidence))),
|
|
321
|
+
withReads: (evidence, rows, work) => batch({ evidence, rows }, (captured) => {
|
|
322
|
+
current(captured.evidence);
|
|
323
|
+
return composeTenantReadScope(owned, captured.evidence, captured.rows, allTrue);
|
|
324
|
+
}, work),
|
|
325
|
+
/* One handle, read in turn: every snapshot is already this one connection's, so there is nothing to share. */
|
|
326
|
+
together: async (_evidence, work) => {
|
|
327
|
+
if (typeof work !== 'function')
|
|
328
|
+
return Promise.reject(new TenantContextError());
|
|
329
|
+
active();
|
|
330
|
+
return work();
|
|
331
|
+
},
|
|
332
|
+
togetherFenced: async (_evidence, work) => {
|
|
333
|
+
if (typeof work !== 'function')
|
|
334
|
+
return Promise.reject(new TenantContextError());
|
|
335
|
+
active();
|
|
336
|
+
return { value: await work(), fenced: false };
|
|
337
|
+
},
|
|
338
|
+
readPlatformMembership: (lookup) => invoke(lookup, (query) => readSqlitePlatformMembershipSnapshot(db, owner, query)),
|
|
339
|
+
assertPlatformCurrent: (evidence) => invoke(evidence, currentPlatform),
|
|
340
|
+
// The source recomposes the platform scope itself: whatever a runtime
|
|
341
|
+
// passes, a table the platform policy does not name stays denied.
|
|
342
|
+
scopePlatformReads: (evidence, rows) => invoke({ evidence, rows }, (captured) => {
|
|
343
|
+
currentPlatform(captured.evidence);
|
|
344
|
+
return bind(composePlatformReadScope(owned, captured.evidence, captured.rows), () => currentPlatform(captured.evidence));
|
|
345
|
+
}),
|
|
346
|
+
bindPlatformReads: (evidence, rows) => bindLater({ evidence, rows }, (captured) => bind(composePlatformReadScope(owned, captured.evidence, captured.rows), () => currentPlatform(captured.evidence))),
|
|
347
|
+
withPlatformReads: (evidence, rows, work) => batch({ evidence, rows }, (captured) => {
|
|
348
|
+
currentPlatform(captured.evidence);
|
|
349
|
+
return composePlatformReadScope(owned, captured.evidence, captured.rows);
|
|
350
|
+
}, work),
|
|
351
|
+
assertSupportCurrent: (evidence) => invoke(evidence, currentSupport),
|
|
352
|
+
/* The source recomposes the dealer's scope itself, as above — and through
|
|
353
|
+
composeTenantReadScope on a member view of the support evidence, not a
|
|
354
|
+
rule of its own. One policy rule then governs a dealer's rows for its
|
|
355
|
+
own members and for an operator inside it; a second rule could disagree
|
|
356
|
+
with the first, and that disagreement would show up as a session
|
|
357
|
+
reading rows the policy meant to withhold rather than as a failing
|
|
358
|
+
test. The fence is still the support row (currentSupport). */
|
|
359
|
+
scopeSupportReads: (evidence, rows) => invoke({ evidence, rows }, (captured) => {
|
|
360
|
+
currentSupport(captured.evidence);
|
|
361
|
+
return bind(composeTenantReadScope(owned, supportAsMember(captured.evidence), captured.rows, allTrue), () => currentSupport(captured.evidence));
|
|
362
|
+
}),
|
|
363
|
+
resolvePublic: (lookup) => invoke(lookup, resolvePublicIn),
|
|
364
|
+
assertPublicCurrent: (evidence) => invoke(evidence, currentPublic),
|
|
365
|
+
// The source recomposes the visitor's scope itself: the tenant predicate is never the caller's.
|
|
366
|
+
bindPublicReads: (evidence, rows) => bindLater({ evidence, rows }, (captured) => bind(composePublicReadScope(owned, captured.evidence, captured.rows), () => currentPublic(captured.evidence))),
|
|
367
|
+
bindIntakeReads: (evidence, rows) => bindLater({ evidence, rows }, (captured) => {
|
|
368
|
+
const value = captureIntakeEvidence(captured.evidence, owned);
|
|
369
|
+
if (intakePlace(value) !== 'tenant')
|
|
370
|
+
throw new AppAccessDenied();
|
|
371
|
+
const visitor = intakeVisitor(value);
|
|
372
|
+
return bind(composePublicReadScope(owned, visitor, captured.rows), () => currentPublic(visitor));
|
|
373
|
+
}),
|
|
374
|
+
// The source recomposes the service's scope itself, as it does a visitor's.
|
|
375
|
+
bindServiceReads: (evidence, rows) => bindLater({ evidence, rows }, (captured) => {
|
|
376
|
+
const value = captureServiceEvidence(captured.evidence, owned);
|
|
377
|
+
if (value.place !== 'tenant')
|
|
378
|
+
throw new AppAccessDenied();
|
|
379
|
+
return bind(composeServiceScope(owned, value, captured.rows), () => currentService(value));
|
|
380
|
+
}),
|
|
381
|
+
// The source recomposes the link's scope itself: its one record, never a caller's predicate.
|
|
382
|
+
bindLinkReads: (evidence, rows) => bindLater({ evidence, rows }, (captured) => {
|
|
383
|
+
const value = captureLinkEvidence(captured.evidence, owned);
|
|
384
|
+
return bind(composeLinkScope(owned, value, captured.rows), () => currentLink(value));
|
|
385
|
+
}),
|
|
386
|
+
resolveLink: (lookup) => invoke(lookup, (query) => {
|
|
387
|
+
const { id } = captureLinkLookup(query);
|
|
388
|
+
let row;
|
|
389
|
+
try {
|
|
390
|
+
row = findSqliteLink(db, owner.appId, id, now());
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
// A store no command has written to yet has no link table: no link, as any other miss.
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
return linkResolution(row, (tenant) => readSqliteIntakeAnchor(db, owner, tenant));
|
|
397
|
+
}),
|
|
398
|
+
resolveIntake: (lookup) => invoke(lookup, (query) => {
|
|
399
|
+
const value = captureIntakeLookup(query, owner), sql = intakeAddressQuery(owned, value.column);
|
|
400
|
+
const tenantId = value.address === null ? undefined : intakeTenantOf(db.prepare(sql).all(value.address));
|
|
401
|
+
return intakeResolution(tenantId, (id) => readSqliteIntakeAnchor(db, owner, id));
|
|
402
|
+
}),
|
|
403
|
+
resolveIntakeByTenant: (lookup) => invoke(lookup, (query) => {
|
|
404
|
+
const value = captureIntakeTenantLookup(query, owner);
|
|
405
|
+
return intakeResolutionByTenant(value.tenantId, (id) => readSqliteIntakeAnchor(db, owner, id));
|
|
406
|
+
}),
|
|
407
|
+
readTenantNames: (lookup) => invoke(lookup, (query) => {
|
|
408
|
+
const asked = namesLookup(owned, query);
|
|
409
|
+
if (!asked)
|
|
410
|
+
return Object.freeze({});
|
|
411
|
+
const rows = db.prepare(tenantNamesQuery(owned, asked.plan, asked.tenants.length)).all(...asked.tenants);
|
|
412
|
+
return tenantNamesOf(asked.plan, rows, asked.tenants);
|
|
413
|
+
}),
|
|
414
|
+
readTenantAddresses: (lookup) => invoke(lookup, (query) => {
|
|
415
|
+
const { tenantId, columns } = captureAddressesLookup(owned, query);
|
|
416
|
+
const found = {};
|
|
417
|
+
for (const [kind, column] of Object.entries(columns)) {
|
|
418
|
+
if (column === undefined)
|
|
419
|
+
continue;
|
|
420
|
+
const address = heldAddress(db.prepare(tenantAddressQuery(owned, column)).all(tenantId));
|
|
421
|
+
const own = address && tenantOwnAddress(tenantId, address, db.prepare(intakeAddressQuery(owned, column)).all(address));
|
|
422
|
+
if (own)
|
|
423
|
+
found[kind] = own;
|
|
424
|
+
}
|
|
425
|
+
return Object.freeze(found);
|
|
426
|
+
}),
|
|
427
|
+
// Always a tenant's: `@platform` fails the selector.
|
|
428
|
+
readTenantProfile: (lookup) => invoke(lookup, (query) => {
|
|
429
|
+
const { tenantId, columns } = captureProfileLookup(owned, query);
|
|
430
|
+
return heldProfile(owned, columns, db.prepare(tenantProfileQuery(owned, columns)).all(tenantId));
|
|
431
|
+
}),
|
|
432
|
+
readServiceAnchors: (tenantId) => invoke(tenantId, (id) => Object.freeze({
|
|
433
|
+
tenantVersion: id === null ? null : readSqliteIntakeAnchor(db, owner, parseTenantSelector([id])),
|
|
434
|
+
platformVersion: readSqliteIntakeAnchor(db, owner, PLATFORM_TENANT_ID),
|
|
435
|
+
})),
|
|
436
|
+
readActiveTenants: (options) => invoke(options ?? {}, (query) => {
|
|
437
|
+
const zone = activeTenantsZone(owned, query);
|
|
438
|
+
const active = readSqliteActiveTenants(db, owner);
|
|
439
|
+
if (zone === undefined)
|
|
440
|
+
return Object.freeze(active.map((id) => Object.freeze({ id })));
|
|
441
|
+
const rows = db.prepare(tenantProfileColumnQuery(owned, zone)).all();
|
|
442
|
+
return activeWithColumn(owned, zone, active, rows);
|
|
443
|
+
}),
|
|
444
|
+
readSandboxClocks: () => invoke(null, async () => {
|
|
445
|
+
const rows = sqliteSandboxSession(db);
|
|
446
|
+
return (await sandboxStorePresent(rows)) ? sandboxRows(rows, owner.appId).clocks() : Object.freeze([]);
|
|
447
|
+
}),
|
|
448
|
+
readSandboxes: (tenants) => invoke(sandboxLookup(tenants), async (asked) => {
|
|
449
|
+
const rows = sqliteSandboxSession(db);
|
|
450
|
+
return (await sandboxStorePresent(rows)) ? sandboxRows(rows, owner.appId).among(asked) : new Set();
|
|
451
|
+
}),
|
|
452
|
+
readDueTimers: (query) => invoke(query, (value) => {
|
|
453
|
+
const plan = dueTimersPlan(owned, value);
|
|
454
|
+
const active = plan.tenants ? readSqliteActiveTenants(db, owner) : [];
|
|
455
|
+
if (plan.tenants && !active.length)
|
|
456
|
+
return Object.freeze([]);
|
|
457
|
+
return plan.decode(db.prepare(plan.sql).all(...plan.params(active)));
|
|
458
|
+
}),
|
|
459
|
+
readRecordHistory: (query) => invoke(query, (value) => {
|
|
460
|
+
assertHistoryQuery(value);
|
|
461
|
+
return readSqliteRecordHistory(db, value);
|
|
462
|
+
}),
|
|
463
|
+
readRecordActivity: (query) => invoke(query, (value) => {
|
|
464
|
+
assertActivityQuery(value);
|
|
465
|
+
return readSqliteRecordActivity(db, value);
|
|
466
|
+
}),
|
|
467
|
+
readInbox: (query) => invoke(query, (value) => {
|
|
468
|
+
assertInboxQuery(value);
|
|
469
|
+
return readSqliteInbox(db, value);
|
|
470
|
+
}),
|
|
471
|
+
readEmailOff: (query) => invoke(query, (value) => {
|
|
472
|
+
assertEmailSwitchQuery(value);
|
|
473
|
+
return sqliteInboxMail(async (work) => work(db)).emailOff(value.app, value.recipient);
|
|
474
|
+
}),
|
|
475
|
+
readBranding: (query) => invoke(query, (value) => {
|
|
476
|
+
assertBrandingQuery(value);
|
|
477
|
+
return readSqliteBranding(db, value);
|
|
478
|
+
}),
|
|
479
|
+
readBrandingLogo: (query) => invoke(query, (value) => {
|
|
480
|
+
assertBrandingLogoQuery(value);
|
|
481
|
+
return readSqliteBrandingLogo(db, value);
|
|
482
|
+
}),
|
|
483
|
+
close,
|
|
484
|
+
});
|
|
485
|
+
sources.add(source);
|
|
486
|
+
registerTenantSourceIdentity(source, { ...owner, canonicalPath });
|
|
487
|
+
return source;
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
try {
|
|
491
|
+
opened?.close();
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
/* Construction never publishes its handle. */
|
|
495
|
+
}
|
|
496
|
+
return denyTenant();
|
|
497
|
+
}
|
|
498
|
+
}
|
|
@@ -1,33 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Search for a tenant App: a search provider's index beside PostgreSQL (or
|
|
3
|
-
* SQLite), as an ordinary App has it (appSearchRuntime.ts), with every tenant
|
|
4
|
-
* in one index.
|
|
5
|
-
*
|
|
6
|
-
* One collection per searched resource of the App — not one per tenant. Each
|
|
7
|
-
* document keeps its record's tenant (`mistri_tenant`), and every search a
|
|
8
|
-
* tenant's context asks names that tenant as a filter the engine applies
|
|
9
|
-
* before it ranks. Why one: a deployment's tenants come and go by the
|
|
10
|
-
* thousand, an engine's collection is a schema and an in-memory index of its
|
|
11
|
-
* own, and a collection per tenant would be made at a tenant's creation,
|
|
12
|
-
* migrated with every field the App adds, and reindexed one by one. One
|
|
13
|
-
* collection is one schema, one reindex and the engine's own documented way
|
|
14
|
-
* to serve many tenants. An engine's scoped search keys can embed such a
|
|
15
|
-
* filter in a key a browser could hold; here no key leaves the server, so the
|
|
16
|
-
* filter is composed on it from the tenant the lease admitted, never from
|
|
17
|
-
* anything a request says.
|
|
18
|
-
*
|
|
19
|
-
* And the engine is never the boundary. The keys it answers are read through
|
|
20
|
-
* the context's own reader, under its tenant, grants and row scope, as every
|
|
21
|
-
* row is (`tenantSearchAdapter`); an index that held a wrong document could
|
|
22
|
-
* narrow a list, never show a row of another tenant.
|
|
23
|
-
*
|
|
24
|
-
* The index follows the source's writes, whatever wrote them — a member's
|
|
25
|
-
* edit, a command, a job, an intake, the App API — through the writer's
|
|
26
|
-
* commit observer (tenantWriteSource.ts): each record written is re-read from
|
|
27
|
-
* the database, its tenant with it, and its document written or removed, off
|
|
28
|
-
* the request, as an ordinary App's are. `--reindex --policy` fills it from
|
|
29
|
-
* scratch.
|
|
30
|
-
*/
|
|
31
1
|
import type { Adapter } from '@mistriwork/engine/adapters/adapter.js';
|
|
32
2
|
import type { AppDef } from '../../shared/appModel.js';
|
|
33
3
|
import type { DatabaseSchema } from '@mistriwork/engine/shared/schema.js';
|
|
@@ -48,4 +18,6 @@ export declare function openTenantSearch(input: Readonly<{
|
|
|
48
18
|
registry: Registry;
|
|
49
19
|
app: AppDef;
|
|
50
20
|
ownership: TenantOwnershipSnapshot;
|
|
21
|
+
/** The deployment's resolved PostgreSQL runtime URL: under the row-security backstop, the indexer reads as the owner. */
|
|
22
|
+
url?: string;
|
|
51
23
|
}>): TenantSearch | undefined;
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { indexerFor, tenantSearchAdapter } from '../app/appSearchRuntime.js';
|
|
2
2
|
import { searchProviderOf } from '../app/searchProvider.js';
|
|
3
3
|
import { observeTenantCommits } from './tenantWriteSource.js';
|
|
4
|
+
import { tenantAdapter, tenantBackstop } from './tenantConnections.js';
|
|
4
5
|
/** Each tenant-owned resource's tenant column, by its logical name. */
|
|
5
6
|
export function tenantSearchColumns(ownership) {
|
|
6
7
|
return Object.fromEntries(Object.entries(ownership).flatMap(([resource, rule]) => rule && rule.kind === 'tenant' && typeof rule.column === 'string' ? [[resource, rule.column]] : []));
|
|
7
8
|
}
|
|
8
9
|
/** The tenant App's search, or undefined when it declares none or no search provider is plugged in. */
|
|
9
10
|
export function openTenantSearch(input) {
|
|
10
|
-
const { registry, app, ownership } = input;
|
|
11
|
+
const { registry, app, ownership, url } = input;
|
|
11
12
|
const searched = Object.entries(app.resources ?? {}).filter(([, resource]) => resource.search);
|
|
12
13
|
if (!searched.length || !searchProviderOf(registry))
|
|
13
14
|
return undefined;
|
|
@@ -15,6 +16,13 @@ export function openTenantSearch(input) {
|
|
|
15
16
|
const named = ownership.source.connection;
|
|
16
17
|
const connection = registry.list().find((each) => each.id === named || each.name === named)?.id ?? named;
|
|
17
18
|
const indexer = indexerFor(registry);
|
|
19
|
+
/* The registry's adapter is the runtime role, which reads no tenant row under the backstop, so the indexer would
|
|
20
|
+
remove every document it re-reads. It reads as the owner, across tenants by design (each document keeps its row's
|
|
21
|
+
tenant). One holder of the owner's shared pool, taken at the first read and let go once at close. */
|
|
22
|
+
let owner, closed = false;
|
|
23
|
+
if (url !== undefined && tenantBackstop(url)) {
|
|
24
|
+
indexer.readThrough(connection, () => (owner ??= tenantAdapter(url, 'Private tenant search', false, 'owner')));
|
|
25
|
+
}
|
|
18
26
|
const stop = observeTenantCommits(ownership, (writes) => {
|
|
19
27
|
for (const write of writes) {
|
|
20
28
|
const physical = ownership.resources[write.table];
|
|
@@ -26,6 +34,13 @@ export function openTenantSearch(input) {
|
|
|
26
34
|
});
|
|
27
35
|
return Object.freeze({
|
|
28
36
|
reader: (adapter, schema, tenantId) => tenantSearchAdapter(adapter, { registry, app, schema, tenantId, tenantColumns }),
|
|
29
|
-
close:
|
|
37
|
+
close: () => {
|
|
38
|
+
stop();
|
|
39
|
+
if (closed)
|
|
40
|
+
return;
|
|
41
|
+
closed = true;
|
|
42
|
+
indexer.readThrough(connection, undefined);
|
|
43
|
+
void owner?.close().catch(() => { });
|
|
44
|
+
},
|
|
30
45
|
});
|
|
31
46
|
}
|
|
@@ -138,10 +138,18 @@ options = {}) {
|
|
|
138
138
|
: undefined;
|
|
139
139
|
if (listen && !/^postgres(ql)?:\/\//i.test(listen))
|
|
140
140
|
throw new TenantStartupError('A PostgreSQL source\'s "listen" must be a postgres:// URL.');
|
|
141
|
+
/* The connection's "owner", under "backstop": "rls": `url` and the replicas are then the runtime role's, which reads
|
|
142
|
+
under the pinned policy and owns nothing; the owner's is where what crosses tenants runs, the catalog among it
|
|
143
|
+
(enrollment attests the pair, tenantEnrollment.ts). */
|
|
144
|
+
const owner = connection.backstop
|
|
145
|
+
? (await resolveConnection(connection.name, connection.owner, { environment: capturedEnvironment })).url
|
|
146
|
+
: undefined;
|
|
147
|
+
if (connection.backstop && !/^postgres(ql)?:\/\//i.test(owner))
|
|
148
|
+
throw new TenantStartupError('A PostgreSQL source\'s "owner" must be a postgres:// URL.');
|
|
141
149
|
if (isPostgresAuthStore(store))
|
|
142
|
-
assertPostgresAuthStoreSeparation(store, [{ url }, ...replicas.map((each) => ({ url: each }))]);
|
|
150
|
+
assertPostgresAuthStoreSeparation(store, [{ url }, ...replicas.map((each) => ({ url: each })), ...(owner ? [{ url: owner }] : [])]);
|
|
143
151
|
describe = async () => {
|
|
144
|
-
const adapter = new PostgresAdapter(url, 'Tenant startup');
|
|
152
|
+
const adapter = new PostgresAdapter(owner ?? url, 'Tenant startup');
|
|
145
153
|
try {
|
|
146
154
|
return await adapter.readSnapshot((snapshot) => snapshot.describe());
|
|
147
155
|
}
|
|
@@ -155,11 +163,14 @@ options = {}) {
|
|
|
155
163
|
url,
|
|
156
164
|
...(replicas.length ? { replicas: Object.freeze(replicas) } : {}),
|
|
157
165
|
...(listen ? { listen } : {}),
|
|
166
|
+
...(owner ? { owner } : {}),
|
|
158
167
|
});
|
|
159
168
|
}
|
|
160
169
|
else {
|
|
161
170
|
if (connection.replicas?.length)
|
|
162
171
|
throw new TenantStartupError('SQLite has no replicas: a file is read where it is. Remove "replicas".');
|
|
172
|
+
if (connection.backstop)
|
|
173
|
+
throw new TenantStartupError('SQLite has no roles or row-level security. Remove "backstop" and "owner".');
|
|
163
174
|
const path = resolved.url.replace(/^sqlite:(\/\/)?/i, '');
|
|
164
175
|
if (!path || path.includes('://') || /^file:/i.test(path) || path === ':memory:')
|
|
165
176
|
throw new TenantStartupError();
|
|
@@ -109,7 +109,8 @@ async function openSqliteStore(path, owner, key, authStore, assertAuth) {
|
|
|
109
109
|
* precedes the final native observation, which may await the auth store. */
|
|
110
110
|
async function openPostgresStore(url, owner, key, assertAuth) {
|
|
111
111
|
assertAuth();
|
|
112
|
-
|
|
112
|
+
// Support crosses tenants by design (its log and audit name each one): under the backstop, as the owner.
|
|
113
|
+
const writer = tenantAdapter(url, 'Private tenant support', false, 'owner');
|
|
113
114
|
const attest = async (client) => {
|
|
114
115
|
assertAuth();
|
|
115
116
|
await assertPostgresTenantAdministrationJournal(client, owner);
|
|
@@ -68,6 +68,8 @@ function connectionShape(connections) {
|
|
|
68
68
|
schemas: each.schemas?.length ?? 0,
|
|
69
69
|
replicas: each.replicas?.length ?? 0,
|
|
70
70
|
listen: each.listen !== undefined,
|
|
71
|
+
// Only under the backstop: a configuration without one keeps the shape it had.
|
|
72
|
+
...(each.backstop ? { backstop: each.backstop } : {}),
|
|
71
73
|
}));
|
|
72
74
|
}
|
|
73
75
|
/**
|