@powerhousedao/switchboard 6.2.3-dev.76 → 6.2.3-dev.78

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 CHANGED
@@ -1,3 +1,36 @@
1
+ ## 6.2.3-dev.78 (2026-10-27)
2
+
3
+ ### 🚀 Features
4
+
5
+ - **portle:** scaffold @powerhousedao/portle, the switchboard plugin that gates publication through Portle ([68ab561f7d](https://github.com/powerhouse-inc/powerhouse/commit/68ab561f7d))
6
+ - **reactor-api,reactor-browser,switchboard:** type-neutral drive node queries and read.drives on the remote client ([b8a09950c0](https://github.com/powerhouse-inc/powerhouse/commit/b8a09950c0))
7
+ - **reactor-api,switchboard:** vacuum full policy knob, no forced rewrite under load by default ([d6dcbf5cd0](https://github.com/powerhouse-inc/powerhouse/commit/d6dcbf5cd0))
8
+
9
+ ### 🩹 Fixes
10
+
11
+ - **registry:** a failed tarball write no longer records its attachment ([5d3ae94bd8](https://github.com/powerhouse-inc/powerhouse/commit/5d3ae94bd8))
12
+ - **reactor-api:** the one-time VACUUM FULL is off by default; quiet and forced are opt-ins ([fd7c19e313](https://github.com/powerhouse-inc/powerhouse/commit/fd7c19e313))
13
+ - **switchboard:** port 0 reports the bound port ([3218c7105d](https://github.com/powerhouse-inc/powerhouse/commit/3218c7105d))
14
+
15
+ ### ❤️ Thank You
16
+
17
+ - Benjamin Jordan
18
+ - Claude Fable 5.1
19
+ - Claude Opus 5.5
20
+ - Wouter Kampmann
21
+
22
+ ## 6.2.3-dev.77 (2026-10-26)
23
+
24
+ ### 🚀 Features
25
+
26
+ - **switchboard:** wire the reactor client halves ([73e52624a2](https://github.com/powerhouse-inc/powerhouse/commit/73e52624a2))
27
+ - **switchboard:** move permission rows to the reactor store at boot ([5fd8f83190](https://github.com/powerhouse-inc/powerhouse/commit/5fd8f83190))
28
+
29
+ ### ❤️ Thank You
30
+
31
+ - Claude Fable 5.1
32
+ - Wouter Kampmann
33
+
1
34
  ## 6.2.3-dev.76 (2026-10-25)
2
35
 
3
36
  ### 🚀 Features
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="970d13d2-8fb1-53c8-819e-786cc25376f0")}catch(e){}}();
4
- import { a as startSwitchboard, d as initProfilerFromEnv, f as parseForcePgVersion, o as StoredDocumentsRefusedError } from "./server-CJjK7WpR.mjs";
4
+ import { a as startSwitchboard, d as initProfilerFromEnv, f as parseForcePgVersion, o as StoredDocumentsRefusedError } from "./server-Bdq8xquD.mjs";
5
5
  import { metrics } from "@opentelemetry/api";
6
6
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
7
7
  import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
@@ -25,7 +25,12 @@ interface SwitchboardHostContext {
25
25
  workflows?: unknown;
26
26
  workflowsRetry?: unknown;
27
27
  api?: unknown;
28
+ /** @deprecated The facade; plugins that have moved take `read` and `write`. */
28
29
  client?: unknown;
30
+ /** The reactor's read half (IReactorReadClient), set at onReactorReady. */
31
+ read?: unknown;
32
+ /** The reactor's write half (IReactorWriteClient), set at onReactorReady. */
33
+ write?: unknown;
29
34
  graphqlManager?: unknown;
30
35
  reactorClientModule?: unknown;
31
36
  /** Late subgraph registrations drain before the readiness router update. */
@@ -35,4 +40,4 @@ interface SwitchboardHostContext {
35
40
  //#endregion
36
41
  export { SwitchboardHostContext as t };
37
42
  export {};
38
- //# sourceMappingURL=plugin-host-CGO4XZzK.d.mts.map
43
+ //# sourceMappingURL=plugin-host-BBqojyyY.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-host-BBqojyyY.d.mts","names":[],"sources":["../src/plugin-host.mts"],"mappings":";;;;;;;UAgDiB;;;EAGf;EACA,SAAS;EACT;EACA;;;EAGA;;;EAGA;EACA;;;EAGA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB;EAChB,eAAe,eAAe"}
@@ -1,4 +1,4 @@
1
- import { t as SwitchboardHostContext } from "../plugin-host-CGO4XZzK.mjs";
1
+ import { t as SwitchboardHostContext } from "../plugin-host-BBqojyyY.mjs";
2
2
  import { z } from "zod";
3
3
  import { HostPlugin } from "@powerhousedao/host-core";
4
4
  //#region src/plugins/attachments.d.mts
@@ -1,4 +1,4 @@
1
- import { c as attachmentsPlugin, l as attachmentsPluginConfigSchema } from "../server-CJjK7WpR.mjs";
1
+ import { c as attachmentsPlugin, l as attachmentsPluginConfigSchema } from "../server-Bdq8xquD.mjs";
2
2
  export { attachmentsPlugin, attachmentsPlugin as default, attachmentsPluginConfigSchema };
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c8c8de12-12b0-59fd-b8ff-cfaccbcef3e8")}catch(e){}}();
4
- //# debugId=c8c8de12-12b0-59fd-b8ff-cfaccbcef3e8
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4153b88d-7424-5d61-823d-fdde66aed53b")}catch(e){}}();
4
+ //# debugId=4153b88d-7424-5d61-823d-fdde66aed53b
@@ -1,4 +1,4 @@
1
- import { t as SwitchboardHostContext } from "../plugin-host-CGO4XZzK.mjs";
1
+ import { t as SwitchboardHostContext } from "../plugin-host-BBqojyyY.mjs";
2
2
  import { z } from "zod";
3
3
  import { HostPlugin } from "@powerhousedao/host-core";
4
4
  //#region src/plugins/mcp.d.mts
@@ -1,4 +1,4 @@
1
- import { t as SwitchboardHostContext } from "../plugin-host-CGO4XZzK.mjs";
1
+ import { t as SwitchboardHostContext } from "../plugin-host-BBqojyyY.mjs";
2
2
  import { z } from "zod";
3
3
  import { HostPlugin } from "@powerhousedao/host-core";
4
4
  //#region src/plugins/privacy.d.mts
@@ -1,4 +1,4 @@
1
- import { t as SwitchboardHostContext } from "../plugin-host-CGO4XZzK.mjs";
1
+ import { t as SwitchboardHostContext } from "../plugin-host-BBqojyyY.mjs";
2
2
  import { t as ComposedWorkflowRuntime } from "../workflow-runtime-7GaJ13c9.mjs";
3
3
  import { z } from "zod";
4
4
  import { HostPlugin } from "@powerhousedao/host-core";
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="23ac9e84-b25f-5218-b443-313ef3078eee")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ca62b433-fc4f-5ba3-9edb-8b3b8985f35a")}catch(e){}}();
3
3
  import { _ as triggerFatalShutdown, a as workflowsPlugin, c as WORKFLOW_TELEMETRY_SCOPE, d as isWorkflowSingletonConflict, f as modelManifestSource, g as installFatalErrorShutdown, h as workflowSingletonLossHandler, l as assertWorkflowPackageLoadable, m as retryWorkflowSingleton, p as resolveWorkflowsEnabled, s as WORKFLOW_PACKAGE_NAME, u as composeWorkflowRuntime } from "./workflows-fsBcElEi.mjs";
4
4
  import { i as startPrivacy, r as resolvePrivacy, t as privacyPlugin } from "./privacy-BsFl7GzK.mjs";
5
5
  import { t as mcpPlugin } from "./mcp-SsBK14Jm.mjs";
@@ -20,13 +20,13 @@ import { pathToFileURL } from "node:url";
20
20
  import { CatchUpPriority, ChannelScheme, DriveCollectionId, EventBus, HardenedPGliteDialect, IN_MEMORY_PGLITE_STORAGE_FACTS, PGLITE_PATH_STORAGE_FACTS, POSTGRES_STORAGE_FACTS, REACTOR_SCHEMA, ReactorBuilder, ReactorClientBuilder, UnsupportedStoredProtocolError, createHybridProjectionCoordinatorFactory, instrumentPgPool, parseCatchUpPriority, parseDriveUrl, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
21
21
  import { HttpPackageLoader, ImportPackageLoader, NodeEventLoopDelay, PackageManagementService, PackagesSubgraph, RequestLoadRecorder, baseDocumentModels, getUniqueDocumentModels, initializeAndStartAPI, reportFailure, resolveRenownConfig, runDetached } from "@powerhousedao/reactor-api";
22
22
  import { httpsHooksPath } from "@powerhousedao/reactor-api/https-hooks";
23
- import { PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, resolvePgliteWorkerMemoryMb, syncTree } from "@powerhousedao/reactor-api/pglite-node";
23
+ import { PGLITE_UTC_PARSERS, ThreadedPGlite, createDurableNodeFs, pgliteWorkerEntryPath, preparePgliteDataDir, removeStalePgliteFiles, resolvePgliteFsync, resolvePgliteMaintenance, resolvePgliteWorkerMemoryMb, syncTree } from "@powerhousedao/reactor-api/pglite-node";
24
24
  import { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentReferenceReadModel, AttachmentSchemaCompiler, HashMismatch, InvalidAttachmentMetadata, InvalidAttachmentRef, ReservationNotFound, SizeMismatch, UploadTooLarge, createRef, createRemoteAttachmentService, parseAttachmentDownloadTarget, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
25
25
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
26
- import { DriveNodeView, NodeProcessor, ReactorDriveClient } from "@powerhousedao/reactor-drive";
26
+ import { DriveNodeView, NodeProcessor, REACTOR_DRIVE_DOCUMENT_TYPE, ReactorDriveClient, createReactorDriveWriteStrategy } from "@powerhousedao/reactor-drive";
27
27
  import { REACTOR_DRIVE_SUBGRAPH_NAME, createReactorDriveResolvers, reactorDriveSubgraphTypeDefs } from "@powerhousedao/reactor-drive/subgraph";
28
28
  import { DEFAULT_KEYPAIR_PATH, DEFAULT_RENOWN_URL, NodeKeyStorage, RENOWN_READ_MODEL_SUBGRAPH, RenownBuilder, RenownCryptoBuilder, createLocalCredentialVerifier, createRenownTrustPolicy, resolveSwitchboardEndpoint } from "@renown/sdk/node";
29
- import { Kysely, PostgresDialect } from "kysely";
29
+ import { Kysely, PostgresDialect, sql } from "kysely";
30
30
  import net from "node:net";
31
31
  import path$1 from "path";
32
32
  import { Pool } from "pg";
@@ -144,6 +144,153 @@ async function initProfiler(options, flags = {
144
144
  if (flags.heapEnabled) Pyroscope.startHeapProfiling();
145
145
  }
146
146
  //#endregion
147
+ //#region src/permissions-backfill.mts
148
+ /** The permission tables, as reactor-api once kept them on the read-model store. */
149
+ const PERMISSION_TABLES = [
150
+ "DocumentPermission",
151
+ "OperationUserPermission",
152
+ "DocumentProtection"
153
+ ];
154
+ /** What a read-model table is renamed to once its rows live in the reactor store. */
155
+ const MIGRATED_TABLE_SUFFIX = "_migrated_2026_10_25";
156
+ const INSERT_BATCH_SIZE = 500;
157
+ /**
158
+ * Moves the document permission rows from the read-model store into the
159
+ * reactor store, once.
160
+ *
161
+ * Runs at boot after the reactor's migrations (029 creates the target tables)
162
+ * and before the permission service serves a check. When the read-model
163
+ * store still has the legacy tables and the reactor store's are empty, every
164
+ * row is copied in one reactor-store transaction (ids are not carried: no
165
+ * table references them, and the target's serial assigns fresh ones), then
166
+ * the legacy tables are renamed to `<name>_migrated_2026_10_25` so the copy
167
+ * cannot run again. The renamed tables are kept for a release.
168
+ *
169
+ * Idempotent across crashes: when the copy committed but the rename did not,
170
+ * the next boot finds equal row counts on both sides and only renames. Any
171
+ * other mix of rows on both sides is refused with a warning and both stores
172
+ * are left as they are. Plain SQL throughout, so a PGlite or Postgres read
173
+ * store behaves the same.
174
+ */
175
+ async function backfillPermissionTables(readModelDb, reactorDb, logger) {
176
+ const source = readModelDb;
177
+ const target = reactorDb;
178
+ const present = await existingTables(source);
179
+ const legacy = PERMISSION_TABLES.filter((table) => present.has(table));
180
+ if (legacy.length === 0) {
181
+ if (PERMISSION_TABLES.some((table) => present.has(migratedName(table)))) {
182
+ logger.debug("Permission tables backfill: already done; the read-model tables carry the _migrated_2026_10_25 suffix");
183
+ return { status: "already-backfilled" };
184
+ }
185
+ logger.debug("Permission tables backfill: the read-model store has no permission tables; nothing to copy");
186
+ return { status: "fresh-install" };
187
+ }
188
+ const blocked = legacy.filter((table) => present.has(migratedName(table)));
189
+ if (blocked.length > 0) return refuse(logger, `the read-model store has both ${blocked.join(", ")} and ${blocked.map(migratedName).join(", ")}; drop or rename one of each pair`);
190
+ const legacyCounts = await countRows(source, present);
191
+ const reactorCounts = await countRows(target, new Set(PERMISSION_TABLES));
192
+ if (PERMISSION_TABLES.reduce((sum, table) => sum + reactorCounts[table], 0) > 0) {
193
+ if (!countsEqual(legacyCounts, reactorCounts)) return refuse(logger, `the reactor store already has permission rows (${formatCounts(reactorCounts)}) that differ from the read-model store's (${formatCounts(legacyCounts)})`);
194
+ await renameLegacyTables(source, legacy);
195
+ logger.info(`Permission tables backfill: rows were copied by an earlier boot (${formatCounts(legacyCounts)}); renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`);
196
+ return {
197
+ status: "rename-completed",
198
+ counts: legacyCounts
199
+ };
200
+ }
201
+ await target.transaction().execute(async (trx) => {
202
+ if (present.has("DocumentPermission")) await copyDocumentPermissions(source, trx);
203
+ if (present.has("OperationUserPermission")) await copyOperationUserPermissions(source, trx);
204
+ if (present.has("DocumentProtection")) await copyDocumentProtections(source, trx);
205
+ const copied = await countRows(trx, new Set(PERMISSION_TABLES));
206
+ if (!countsEqual(copied, legacyCounts)) throw new Error(`Permission tables backfill copied ${formatCounts(copied)} but the read-model store has ${formatCounts(legacyCounts)}; rolled back`);
207
+ });
208
+ await renameLegacyTables(source, legacy);
209
+ logger.info(`Permission tables backfill: copied ${formatCounts(legacyCounts)} from the read-model store to the reactor store; renamed the read-model tables to *${MIGRATED_TABLE_SUFFIX}`);
210
+ return {
211
+ status: "copied",
212
+ counts: legacyCounts
213
+ };
214
+ }
215
+ function migratedName(table) {
216
+ return `${table}${MIGRATED_TABLE_SUFFIX}`;
217
+ }
218
+ function refuse(logger, reason) {
219
+ logger.warn(`Permission tables backfill refused: ${reason}. Permission checks read the reactor store; both stores were left unchanged.`);
220
+ return {
221
+ status: "refused",
222
+ reason
223
+ };
224
+ }
225
+ /** The permission tables, legacy or renamed, in the read-model store's own schema. */
226
+ async function existingTables(db) {
227
+ const names = PERMISSION_TABLES.flatMap((table) => [table, migratedName(table)]);
228
+ const result = await sql`
229
+ select table_name from information_schema.tables
230
+ where table_schema = current_schema()
231
+ and table_name in (${sql.join(names)})
232
+ `.execute(db);
233
+ return new Set(result.rows.map((row) => row.table_name));
234
+ }
235
+ async function countRows(db, tables) {
236
+ const counts = {
237
+ DocumentPermission: 0,
238
+ OperationUserPermission: 0,
239
+ DocumentProtection: 0
240
+ };
241
+ for (const table of PERMISSION_TABLES) {
242
+ if (!tables.has(table)) continue;
243
+ const row = await db.selectFrom(table).select((eb) => eb.fn.countAll().as("count")).executeTakeFirstOrThrow();
244
+ counts[table] = Number(row.count);
245
+ }
246
+ return counts;
247
+ }
248
+ function countsEqual(a, b) {
249
+ return PERMISSION_TABLES.every((table) => a[table] === b[table]);
250
+ }
251
+ function formatCounts(counts) {
252
+ return PERMISSION_TABLES.map((table) => `${table}=${counts[table]}`).join(", ");
253
+ }
254
+ async function copyDocumentPermissions(source, trx) {
255
+ const rows = await source.selectFrom("DocumentPermission").select([
256
+ "documentId",
257
+ "userAddress",
258
+ "permission",
259
+ "grantedBy",
260
+ "createdAt",
261
+ "updatedAt"
262
+ ]).orderBy("id").execute();
263
+ for (const batch of batches(rows)) await trx.insertInto("DocumentPermission").values(batch).execute();
264
+ }
265
+ async function copyOperationUserPermissions(source, trx) {
266
+ const rows = await source.selectFrom("OperationUserPermission").select([
267
+ "documentId",
268
+ "operationType",
269
+ "userAddress",
270
+ "grantedBy",
271
+ "createdAt"
272
+ ]).orderBy("id").execute();
273
+ for (const batch of batches(rows)) await trx.insertInto("OperationUserPermission").values(batch).execute();
274
+ }
275
+ async function copyDocumentProtections(source, trx) {
276
+ const rows = await source.selectFrom("DocumentProtection").select([
277
+ "documentId",
278
+ "protected",
279
+ "ownerAddress",
280
+ "createdAt",
281
+ "updatedAt"
282
+ ]).orderBy("documentId").execute();
283
+ for (const batch of batches(rows)) await trx.insertInto("DocumentProtection").values(batch).execute();
284
+ }
285
+ function* batches(rows) {
286
+ for (let start = 0; start < rows.length; start += INSERT_BATCH_SIZE) yield rows.slice(start, start + INSERT_BATCH_SIZE);
287
+ }
288
+ async function renameLegacyTables(db, tables) {
289
+ await db.transaction().execute(async (trx) => {
290
+ for (const table of tables) await sql`ALTER TABLE ${sql.id(table)} RENAME TO ${sql.id(migratedName(table))}`.execute(trx);
291
+ });
292
+ }
293
+ //#endregion
147
294
  //#region src/attachments/auth.ts
148
295
  const ANONYMOUS_ACTOR = {
149
296
  user: void 0,
@@ -1341,20 +1488,8 @@ function pgliteFsyncFor(major, dir, logger) {
1341
1488
  if (wanted && major === 16) logger.warn(`PGlite data dir ${dir} is PG16 on pglite-legacy-02, which does not sync commits to disk; only checkpoints are synced until --migrate-pglite upgrades it.`);
1342
1489
  return wanted;
1343
1490
  }
1344
- /** VACUUM FULL timing from the environment; unset or invalid keeps the defaults. */
1345
- function vacuumFullTimingFromEnv(env) {
1346
- const ms = (value) => {
1347
- if (value === void 0 || value.trim() === "") return void 0;
1348
- const parsed = Number(value);
1349
- return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
1350
- };
1351
- const quiet = ms(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);
1352
- const maxDefer = ms(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);
1353
- return {
1354
- ...quiet === void 0 ? {} : { vacuumFullQuietMs: quiet },
1355
- ...maxDefer === void 0 ? {} : { vacuumFullMaxDeferMs: maxDefer }
1356
- };
1357
- }
1491
+ /** The VACUUM FULL settings from the environment; see `resolvePgliteMaintenance`. */
1492
+ const vacuumFullTimingFromEnv = resolvePgliteMaintenance;
1358
1493
  /** Preloads the module's NodeFS so the returned factory can be synchronous. */
1359
1494
  async function loadDurableFsFactory(major, logger, proc) {
1360
1495
  const NodeFS = await loadNodeFsClass(major);
@@ -1695,7 +1830,7 @@ function readConfigWorkflowsEnabled(configPath) {
1695
1830
  }
1696
1831
  }
1697
1832
  async function resolveServerPort(requested, strictPort, logger) {
1698
- if (strictPort) return requested;
1833
+ if (requested === 0 || strictPort) return requested;
1699
1834
  for (let i = 0; i < PORT_FALLBACK_ATTEMPTS; i++) {
1700
1835
  const candidate = requested + i;
1701
1836
  if (await isPortAvailable(candidate)) {
@@ -1777,7 +1912,7 @@ function deriveAttachmentServiceConfig(options, serverPort, renown) {
1777
1912
  }) : void 0 : void 0
1778
1913
  };
1779
1914
  }
1780
- async function initServer(serverPort, options, renown, renownConfig) {
1915
+ async function initServer(requestedPort, options, renown, renownConfig) {
1781
1916
  const { dev, packages = [], remoteDrives = [], logger = defaultLogger } = options;
1782
1917
  const pluginHost = isPluginHostEnabled() ? createSwitchboardPluginHost({
1783
1918
  logger,
@@ -1879,7 +2014,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
1879
2014
  const catchUpPriority = new CatchUpPriority(catchUpPrioritySettingFromEnv(process.env.PH_CATCH_UP_PRIORITY, logger));
1880
2015
  let workerModels;
1881
2016
  let localRenownRequest;
1882
- const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests }) => {
2017
+ const initializeClient = async (documentModels, { attachmentReferenceWriter, upgradeManifests, readModelDb }) => {
1883
2018
  if (options.reactor) {
1884
2019
  const attachmentReferenceProjection = await registerAttachmentReferenceReadModelOnModule(options.reactor, attachmentReferenceWriter);
1885
2020
  if (options.reactor.reactorModule) {
@@ -1975,6 +2110,10 @@ async function initServer(serverPort, options, renown, renownConfig) {
1975
2110
  reactorBuilder.withShutdownHook(async () => {
1976
2111
  if (apiRef.current) await apiRef.current.dispose();
1977
2112
  });
2113
+ const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
2114
+ const nodeView = new DriveNodeView(reactorDriveSchemaDb);
2115
+ driveNodeView = nodeView;
2116
+ clientBuilder.withDriveNodeSource(nodeView).withDriveWriteStrategy(REACTOR_DRIVE_DOCUMENT_TYPE, createReactorDriveWriteStrategy);
1978
2117
  let module;
1979
2118
  try {
1980
2119
  module = await clientBuilder.buildModule();
@@ -1991,18 +2130,31 @@ async function initServer(serverPort, options, renown, renownConfig) {
1991
2130
  new ReactorInstrumentation(module.reactorModule).start();
1992
2131
  reactorLogger.info("Reactor metrics instrumentation started");
1993
2132
  }
1994
- const reactorDriveSchemaDb = baseKysely.withSchema(REACTOR_SCHEMA);
1995
- driveNodeView = new DriveNodeView(reactorDriveSchemaDb);
1996
2133
  const reactorDriveClient = new ReactorDriveClient({
1997
- reactor: module.client,
1998
- readModel: driveNodeView
2134
+ read: module.read,
2135
+ write: module.write,
2136
+ readModel: nodeView
1999
2137
  });
2000
2138
  ownedReactorModule = module;
2001
2139
  if (options.fatalErrorShutdown) installFatalErrorShutdown(logger);
2140
+ const permissionsDb = baseKysely.withSchema(REACTOR_SCHEMA);
2141
+ try {
2142
+ if (readModelDb) await backfillPermissionTables(readModelDb, permissionsDb, logger);
2143
+ } catch (error) {
2144
+ logger.error("Aborting boot: permission tables backfill failed: @error", error);
2145
+ try {
2146
+ await module.reactorModule?.shutdown();
2147
+ } catch (shutdownError) {
2148
+ logger.error("Aborting boot: reactor shutdown failed: @error", shutdownError);
2149
+ }
2150
+ throw error;
2151
+ }
2002
2152
  return {
2003
2153
  module,
2004
2154
  reactorDriveClient,
2005
- attachmentReferenceProjection: { status: "available" }
2155
+ driveNodes: nodeView,
2156
+ attachmentReferenceProjection: { status: "available" },
2157
+ permissionsDb
2006
2158
  };
2007
2159
  };
2008
2160
  const abortBoot = async (api) => {
@@ -2073,7 +2225,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
2073
2225
  pgliteFactory = (connectionString) => openReadStore(connectionString ?? readModelPgliteDir);
2074
2226
  }
2075
2227
  const api = await initializeAndStartAPI(initializeClient, {
2076
- port: serverPort,
2228
+ port: requestedPort,
2077
2229
  dbPath: readModelPath,
2078
2230
  pgliteFactory,
2079
2231
  https: options.https,
@@ -2091,6 +2243,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
2091
2243
  verifyCredential
2092
2244
  }, "switchboard");
2093
2245
  apiRef.current = api;
2246
+ const serverPort = api.port;
2094
2247
  if (renownConfig.source === "self") {
2095
2248
  const { graphqlManager: manager } = api;
2096
2249
  if (!manager.hasSubgraphHandler(RENOWN_READ_MODEL_SUBGRAPH)) {
@@ -2112,10 +2265,12 @@ async function initServer(serverPort, options, renown, renownConfig) {
2112
2265
  attachmentService = createRemoteAttachmentService(deriveAttachmentServiceConfig(options, serverPort, renown));
2113
2266
  }
2114
2267
  if (process.env.SENTRY_DSN) api.httpAdapter.setupSentryErrorHandler(Sentry);
2115
- const { client, graphqlManager, documentModelRegistry } = api;
2268
+ const { client, read, write, graphqlManager, documentModelRegistry } = api;
2116
2269
  const lateSubgraphs = [];
2117
2270
  if (pluginHost) {
2118
2271
  pluginHost.ctx.client = client;
2272
+ pluginHost.ctx.read = read;
2273
+ pluginHost.ctx.write = write;
2119
2274
  pluginHost.ctx.graphqlManager = graphqlManager;
2120
2275
  pluginHost.ctx.lateSubgraphs = lateSubgraphs;
2121
2276
  pluginHost.ctx.reactorClientModule = options.reactor ?? ownedReactorModule;
@@ -2149,6 +2304,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
2149
2304
  const registerWorkflowSubgraph = (composed) => {
2150
2305
  const WorkflowRuntimeSubgraph = composed.subgraph;
2151
2306
  const workflowSubgraph = new WorkflowRuntimeSubgraph({
2307
+ readClient: read,
2152
2308
  reactorClient: client,
2153
2309
  http: graphqlManager.scopeForPackage(WORKFLOW_PACKAGE_NAME),
2154
2310
  relationalDb: api.relationalDb,
@@ -2266,6 +2422,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
2266
2422
  const packagesSubgraph = new PackagesSubgraph({
2267
2423
  relationalDb: void 0,
2268
2424
  analyticsStore: void 0,
2425
+ readClient: read,
2269
2426
  reactorClient: client,
2270
2427
  graphqlManager,
2271
2428
  syncManager: api.syncManager,
@@ -2291,6 +2448,7 @@ async function initServer(serverPort, options, renown, renownConfig) {
2291
2448
  hostCanRead: (documentId, address) => authorizationService.canRead(documentId, address)
2292
2449
  }),
2293
2450
  typeDefs: reactorDriveSubgraphTypeDefs,
2451
+ readClient: read,
2294
2452
  reactorClient: client,
2295
2453
  relationalDb: void 0
2296
2454
  };
@@ -2459,5 +2617,5 @@ function feedCatchUpPriority(priority, server) {
2459
2617
  //#endregion
2460
2618
  export { startSwitchboard as a, attachmentsPlugin as c, initProfilerFromEnv as d, parseForcePgVersion as f, resolvePgliteStorageDirs as i, attachmentsPluginConfigSchema as l, deriveAttachmentServiceConfig as n, StoredDocumentsRefusedError as o, isPortAvailable as r, resolveUnsupportedStoredDocuments as s, createReactorKysely as t, applySwitchboardReactorDefaults as u };
2461
2619
 
2462
- //# sourceMappingURL=server-CJjK7WpR.mjs.map
2463
- //# debugId=23ac9e84-b25f-5218-b443-313ef3078eee
2620
+ //# sourceMappingURL=server-Bdq8xquD.mjs.map
2621
+ //# debugId=ca62b433-fc4f-5ba3-9edb-8b3b8985f35a