@crombolo/server 0.64.0 → 0.66.0

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 (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
@@ -6,7 +6,12 @@
6
6
  * the running nodes instead.
7
7
  */
8
8
 
9
- import type { DocumentOperations, EventSink, MediaOperations } from '@crombolo/content'
9
+ import type {
10
+ DocumentOperations,
11
+ ElementOperations,
12
+ EventSink,
13
+ MediaOperations,
14
+ } from '@crombolo/content'
10
15
  import { currentSchemaState, type Db } from '@crombolo/data'
11
16
  import { PublishedCache } from '@crombolo/render'
12
17
  import { createPublishedContentSource } from './adapters/documents.ts'
@@ -90,3 +95,23 @@ export async function siteMediaOperations(
90
95
  webhooks,
91
96
  }).media
92
97
  }
98
+
99
+ /**
100
+ * Library operations for a process that is not serving requests (story 361): the
101
+ * same rules and audit entries as the back office's. Its cache instructions are
102
+ * the command line's, so a running server refreshes its pages and menus.
103
+ */
104
+ export async function siteElementOperations(
105
+ db: Db,
106
+ config: CromboloConfig,
107
+ ): Promise<ElementOperations> {
108
+ const state = await currentSchemaState(db)
109
+ return createNodeOperations({
110
+ db,
111
+ config,
112
+ nodeState: { version: state.version, revision: state.revision },
113
+ nodeId: config.nodeId,
114
+ instructedBy: `cli:${config.nodeId}`,
115
+ mediaFiles: new MediaFileStore(await mediaStoreFor(config)),
116
+ }).elements
117
+ }
package/src/core.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  BACKOFFICE_CODE,
10
10
  BACKOFFICE_CODE_WARNING,
11
11
  BUNDLE_PERMISSIONS,
12
+ type BundlePackage,
12
13
  createBackOfficePaths,
13
14
  createExtensionRegistry,
14
15
  USER_DELEGATE,
@@ -17,6 +18,7 @@ import { mediaJobHandlers } from '@crombolo/content'
17
18
  import { ObjectTypes } from '@crombolo/core'
