@crombolo/server 0.37.0 → 0.38.1

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 (79) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +10 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-query.ts +1 -1
  21. package/src/adapters/users.ts +13 -13
  22. package/src/adapters/webhooks.ts +1 -1
  23. package/src/anonymise-rules.ts +83 -0
  24. package/src/approvals-api.ts +1 -1
  25. package/src/approvals.ts +75 -38
  26. package/src/back-office-url.ts +20 -0
  27. package/src/backup.ts +26 -2
  28. package/src/bundle-code.ts +1 -1
  29. package/src/bundle-grants.ts +265 -0
  30. package/src/bundle-install.ts +13 -2
  31. package/src/bundle-media.ts +12 -11
  32. package/src/bundles.ts +126 -43
  33. package/src/component-snippets.ts +1 -1
  34. package/src/components.ts +6 -1
  35. package/src/config.ts +61 -3
  36. package/src/content-notifications.ts +13 -9
  37. package/src/content-operations.ts +23 -65
  38. package/src/content-query.ts +1 -1
  39. package/src/core.ts +663 -0
  40. package/src/cron.ts +139 -0
  41. package/src/custom-tables.ts +274 -0
  42. package/src/database.ts +22 -14
  43. package/src/dictionary-transfer.ts +1 -1
  44. package/src/git-routes.ts +1 -1
  45. package/src/identity-provider-overrides.ts +18 -16
  46. package/src/imaging.ts +65 -15
  47. package/src/index.ts +10 -1
  48. package/src/job-wake.ts +23 -0
  49. package/src/live-reload.ts +195 -0
  50. package/src/log-viewer.ts +6 -1
  51. package/src/marketplace.ts +82 -10
  52. package/src/media-access.ts +12 -9
  53. package/src/member-auth.ts +6 -4
  54. package/src/models-builder.ts +1 -1
  55. package/src/node-operations.ts +122 -0
  56. package/src/owner-jobs.ts +428 -0
  57. package/src/ports.ts +36 -154
  58. package/src/preview-tokens.ts +6 -12
  59. package/src/remote.ts +3 -1
  60. package/src/schema.ts +8 -3
  61. package/src/seed/compile.ts +7 -5
  62. package/src/seed/export.ts +6 -4
  63. package/src/seo.ts +2 -2
  64. package/src/server.ts +333 -452
  65. package/src/settings.ts +18 -2
  66. package/src/site-data.ts +195 -0
  67. package/src/site-file.ts +30 -4
  68. package/src/site-queries.ts +140 -0
  69. package/src/site-replace.ts +25 -19
  70. package/src/site-sections.ts +1 -1
  71. package/src/site-services.ts +23 -6
  72. package/src/status-pages.ts +19 -5
  73. package/src/status.ts +11 -9
  74. package/src/url-settings.ts +1 -2
  75. package/src/webhook-files.ts +1 -1
  76. package/src/webhooks.ts +31 -23
  77. package/src/worker-watch.ts +73 -0
  78. package/src/worker.ts +138 -0
  79. package/src/bundle-tables.ts +0 -161
package/src/status.ts CHANGED
@@ -24,11 +24,12 @@ import {
24
24
  readLedger,
25
25
  readReport,
26
26
  readState,
27
+ sql,
27
28
  TransferRunRepository,
28
29
  } from '@crombolo/data'
29
30
  import { loadSchemaDirectory } from '@crombolo/schema'
30
- import { BundleConfigurationError, bundleChainsFor, pendingBundleSteps } from './bundle-tables.ts'
31
31
  import { type CromboloConfig, describeDatabase, VERSION } from './config.ts'
32
+ import { BundleConfigurationError, pendingTablesSteps, tablesChainsFor } from './custom-tables.ts'
32
33
  import { type EmailAvailability, emailAvailability, resolveEmailPort } from './email.ts'
33
34
  import { formTypesFor } from './form-types.ts'
34
35
  import { assertViewRuntime } from './view-runtime.ts'
@@ -97,11 +98,12 @@ function compareVersions(a: string, b: string): number {
97
98
  }
98
99
 
99
100
  async function contentCounts(db: Db): Promise<SiteStatus['content']> {
100
- const rows = await db.query<{ node_object_type: string; n: number }>(
101
- `SELECT node_object_type, COUNT(*) AS n FROM node
102
- WHERE trashed = ? GROUP BY node_object_type`,
103
- [db.dialect.boolValue(false)],
104
- )
101
+ const rows = await db.q
102
+ .selectFrom('node')
103
+ .select(['node_object_type', sql<number>`COUNT(*)`.as('n')])
104
+ .where('trashed', '=', db.dialect.boolValue(false) as boolean)
105
+ .groupBy('node_object_type')
106
+ .execute()
105
107
  const of = (objectType: string) =>
106
108
  Number(rows.find((row) => row.node_object_type === objectType)?.n ?? 0)
107
109
  return {
@@ -201,10 +203,10 @@ export async function siteStatus(config: CromboloConfig): Promise<SiteStatus> {
201
203
  )
202
204
 
203
205
  try {
204
- const chains = bundleChainsFor(config)
206
+ const chains = tablesChainsFor(config)
205
207
  for (const chain of chains)
206
208
  status.bundles[chain.id] = { name: chain.name, state: null, pending: [] }
207
- for (const bundle of await pendingBundleSteps(db, chains)) {
209
+ for (const bundle of await pendingTablesSteps(db, chains)) {
208
210
  status.bundles[bundle.id] = {
209
211
  name: bundle.name,
210
212
  state: bundle.state,
@@ -212,7 +214,7 @@ export async function siteStatus(config: CromboloConfig): Promise<SiteStatus> {
212
214
  }
213
215
  if (bundle.pending.length > 0 && !config.development)
214
216
  status.problems.push(
215
- `the bundle "${bundle.id}" has ${bundle.pending.length} step(s) pending: run \`crombolo upgrade\``,
217
+ `${bundle.id === 'site' ? "the site's own tables have" : `the bundle "${bundle.id}" has`} ${bundle.pending.length} step(s) pending: run \`crombolo upgrade\``,
216
218
  )
217
219
  }
218
220
  } catch (error) {
@@ -20,9 +20,8 @@ import {
20
20
  type PublishedCacheOptions,
21
21
  type PublishedContentSource,
22
22
  } from '@crombolo/render'
23
- import { createSchemaFileWriter } from './adapters/schema-files.ts'
23
+ import { createSchemaFileWriter, schemaFiles } from './adapters/schema-files.ts'
24
24
  import type { CromboloConfig } from './config.ts'
25
- import { schemaFiles } from './ports.ts'
26
25
  import type { RedirectTracker } from './redirects.ts'
27
26
 
28
27
  export interface UrlChangeContext {
@@ -7,7 +7,7 @@
7
7
  * one differs from the one its alias derives, and names its content types by
8
8
  * alias. A legacy `<key>.toml` with keys still reads.
9
9
  */
10
- import { WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management'
10
+ import { WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management/domain'
11
11
  import { derivedKey } from '@crombolo/core'
12
12
 
13
13
  export type WebhookStore = 'files' | 'database'
package/src/webhooks.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
7
  import { join } from 'node:path'
8
- import { type RaisedWebhookEvent, WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management'
8
+ import { type RaisedWebhookEvent, WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management/domain'
9
9
  import {
10
10
  ContentTypeRepository,
11
11
  type Db,
@@ -142,6 +142,8 @@ export interface WebhookServiceOptions {
142
142
  /** Publishes the schema directory to a shared store, when there is one. */
143
143
  onFilesChanged?: () => Promise<void>
144
144
  now?: () => Date
145
+ /** Whether a bundle is turned on (story 222); its events are not delivered while it is off. */
146
+ isBundleOn?(bundleId: string): boolean
145
147
  }
146
148
 
147
149
  /** An event as a webhook delivers it, with the item's type and place as they were when it happened. */
@@ -436,6 +438,13 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
436
438
  delivery: WebhookDelivery,
437
439
  bundleId: string,
438
440
  ): Promise<{ ok: true } | { ok: false; error: string; retry: boolean }> => {
441
+ // A bundle that is off runs nothing of its own (story 222).
442
+ if (options.isBundleOn && !options.isBundleOn(bundleId))
443
+ return {
444
+ ok: false,
445
+ error: `The bundle "${bundleId}" is waiting for an administrator to approve what it may do.`,
446
+ retry: false,
447
+ }
439
448
  const handler = bundles.find((bundle) => bundle.id === bundleId)?.events?.[delivery.eventAlias]
440
449
  const entry = {
441
450
  deliveryId: delivery.id,
@@ -607,24 +616,26 @@ async function itemFacts(
607
616
  db: Db,
608
617
  key: string,
609
618
  ): Promise<Pick<WebhookFacts, 'contentTypeKey' | 'contentTypeAlias' | 'ancestors'> | undefined> {
610
- const rows = await db.query<{
611
- type_key: string
612
- type_alias: string | null
613
- path: string
614
- original_path: string | null
615
- original_parent_id: number | null
616
- }>(
617
- `SELECT tn.unique_id AS type_key, ct.alias AS type_alias, n.path AS path,
618
- op.path AS original_path, d.original_parent_id AS original_parent_id
619
- FROM node n
620
- JOIN content c ON c.node_id = n.id
621
- JOIN node tn ON tn.id = c.content_type_id
622
- LEFT JOIN content_type ct ON ct.node_id = tn.id
623
- LEFT JOIN document d ON d.node_id = n.id AND n.trashed = ?
624
- LEFT JOIN node op ON op.id = d.original_parent_id
625
- WHERE n.unique_id = ?`,
626
- [db.dialect.boolValue(true), key],
627
- )
619
+ const rows = await db.q
620
+ .selectFrom('node as n')
621
+ .innerJoin('content as c', 'c.node_id', 'n.id')
622
+ .innerJoin('node as tn', 'tn.id', 'c.content_type_id')
623
+ .leftJoin('content_type as ct', 'ct.node_id', 'tn.id')
624
+ .leftJoin('document as d', (join) =>
625
+ join
626
+ .onRef('d.node_id', '=', 'n.id')
627
+ .on('n.trashed', '=', db.dialect.boolValue(true) as boolean),
628
+ )
629
+ .leftJoin('node as op', 'op.id', 'd.original_parent_id')
630
+ .select([
631
+ 'tn.unique_id as type_key',
632
+ 'ct.alias as type_alias',
633
+ 'n.path as path',
634
+ 'op.path as original_path',
635
+ 'd.original_parent_id as original_parent_id',
636
+ ])
637
+ .where('n.unique_id', '=', key)
638
+ .execute()
628
639
  const row = rows[0]
629
640
  if (!row) return undefined
630
641
  // In the recycle bin its path is the bin's, so its ancestors are where it was.
@@ -635,10 +646,7 @@ async function itemFacts(
635
646
  const found =
636
647
  ids.length === 0
637
648
  ? []
638
- : await db.query<{ id: number; unique_id: string }>(
639
- `SELECT id, unique_id FROM node WHERE id IN (${ids.map(() => '?').join(', ')})`,
640
- ids,
641
- )
649
+ : await db.q.selectFrom('node').select(['id', 'unique_id']).where('id', 'in', ids).execute()
642
650
  const keyOf = new Map(found.map((r) => [Number(r.id), String(r.unique_id).toLowerCase()]))
643
651
  return {
644
652
  contentTypeKey: String(row.type_key).toLowerCase(),
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Whether anything is running the jobs a node left to a worker (story 223,
3
+ * decision 4). Work queues safely while none is; this says so, in `/health`,
4
+ * on the Background jobs screen and once in the log, and drains nothing.
5
+ */
6
+ import { type Db, liveNodes } from '@crombolo/data'
7
+ import type { CromboloConfig } from './config.ts'
8
+ import { runsJobs } from './job-wake.ts'
9
+ import { logger } from './logging.ts'
10
+
11
+ /** A worker not seen in `server` for this long is not running. */
12
+ export const WORKER_GONE_AFTER_MS = 5 * 60_000
13
+
14
+ export interface JobsStatus {
15
+ /** Whether this node runs the jobs itself. */
16
+ here: boolean
17
+ /** A live worker's node id, when this node leaves its jobs to one. */
18
+ worker: string | null
19
+ /** Since when no worker has been seen; null while one is, or where jobs run here. */
20
+ waitingSince: string | null
21
+ }
22
+
23
+ export interface WorkerWatch {
24
+ status(): JobsStatus
25
+ /** Looks for a live worker now; the timer calls this too. */
26
+ check(): Promise<JobsStatus>
27
+ start(): void
28
+ stop(): void
29
+ }
30
+
31
+ export function createWorkerWatch(options: {
32
+ db: Db
33
+ config: Pick<CromboloConfig, 'role' | 'runJobs'>
34
+ intervalMs?: number
35
+ now?: () => Date
36
+ }): WorkerWatch {
37
+ const here = runsJobs(options.config)
38
+ const now = options.now ?? (() => new Date())
39
+ const log = logger('jobs')
40
+ let status: JobsStatus = { here, worker: null, waitingSince: null }
41
+ let timer: ReturnType<typeof setInterval> | undefined
42
+ const watch: WorkerWatch = {
43
+ status: () => status,
44
+ async check() {
45
+ if (here) return status
46
+ const workers = (await liveNodes(options.db, { seenWithinMs: WORKER_GONE_AFTER_MS })).filter(
47
+ (node) => node.role === 'worker',
48
+ )
49
+ const worker = workers[0]?.nodeId ?? null
50
+ if (!worker && !status.waitingSince)
51
+ log.warning(
52
+ 'Background work is waiting: this node leaves its jobs to a worker, and none has been seen for five minutes',
53
+ )
54
+ status = {
55
+ here,
56
+ worker,
57
+ waitingSince: worker ? null : (status.waitingSince ?? now().toISOString()),
58
+ }
59
+ return status
60
+ },
61
+ start() {
62
+ if (here || timer) return
63
+ void watch.check().catch(() => {})
64
+ timer = setInterval(() => void watch.check().catch(() => {}), options.intervalMs ?? 60_000)
65
+ timer.unref()
66
+ },
67
+ stop() {
68
+ if (timer) clearInterval(timer)
69
+ timer = undefined
70
+ },
71
+ }
72
+ return watch
73
+ }
package/src/worker.ts ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * A node that runs the background jobs and nothing else (story 223): core's,
3
+ * the site's and its bundles' jobs and schedules, on the core every node is
4
+ * built on. It answers `/health` alone; no page, back office or API is
5
+ * mounted. docs/operations.md, "Running a cluster".
6
+ */
7
+ import type { WritesPaused } from '@crombolo/data'
8
+ import type { Server } from 'bun'
9
+ import type { CromboloConfig } from './config.ts'
10
+ import { VERSION } from './config.ts'
11
+ import { createCore } from './core.ts'
12
+ import { closeTables } from './custom-tables.ts'
13
+ import type { BackgroundJobs } from './jobs.ts'
14
+ import { logger } from './logging.ts'
15
+ import type { JobRunner } from './owner-jobs.ts'
16
+ import type { SchemaBoot } from './schema.ts'
17
+ import { createSeoHost } from './seo.ts'
18
+
19
+ export interface WorkerHealth {
20
+ /** False once the database is ahead of this node, as on any node that writes. */
21
+ ok: boolean
22
+ readOnly: boolean
23
+ paused: WritesPaused | null
24
+ version: string
25
+ revision: string
26
+ nodeId: string
27
+ role: 'worker'
28
+ /** The job this worker is running, and when it last claimed one. */
29
+ jobs: { running: string | null; lastClaimAt: string | null }
30
+ }
31
+
32
+ export interface WorkerHandle {
33
+ config: CromboloConfig
34
+ db: Awaited<ReturnType<typeof createCore>>['db']
35
+ schema: SchemaBoot
36
+ /** A worker never seeds, so there is never a password to print. */
37
+ seededAdminPassword: undefined
38
+ health(): WorkerHealth
39
+ /** `/health`, and no answer to anything else. */
40
+ fetch(request: Request): Promise<Response>
41
+ serveOptions: {
42
+ port: number
43
+ maxRequestBodySize: number
44
+ fetch(request: Request, server: Server<unknown>): Promise<Response>
45
+ websocket: { message(): void }
46
+ }
47
+ /** The wired bundles that are off, waiting for an administrator to approve these permissions. */
48
+ waitingBundles(): { id: string; missing: string[] }[]
49
+ /** Core's jobs; each run can be called directly. */
50
+ jobs: BackgroundJobs
51
+ /** The site's and bundles' jobs (story 187). */
52
+ backgroundJobs: JobRunner
53
+ /** Applies cache instructions other nodes appended; the interval calls this too. */
54
+ poll(): Promise<number>
55
+ /** Finishes or releases the running job, then closes the database. */
56
+ close(): Promise<void>
57
+ }
58
+
59
+ export async function createWorker(config: CromboloConfig): Promise<WorkerHandle> {
60
+ if (config.role !== 'worker')
61
+ throw new Error(`createWorker needs the worker role, not '${config.role}'.`)
62
+ let seo: ReturnType<typeof createSeoHost> | undefined
63
+ const core = await createCore(config, {
64
+ // E-mails are rendered here, pages never: no island needs its browser code.
65
+ buildIslands: false,
66
+ siteName: async () => (await seo?.siteDefaults())?.siteName ?? config.siteName,
67
+ })
68
+ const { db, schema, poller, bundleGrants, bundlePackages, jobs, jobRunner } = core
69
+ // For the site's name in the e-mails a form sends, as its settings give it.
70
+ seo = createSeoHost({
71
+ db,
72
+ config,
73
+ cache: core.cache,
74
+ isProtected: async () => true,
75
+ draft: async () => undefined,
76
+ })
77
+
78
+ const health = (): WorkerHealth => {
79
+ const paused = poller.paused
80
+ return {
81
+ ok: !schema.compatibilityMode && !poller.behind,
82
+ readOnly: schema.compatibilityMode || poller.behind || paused !== undefined,
83
+ paused: paused ?? null,
84
+ version: schema.nodeState.version,
85
+ revision: schema.nodeState.revision,
86
+ nodeId: schema.nodeId,
87
+ role: 'worker',
88
+ jobs: jobRunner.state(),
89
+ }
90
+ }
91
+ const fetch = async (request: Request): Promise<Response> => {
92
+ if (new URL(request.url).pathname !== '/health') return new Response(null, { status: 404 })
93
+ const report = health()
94
+ return Response.json(report, {
95
+ status: report.ok ? 200 : 503,
96
+ headers: { 'cache-control': 'no-store' },
97
+ })
98
+ }
99
+
100
+ await core.startJobs()
101
+ logger('server').info('Crombolo {version} started on node {nodeId} as worker', {
102
+ version: VERSION,
103
+ nodeId: schema.nodeId,
104
+ })
105
+
106
+ return {
107
+ config,
108
+ db,
109
+ schema,
110
+ seededAdminPassword: undefined,
111
+ health,
112
+ fetch,
113
+ serveOptions: {
114
+ port: config.port,
115
+ maxRequestBodySize: 1024,
116
+ fetch: (request) => fetch(request),
117
+ websocket: { message() {} },
118
+ },
119
+ waitingBundles: () =>
120
+ config.bundles.flatMap((bundle) => {
121
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
122
+ if (!pkg || bundleGrants.isOn(bundle.id)) return []
123
+ return [{ id: bundle.id, missing: bundleGrants.state(pkg).missing }]
124
+ }),
125
+ jobs,
126
+ backgroundJobs: jobRunner,
127
+ poll: () => poller.poll(),
128
+ async close() {
129
+ core.diagnostics.stop()
130
+ await core.stopJobs()
131
+ // A dispatch a job started finishes before the connection goes.
132
+ await core.dispatcher.settled().catch(() => {})
133
+ poller.stop()
134
+ await closeTables(core.chains)
135
+ await db.close()
136
+ },
137
+ }
138
+ }
@@ -1,161 +0,0 @@
1
- /**
2
- * The chains of the bundles a site wires that own tables: worked out once from
3
- * the configuration and the packages those bundles came from, and run after
4
- * core's, in the order `bundles` lists them. `docs/bundles.md`, Part 4.
5
- *
6
- * Only a node that mounts bundles — one that serves the backoffice — applies
7
- * them or checks them at boot. A `web` node reads nothing of a bundle's.
8
- */
9
- import { type BundlePackage, discoverBundles } from '@crombolo/backoffice-host'
10
- import {
11
- bundlePlan,
12
- type CompiledTables,
13
- compileBundleTables,
14
- type Db,
15
- type Migration,
16
- type MigrationPlan,
17
- migrate,
18
- type PlannedStep,
19
- pendingMigrations,
20
- planUpgrade,
21
- readLedger,
22
- readState,
23
- } from '@crombolo/data'
24
- import { type ServerBundle, validateServerBundles } from './bundles.ts'
25
- import { type CromboloConfig, VERSION } from './config.ts'
26
-
27
- /** One bundle's chain, with what it is called. */
28
- export interface BundleChain {
29
- id: string
30
- name: string
31
- compiled: CompiledTables
32
- plan: MigrationPlan
33
- }
34
-
35
- /**
36
- * The chains of every wired bundle that declares tables, in wiring order.
37
- * Throws when a declaration is invalid; `validateServerBundles` is what reports
38
- * the reasons, and boot runs it first.
39
- */
40
- export function bundleChains(
41
- bundles: readonly ServerBundle[],
42
- packages: readonly BundlePackage[],
43
- ): BundleChain[] {
44
- return bundles.flatMap((bundle) => {
45
- if (!bundle.tables) return []
46
- const owner = packages.find((pkg) => pkg.id === bundle.id)
47
- const compiled = compileBundleTables(bundle.tables, owner?.version)
48
- return [{ id: bundle.id, name: owner?.name ?? bundle.id, compiled, plan: bundlePlan(compiled) }]
49
- })
50
- }
51
-
52
- /** The wired bundles cannot be used: every reason, at once. */
53
- export class BundleConfigurationError extends Error {
54
- constructor(readonly problems: string[]) {
55
- super(`The configured bundles cannot be used:\n- ${problems.join('\n- ')}`)
56
- }
57
- }
58
-
59
- /**
60
- * The chains for a site's configuration, discovering its packages and checking
61
- * the bundles exactly as boot checks them, so a command off the server refuses
62
- * what the server would.
63
- */
64
- export function bundleChainsFor(
65
- config: Pick<CromboloConfig, 'bundles' | 'siteDir'>,
66
- ): BundleChain[] {
67
- if (config.bundles.length === 0) return []
68
- const packages = discoverBundles(config.siteDir).bundles
69
- const problems = validateServerBundles(config.bundles, packages, VERSION)
70
- if (problems.length > 0) throw new BundleConfigurationError(problems)
71
- return bundleChains(config.bundles, packages)
72
- }
73
-
74
- export interface BundlePending {
75
- id: string
76
- name: string
77
- state: string
78
- pending: Migration[]
79
- }
80
-
81
- /** What each chain still has to run. Throws `UpgradeStateError`, naming the bundle, when one is ahead. */
82
- export async function pendingBundleSteps(
83
- db: Db,
84
- chains: readonly BundleChain[],
85
- ): Promise<BundlePending[]> {
86
- const out: BundlePending[] = []
87
- for (const chain of chains)
88
- out.push({
89
- id: chain.id,
90
- name: chain.name,
91
- state: await readState(db, chain.plan),
92
- pending: await pendingMigrations(db, chain.plan),
93
- })
94
- return out
95
- }
96
-
97
- /** Runs each chain's pending steps, in order, after core's. */
98
- export async function migrateBundles(
99
- db: Db,
100
- chains: readonly BundleChain[],
101
- options: { by?: string } = {},
102
- ): Promise<{ id: string; applied: string[] }[]> {
103
- const out: { id: string; applied: string[] }[] = []
104
- for (const chain of chains) {
105
- const result = await migrate(db, chain.plan, { by: options.by })
106
- out.push({ id: chain.id, applied: result.applied })
107
- }
108
- return out
109
- }
110
-
111
- /** What each chain would run, without running it. */
112
- export async function planBundleUpgrades(
113
- db: Db,
114
- chains: readonly BundleChain[],
115
- ): Promise<{ id: string; name: string; steps: PlannedStep[] }[]> {
116
- const out: { id: string; name: string; steps: PlannedStep[] }[] = []
117
- for (const chain of chains)
118
- out.push({ id: chain.id, name: chain.name, steps: await planUpgrade(db, chain.plan) })
119
- return out
120
- }
121
-
122
- export interface BundleTablesReport {
123
- id: string
124
- name: string
125
- pending: { name: string; kind: string; release: string | null }[]
126
- /** What has run here since the bundle was last purged, oldest first. */
127
- applied: { name: string; kind: string; release: string | null; appliedAt: string }[]
128
- }
129
-
130
- /** Each chain's steps, applied and pending, as the Changes dashboard shows them. */
131
- export async function bundleTablesReport(
132
- db: Db,
133
- chains: readonly BundleChain[],
134
- ): Promise<BundleTablesReport[]> {
135
- const ledger = await readLedger(db)
136
- const out: BundleTablesReport[] = []
137
- for (const chain of chains) {
138
- const rows = ledger.filter((row) => row.bundle === chain.id)
139
- const purged = rows.map((row) => row.kind).lastIndexOf('purge')
140
- const releases = new Map(chain.compiled.steps.map((step) => [step.name, step.release]))
141
- out.push({
142
- id: chain.id,
143
- name: chain.name,
144
- pending: (await pendingMigrations(db, chain.plan)).map((step) => ({
145
- name: step.name,
146
- kind: step.kind ?? 'expand',
147
- release: step.release ?? null,
148
- })),
149
- applied: rows
150
- .slice(purged + 1)
151
- .filter((row) => row.kind === 'expand' || row.kind === 'contract')
152
- .map((row) => ({
153
- name: row.name,
154
- kind: row.kind,
155
- release: releases.get(row.name) ?? null,
156
- appliedAt: row.appliedAt,
157
- })),
158
- })
159
- }
160
- return out
161
- }