18
19
  import {
19
20
  appendCacheInstruction,
21
+ ExtensionSettingRepository,
20
22
  type JobWake,
21
23
  notifyJobs,
22
24
  OwnerSetupNeededError,
@@ -58,13 +60,29 @@ import {
58
60
  type ResolvedMediaFolder,
59
61
  resolveBundleMediaFolders,
60
62
  } from './bundle-media.ts'
61
- import { createBundleRedirects, createServerBundles, validateServerBundles } from './bundles.ts'
63
+ import {
64
+ createBundleRedirects,
65
+ createServerBundles,
66
+ type ServerBundle,
67
+ type ServerBundles,
68
+ validateServerBundles,
69
+ } from './bundles.ts'
62
70
  import { type CromboloConfig, VERSION } from './config.ts'
63
71
  import { createContentDispatcher } from './content-dispatch.ts'
64
72
  import { createContentEventSink } from './content-events.ts'
65
73
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
66
- import { databaseFor, openTables, siteTablesProblems, tablesChains } from './custom-tables.ts'
67
- import { attachDatabase, bootstrapDatabase } from './database.ts'
74
+ import {
75
+ closeTables,
76
+ databaseFor,
77
+ migrateTables,
78
+ openTables,
79
+ pendingTablesSteps,
80
+ siteTablesProblems,
81
+ type TablesChain,
82
+ TablesNotReadyError,
83
+ tablesChains,
84
+ } from './custom-tables.ts'
85
+ import { attachDatabase, bootstrapDatabase, UpgradePendingError } from './database.ts'
68
86
  import { createDiagnostics } from './diagnostics.ts'
69
87
  import { emailReady } from './email.ts'
70
88
  import { siteEmail } from './email-settings.ts'
@@ -74,8 +92,10 @@ import {
74
92
  entryCovers,
75
93
  extensionEntryProblems,
76
94
  readRecordedExtensions,
95
+ startExtension,
77
96
  startExtensions,
78
97
  } from './extension-discovery.ts'
98
+ import type { ExtensionProcess } from './extension-process.ts'
79
99
  import { createFormRegistry, formSigningSecret, signFormToken } from './form-submit.ts'
80
100
  import { formTypesOf } from './form-types.ts'
81
101
  import { createWorkflowRunner } from './form-workflows.ts'
@@ -132,6 +152,25 @@ export interface CoreHooks {
132
152
  streamMemberFile?: (src: string, search: URLSearchParams) => Promise<Response>
133
153
  /** The site's name as its settings give it, for the e-mails a form sends. */
134
154
  siteName?: () => Promise<string>
155
+ /** An extension was started, stopped or unmounted on this node while it runs (story 346). */
156
+ onExtensionsChanged?: () => void
157
+ }
158
+
159
+ /** A site route as the server's route table holds it. */
160
+ type DeclaredRoute = ReturnType<ServerBundles['siteRoutes']>[number]
161
+
162
+ /** Where the server's route table takes an extension's site routes while it runs (story 346). */
163
+ export interface LiveRouteTable {
164
+ /** Why these routes cannot be added beside those there now; nothing when they can. */
165
+ problems(entries: readonly DeclaredRoute[]): string[]
166
+ add(entries: readonly DeclaredRoute[]): string[]
167
+ remove(owner: string): void
168
+ }
169
+
170
+ /** Whether an extension runs on this node, or why it could not start (story 346). */
171
+ export interface ExtensionRunning {
172
+ running: boolean
173
+ reason?: string
135
174
  }
136
175
 
137
176
  /**
@@ -461,15 +500,14 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
461
500
  // Before the poller, which tells it to look again on a `views` instruction
462
501
  // from another node: a closure over a `const` declared later would be a
463
502
  // temporal dead zone waiting for the first instruction to land.
464
- const extensionComponents = createExtensionComponents(
465
- extensionProcesses.map((process) => ({
466
- process,
467
- granted: () => bundleGrants.granted(process.id),
468
- layout: () =>
469
- typeof process.settings.layout === 'string' ? process.settings.layout : undefined,
470
- log: bundleLog(process.id),
471
- })),
472
- )
503
+ const componentSource = (process: ExtensionProcess) => ({
504
+ process,
505
+ granted: () => bundleGrants.granted(process.id),
506
+ layout: () =>
507
+ typeof process.settings.layout === 'string' ? process.settings.layout : undefined,
508
+ log: bundleLog(process.id),
509
+ })
510
+ const extensionComponents = createExtensionComponents(extensionProcesses.map(componentSource))
473
511
  const renderer = new Renderer({
474
512
  cache,
475
513
  componentsDir: config.componentsDir,
@@ -639,128 +677,125 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
639
677
  })()
640
678
  let bundleMedia: BundleMediaFactory | undefined
641
679
  let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
642
- const bundles =
643
- config.bundles.length > 0
644
- ? createServerBundles({
645
- activity,
646
- bundles: config.bundles,
647
- packages: bundlePackages,
648
- coreVersion: VERSION,
649
- database: (bundle) => {
650
- const chain = chains.find((candidate) => candidate.id === bundle.id)
651
- return chain ? databaseFor(chain) : undefined
652
- },
653
- isOn: (bundleId) => bundleGrants.isOn(bundleId),
654
- granted: (bundleId) => bundleGrants.granted(bundleId),
655
- jobs: (bundleId, queuedBy) => jobRunner.jobsFor(bundleId, queuedBy),
656
- pluginApiPath: `${paths.pluginPath}/api`,
657
- host: {
658
- redirects: createBundleRedirects({ db, cache }),
659
- documents: {
660
- url: async (key, culture) => {
661
- const content = await cache.byKey(key, culture ?? null)
662
- return content && content.url !== '#' ? content.url : undefined
663
- },
664
- },
665
- log: bundleLog('bundle'),
666
- identityProviders: identityProvidersFor(),
680
+ // Made even with none, so an extension granted while the site runs mounts here (story 346).
681
+ const bundles = createServerBundles({
682
+ activity,
683
+ bundles: config.bundles,
684
+ packages: bundlePackages,
685
+ coreVersion: VERSION,
686
+ database: (bundle) => {
687
+ const chain = chains.find((candidate) => candidate.id === bundle.id)
688
+ return chain ? databaseFor(chain) : undefined
689
+ },
690
+ isOn: (bundleId) => bundleGrants.isOn(bundleId),
691
+ granted: (bundleId) => bundleGrants.granted(bundleId),
692
+ jobs: (bundleId, queuedBy) => jobRunner.jobsFor(bundleId, queuedBy),
693
+ pluginApiPath: `${paths.pluginPath}/api`,
694
+ host: {
695
+ redirects: createBundleRedirects({ db, cache }),
696
+ documents: {
697
+ url: async (key, culture) => {
698
+ const content = await cache.byKey(key, culture ?? null)
699
+ return content && content.url !== '#' ? content.url : undefined
700
+ },
701
+ },
702
+ log: bundleLog('bundle'),
703
+ identityProviders: identityProvidersFor(),
704
+ },
705
+ log: (id) => bundleLog(id),
706
+ callerHost: {
707
+ // Story 305: each change audited as the person, by the extension.
708
+ identityProviders: (caller, bundle) =>
709
+ identityProvidersFor(async (action, provider, detail) => {
710
+ const person = personOf(caller)
711
+ const name = bundlePackages.find((pkg) => pkg.id === bundle.id)?.name ?? bundle.id
712
+ await recordAudit(db, {
713
+ category: 'settings',
714
+ action,
715
+ source: 'request',
716
+ userKey: person.personKey,
717
+ userName: person.personName,
718
+ entityType: 'IdentityProvider',
719
+ entityKey: `${provider.audience}:${provider.id}`,
720
+ entityName: provider.name,
721
+ detail: attributed(name, person.personName, detail),
722
+ })
723
+ }),
724
+ // Story 308: the site's areas, as the extension; story 325, or as the person using it.
725
+ api: (caller, bundle) => {
726
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
727
+ const granted = () => bundleGrants.granted(bundle.id)
728
+ return createBundleApi({
729
+ bundleId: bundle.id,
730
+ bundleName: pkg?.name ?? bundle.id,
731
+ activity: { recorder: activity, person: personOf(caller) },
732
+ origin: (config.applicationUrl || 'http://localhost').replace(/\/+$/, ''),
733
+ backOfficePath: config.backOfficePath,
734
+ granted,
735
+ dispatch: () => bundleDispatch,
736
+ principal: async () => {
737
+ const itself = extensionPrincipal(
738
+ { id: bundle.id, name: pkg?.name ?? bundle.id },
739
+ granted(),
740
+ )
741
+ if (!pkg || !granted().includes(USER_DELEGATE)) return itself
742
+ if (caller.kind === 'backoffice') return caller.principal
743
+ // A job or an event acts for whoever granted it; a visitor never borrows anyone.
744
+ const key = caller.kind === 'job' ? bundleGrants.state(pkg).grant?.delegateKey : null
745
+ const installer = key ? await userPrincipalByKey(db, key) : undefined
746
+ if (key && !installer)
747
+ bundleLog(bundle.id).warn(
748
+ 'It acts for whoever granted it, {key}, who is no longer a user: it acts as itself.',
749
+ { key },
750
+ )
751
+ return installer ?? itself
667
752
  },
668
- log: (id) => bundleLog(id),
669
- callerHost: {
670
- // Story 305: each change audited as the person, by the extension.
671
- identityProviders: (caller, bundle) =>
672
- identityProvidersFor(async (action, provider, detail) => {
673
- const person = personOf(caller)
674
- const name = bundlePackages.find((pkg) => pkg.id === bundle.id)?.name ?? bundle.id
675
- await recordAudit(db, {
676
- category: 'settings',
677
- action,
678
- source: 'request',
679
- userKey: person.personKey,
680
- userName: person.personName,
681
- entityType: 'IdentityProvider',
682
- entityKey: `${provider.audience}:${provider.id}`,
683
- entityName: provider.name,
684
- detail: attributed(name, person.personName, detail),
685
- })
753
+ })
754
+ },
755
+ fetch: (_caller, bundle) => {
756
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
757
+ return {
758
+ fetch: async (input, init) => {
759
+ const url = new URL(input instanceof Request ? input.url : String(input))
760
+ const origins = declaredOrigins(pkg)
761
+ const event = {
762
+ extensionId: bundle.id,
763
+ ...personOf(_caller),
764
+ kind: 'request' as const,
765
+ area: url.host,
766
+ verb: (init?.method ?? 'GET').toUpperCase(),
767
+ }
768
+ if (!origins.includes(url.origin)) {
769
+ activity.record({ ...event, kind: 'refused', outcome: 'refused' })
770
+ throw new OutboundRefused(
771
+ `${bundle.id} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
772
+ )
773
+ }
774
+ return timed(activity, event, () =>
775
+ pinnedFetch(input, init, {
776
+ allowPrivateAddresses: config.allowPrivateAddresses,
686
777
  }),
687
- // Story 308: the site's areas, as the extension; story 325, or as the person using it.
688
- api: (caller, bundle) => {
689
- const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
690
- const granted = () => bundleGrants.granted(bundle.id)
691
- return createBundleApi({
692
- bundleId: bundle.id,
693
- bundleName: pkg?.name ?? bundle.id,
694
- activity: { recorder: activity, person: personOf(caller) },
695
- origin: (config.applicationUrl || 'http://localhost').replace(/\/+$/, ''),
696
- backOfficePath: config.backOfficePath,
697
- granted,
698
- dispatch: () => bundleDispatch,
699
- principal: async () => {
700
- const itself = extensionPrincipal(
701
- { id: bundle.id, name: pkg?.name ?? bundle.id },
702
- granted(),
703
- )
704
- if (!pkg || !granted().includes(USER_DELEGATE)) return itself
705
- if (caller.kind === 'backoffice') return caller.principal
706
- // A job or an event acts for whoever granted it; a visitor never borrows anyone.
707
- const key =
708
- caller.kind === 'job' ? bundleGrants.state(pkg).grant?.delegateKey : null
709
- const installer = key ? await userPrincipalByKey(db, key) : undefined
710
- if (key && !installer)
711
- bundleLog(bundle.id).warn(
712
- 'It acts for whoever granted it, {key}, who is no longer a user: it acts as itself.',
713
- { key },
714
- )
715
- return installer ?? itself
716
- },
717
- })
718
- },
719
- fetch: (_caller, bundle) => {
720
- const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
721
- return {
722
- fetch: async (input, init) => {
723
- const url = new URL(input instanceof Request ? input.url : String(input))
724
- const origins = declaredOrigins(pkg)
725
- const event = {
726
- extensionId: bundle.id,
727
- ...personOf(_caller),
728
- kind: 'request' as const,
729
- area: url.host,
730
- verb: (init?.method ?? 'GET').toUpperCase(),
731
- }
732
- if (!origins.includes(url.origin)) {
733
- activity.record({ ...event, kind: 'refused', outcome: 'refused' })
734
- throw new OutboundRefused(
735
- `${bundle.id} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
736
- )
737
- }
738
- return timed(activity, event, () =>
739
- pinnedFetch(input, init, {
740
- allowPrivateAddresses: config.allowPrivateAddresses,
741
- }),
742
- )
743
- },
744
- }
745
- },
746
- media: (caller, bundle) => {
747
- bundleMedia ??= createBundleMedia({
748
- db,
749
- operations: operations.media,
750
- files: mediaFiles,
751
- cache: mediaCache,
752
- folders: (id) => bundleMediaFolders.get(id) ?? [],
753
- bundleName: (id) => bundles?.mounted.find((b) => b.id === id)?.name ?? id,
754
- stream: (src, search) =>
755
- hooks.streamMemberFile?.(src, search) ??
756
- Promise.resolve(new Response(null, { status: 404 })),
757
- })
758
- return bundleMedia(caller, bundle)
759
- },
778
+ )
760
779
  },
780
+ }
781
+ },
782
+ media: (caller, bundle) => {
783
+ bundleMedia ??= createBundleMedia({
784
+ db,
785
+ operations: operations.media,
786
+ files: mediaFiles,
787
+ cache: mediaCache,
788
+ folders: (id) => bundleMediaFolders.get(id) ?? [],
789
+ bundleName: (id) => bundles.mounted.find((b) => b.id === id)?.name ?? id,
790
+ stream: (src, search) =>
791
+ hooks.streamMemberFile?.(src, search) ??
792
+ Promise.resolve(new Response(null, { status: 404 })),
761
793
  })
762
- : undefined
763
- if (bundles) {
794
+ return bundleMedia(caller, bundle)
795
+ },
796
+ },
797
+ })
798
+ {
764
799
  // A declared folder that is not there would fail on the first upload; the
765
800
  // boot says so instead, naming the bundle and the path.
766
801
  const names = new Map(bundles.mounted.map((bundle) => [bundle.id, bundle.name]))
@@ -776,6 +811,171 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
776
811
  bundleMediaFolders = resolved.folders
777
812
  }
778
813
 
814
+ let routeTable: LiveRouteTable | undefined
815
+ /** The site routes a bundle declares, as the route table checks them, before it is mounted. */
816
+ const siteRoutesOf = (bundle: ServerBundle): DeclaredRoute[] =>
817
+ (bundle.routes ?? [])
818
+ .filter((route) => route?.options && route.options.audience !== 'backoffice')
819
+ .map((route) => ({
820
+ route: route as DeclaredRoute['route'],
821
+ owner: `the bundle ${bundle.id}`,
822
+ }))
823
+ /** The extension's tables, made and migrated where this node owns writes, as at boot. */
824
+ const tablesOf = async (
825
+ bundle: ServerBundle,
826
+ pkg: BundlePackage,
827
+ ): Promise<TablesChain | undefined> => {
828
+ if (!bundle.tables) return undefined
829
+ const kept = chains.find((chain) => chain.id === bundle.id)
830
+ if (kept) return kept
831
+ const [chain] = tablesChains({ ...config, database: undefined }, [bundle], [pkg])
832
+ if (!chain || config.role === 'web') return chain
833
+ const pending = (await pendingTablesSteps(db, [chain]))[0]?.pending ?? []
834
+ if (owns) {
835
+ if (pending.length > 0 && !config.development)
836
+ throw new UpgradePendingError([], [{ id: bundle.id, steps: pending.map((m) => m.name) }])
837
+ await migrateTables(db, config, [chain], { by: config.nodeId })
838
+ } else {
839
+ if (pending.length > 0) throw new TablesNotReadyError(bundle.id)
840
+ await openTables(db, config, [chain], { provision: false })
841
+ }
842
+ return chain
843
+ }
844
+ /** Takes an extension out of everything that serves it; its tables too, unless kept. */
845
+ const unmount = async (id: string, options: { keepTables: boolean }) => {
846
+ bundles.remove(id)
847
+ routeTable?.remove(`the bundle ${id}`)
848
+ extensionComponents.remove(id)
849
+ bundleMediaFolders.delete(id)
850
+ const at = config.bundles.findIndex((bundle) => bundle.id === id)
851
+ if (at >= 0) config.bundles.splice(at, 1)
852
+ if (options.keepTables) return
853
+ const chain = chains.findIndex((candidate) => candidate.id === id)
854
+ if (chain < 0) return
855
+ const [closing] = chains.splice(chain, 1)
856
+ if (closing) await closeTables([closing]).catch(() => {})
857
+ }
858
+ const stopProcess = async (id: string) => {
859
+ const stopping = extensionProcesses.filter((process) => process.id === id)
860
+ for (const process of stopping)
861
+ extensionProcesses.splice(extensionProcesses.indexOf(process), 1)
862
+ await Promise.all(stopping.map((process) => process.stop()))
863
+ }
864
+ const setFailed = (id: string, reason?: string) => {
865
+ for (let at = failedExtensions.length - 1; at >= 0; at--)
866
+ if (failedExtensions[at]?.id === id) failedExtensions.splice(at, 1)
867
+ if (reason) failedExtensions.push({ id, reason })
868
+ }
869
+ /** Starts an extension and wires it into everything boot wires it into, checked as boot checks it. */
870
+ const startLive = async (pkg: BundlePackage): Promise<ExtensionRunning> => {
871
+ const started = await startExtension(
872
+ config,
873
+ pkg,
874
+ {
875
+ grant: bundleGrants.state(pkg).grant,
876
+ settings: await new ExtensionSettingRepository(db).of(pkg.id).catch(() => ({})),
877
+ },
878
+ bundleLog(pkg.id),
879
+ activity,
880
+ )
881
+ if (started.status === 'not-granted') return { running: false }
882
+ if (started.status === 'failed') {
883
+ setFailed(pkg.id, started.reason)
884
+ return { running: false, reason: started.reason }
885
+ }
886
+ const { bundle, process } = started
887
+ const name = (id: string) => (id === pkg.id ? pkg.name : id)
888
+ try {
889
+ // One turned off keeps its routes, answering "Turned off"; on again, its new process takes them.
890
+ await unmount(pkg.id, { keepTables: true })
891
+ const problems = [
892
+ ...validateServerBundles([bundle], [pkg], VERSION),
893
+ ...bundleEventProblems([bundle]),
894
+ ...(routeTable?.problems(siteRoutesOf(bundle)) ?? []),
895
+ ]
896
+ const media = await resolveBundleMediaFolders(db, [bundle], name)
897
+ problems.push(...media.problems)
898
+ if (problems.length > 0) throw new Error(problems.join(' '))
899
+ const chain = await tablesOf(bundle, pkg)
900
+ // Nothing awaited from here, so no request sees it half mounted.
901
+ const mounted = bundles.add(bundle, pkg)
902
+ const routed = mounted.length > 0 ? [] : (routeTable?.add(bundles.siteRoutes(pkg.id)) ?? [])
903
+ if (mounted.length + routed.length > 0) {
904
+ bundles.remove(pkg.id)
905
+ throw new Error([...mounted, ...routed].join(' '))
906
+ }
907
+ if (chain && !chains.includes(chain)) chains.push(chain)
908
+ const known = bundlePackages.findIndex((candidate) => candidate.id === pkg.id)
909
+ if (known >= 0) bundlePackages.splice(known, 1, pkg)
910
+ else bundlePackages.push(pkg)
911
+ config.bundles.push(bundle)
912
+ for (const [id, folders] of media.folders) bundleMediaFolders.set(id, folders)
913
+ extensionProcesses.push(process)
914
+ extensionComponents.add(componentSource(process))
915
+ setFailed(pkg.id)
916
+ bundleLog(pkg.id).info('{package} started, with no restart', { package: pkg.packageName })
917
+ return { running: true }
918
+ } catch (error) {
919
+ await process.stop()
920
+ const reason = error instanceof Error ? error.message : String(error)
921
+ setFailed(pkg.id, reason)
922
+ bundleLog(pkg.id).error(
923
+ '{package} could not be started, and the site runs without it: {reason}',
924
+ {
925
+ package: pkg.packageName,
926
+ reason,
927
+ },
928
+ )
929
+ return { running: false, reason }
930
+ }
931
+ }
932
+ /**
933
+ * Brings one extension on this node to what its grant says now (story 346):
934
+ * started and mounted when granted and on, its process stopped when off (its
935
+ * routes stay, answering "Turned off"), unmounted when it is no longer installed.
936
+ */
937
+ const reconcile = async (id: string): Promise<ExtensionRunning> => {
938
+ const running = () => extensionProcesses.some((process) => process.id === id)
939
+ // The site's own code, imported the old way, runs in this process from boot to boot.
940
+ if (wiredByImport.has(id)) return { running: true }
941
+ extensions.invalidate()
942
+ await bundleGrants.refresh()
943
+ const pkg = extensions.bundles().bundles.find((candidate) => candidate.id === id)
944
+ if (!pkg?.carries.server) {
945
+ await stopProcess(id)
946
+ await unmount(id, { keepTables: false })
947
+ setFailed(id)
948
+ return { running: false }
949
+ }
950
+ const state = bundleGrants.state(pkg)
951
+ const want = state.on || (entryCovers(pkg, config.extensions?.[id]) && !state.grant?.disabledAt)
952
+ if (!want) {
953
+ await stopProcess(id)
954
+ setFailed(id)
955
+ return { running: false }
956
+ }
957
+ if (running()) return { running: true }
958
+ return startLive(pkg)
959
+ }
960
+ /** One at a time for each extension, so a change and the instruction it sends cannot race. */
961
+ const settling = new Map<string, Promise<ExtensionRunning>>()
962
+ const settle = (id: string): Promise<ExtensionRunning> => {
963
+ const next = (settling.get(id) ?? Promise.resolve({ running: false }))
964
+ .catch(() => ({ running: false }))
965
+ .then(() => reconcile(id))
966
+ .finally(() => {
967
+ if (settling.get(id) === next) settling.delete(id)
968
+ hooks.onExtensionsChanged?.()
969
+ })
970
+ .catch((error: unknown) => {
971
+ const reason = error instanceof Error ? error.message : String(error)
972
+ log.error('The extension {id} could not be brought up to date: {reason}', { id, reason })
973
+ return { running: false, reason }
974
+ })
975
+ settling.set(id, next)
976
+ return next
977
+ }
978
+
779
979
  const poller = new CacheInstructionPoller({
780
980
  db,
781
981
  nodeId: schema.nodeId,
@@ -785,6 +985,10 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
785
985
  // definitions. `views` changes the code that renders it, which is a new
786
986
  // snapshot rather than anything in the published cache.
787
987
  onInstruction: (kind, payload) => {
988
+ if (kind === 'extensions') {
989
+ if (typeof payload.id === 'string') void settle(payload.id)
990
+ return
991
+ }
788
992
  if (kind === 'public-files') return hooks.onSiteFiles?.('public')
789
993
  if (kind !== 'components') return cache.invalidate()
790
994
  // The hash only says when to stop looking eagerly; the snapshot is always
@@ -880,7 +1084,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
880
1084
  id: bundle.id,
881
1085
  handlers: new Map(Object.entries(bundle.jobs ?? {})) as Map<string, JobHandler>,
882
1086
  schedules: bundle.schedules ?? [],
883
- context: () => ({ bundle: bundles?.jobContext(bundle.id) }),
1087
+ context: () => ({ bundle: bundles.jobContext(bundle.id) }),
884
1088
  on: () => bundleGrants.isOn(bundle.id),
885
1089
  })),
886
1090
  ]
@@ -939,9 +1143,29 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
939
1143
  activity,
940
1144
  /** Stops one extension's process on this node, as removing it does (story 328). */
941
1145
  async stopExtension(id: string) {
942
- await Promise.all(
943
- extensionProcesses.filter((process) => process.id === id).map((process) => process.stop()),
1146
+ await stopProcess(id)
1147
+ },
1148
+ /**
1149
+ * An extension was granted, turned on or off, or removed (story 346): this
1150
+ * node brings it up to date, and tells the others to. Answers whether it runs here.
1151
+ */
1152
+ async extensionChanged(id: string): Promise<ExtensionRunning> {
1153
+ const now = await settle(id)
1154
+ await appendCacheInstruction(db, {
1155
+ kind: 'extensions',
1156
+ payload: { id },
1157
+ by: schema.nodeId,
1158
+ }).catch((error: unknown) =>
1159
+ log.error('Could not tell the other nodes about the extension {id}: {error}', {
1160
+ id,
1161
+ error: String(error),
1162
+ }),
944
1163
  )
1164
+ return now
1165
+ },
1166
+ /** The server's route table, once it is built, for what an extension started later declares. */
1167
+ setRouteTable(table: LiveRouteTable) {
1168
+ routeTable = table
945
1169
  },
946
1170
  /** The server's own handler, which `api` calls through once the server is built (story 308). */
947
1171
  setBundleDispatch(dispatch: (request: Request) => Promise<Response>) {