@crombolo/server 0.63.0 → 0.65.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.
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,23 +60,42 @@ 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
- import { resolveEmailPort } from './email.ts'
87
+ import { emailReady } from './email.ts'
88
+ import { siteEmail } from './email-settings.ts'
70
89
  import { createActivityRecorder, personOf, timed } from './extension-activity.ts'
71
90
  import { createExtensionComponents } from './extension-components.ts'
72
91
  import {
73
92
  entryCovers,
74
93
  extensionEntryProblems,
75
94
  readRecordedExtensions,
95
+ startExtension,
76
96
  startExtensions,
77
97
  } from './extension-discovery.ts'
98
+ import type { ExtensionProcess } from './extension-process.ts'
78
99
  import { createFormRegistry, formSigningSecret, signFormToken } from './form-submit.ts'
79
100
  import { formTypesOf } from './form-types.ts'
80
101
  import { createWorkflowRunner } from './form-workflows.ts'
@@ -131,6 +152,25 @@ export interface CoreHooks {
131
152
  streamMemberFile?: (src: string, search: URLSearchParams) => Promise<Response>
132
153
  /** The site's name as its settings give it, for the e-mails a form sends. */
133
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
134
174
  }
135
175
 
136
176
  /**
@@ -460,15 +500,14 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
460
500
  // Before the poller, which tells it to look again on a `views` instruction
461
501
  // from another node: a closure over a `const` declared later would be a
462
502
  // temporal dead zone waiting for the first instruction to land.
463
- const extensionComponents = createExtensionComponents(
464
- extensionProcesses.map((process) => ({
465
- process,
466
- granted: () => bundleGrants.granted(process.id),
467
- layout: () =>
468
- typeof process.settings.layout === 'string' ? process.settings.layout : undefined,
469
- log: bundleLog(process.id),
470
- })),
471
- )
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))
472
511
  const renderer = new Renderer({
473
512
  cache,
474
513
  componentsDir: config.componentsDir,
@@ -492,10 +531,11 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
492
531
  )
493
532
  // Resolved once: constructing it twice would warn twice about a provider that
494
533
  // is half-configured, and the adapters are cheap but not free of side effects.
495
- const email = tracedEmail(resolveEmailPort(config))
534
+ // Story 340: the config's, or one that follows Settings without a restart.
535
+ const email = tracedEmail(await siteEmail(db, config))
496
536
  // Story 045: a change queues the e-mails its subscribers asked for. Nothing is
497
537
  // queued on a site that cannot send; development sends to the console.
498
- const notifier = createContentNotifier(db, { canSend: Boolean(email) })
538
+ const notifier = createContentNotifier(db, { canSend: () => emailReady(email) })
499
539
  const mediaFiles = new MediaFileStore(mediaStore)
500
540
  const webhooks = createWebhookService({
501
541
  db,
@@ -637,128 +677,125 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
637
677
  })()
638
678
  let bundleMedia: BundleMediaFactory | undefined
639
679
  let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
640
- const bundles =
641
- config.bundles.length > 0
642
- ? createServerBundles({
643
- activity,
644
- bundles: config.bundles,
645
- packages: bundlePackages,
646
- coreVersion: VERSION,
647
- database: (bundle) => {
648
- const chain = chains.find((candidate) => candidate.id === bundle.id)
649
- return chain ? databaseFor(chain) : undefined
650
- },
651
- isOn: (bundleId) => bundleGrants.isOn(bundleId),
652
- granted: (bundleId) => bundleGrants.granted(bundleId),
653
- jobs: (bundleId, queuedBy) => jobRunner.jobsFor(bundleId, queuedBy),
654
- pluginApiPath: `${paths.pluginPath}/api`,
655
- host: {
656
- redirects: createBundleRedirects({ db, cache }),
657
- documents: {
658
- url: async (key, culture) => {
659
- const content = await cache.byKey(key, culture ?? null)
660
- return content && content.url !== '#' ? content.url : undefined
661
- },
662
- },
663
- log: bundleLog('bundle'),
664
- 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
665
752
  },
666
- log: (id) => bundleLog(id),
667
- callerHost: {
668
- // Story 305: each change audited as the person, by the extension.
669
- identityProviders: (caller, bundle) =>
670
- identityProvidersFor(async (action, provider, detail) => {
671
- const person = personOf(caller)
672
- const name = bundlePackages.find((pkg) => pkg.id === bundle.id)?.name ?? bundle.id
673
- await recordAudit(db, {
674
- category: 'settings',
675
- action,
676
- source: 'request',
677
- userKey: person.personKey,
678
- userName: person.personName,
679
- entityType: 'IdentityProvider',
680
- entityKey: `${provider.audience}:${provider.id}`,
681
- entityName: provider.name,
682
- detail: attributed(name, person.personName, detail),
683
- })
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,
684
777
  }),
685
- // Story 308: the site's areas, as the extension; story 325, or as the person using it.
686
- api: (caller, bundle) => {
687
- const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
688
- const granted = () => bundleGrants.granted(bundle.id)
689
- return createBundleApi({
690
- bundleId: bundle.id,
691
- bundleName: pkg?.name ?? bundle.id,
692
- activity: { recorder: activity, person: personOf(caller) },
693
- origin: (config.applicationUrl || 'http://localhost').replace(/\/+$/, ''),
694
- backOfficePath: config.backOfficePath,
695
- granted,
696
- dispatch: () => bundleDispatch,
697
- principal: async () => {
698
- const itself = extensionPrincipal(
699
- { id: bundle.id, name: pkg?.name ?? bundle.id },
700
- granted(),
701
- )
702
- if (!pkg || !granted().includes(USER_DELEGATE)) return itself
703
- if (caller.kind === 'backoffice') return caller.principal
704
- // A job or an event acts for whoever granted it; a visitor never borrows anyone.
705
- const key =
706
- caller.kind === 'job' ? bundleGrants.state(pkg).grant?.delegateKey : null
707
- const installer = key ? await userPrincipalByKey(db, key) : undefined
708
- if (key && !installer)
709
- bundleLog(bundle.id).warn(
710
- 'It acts for whoever granted it, {key}, who is no longer a user: it acts as itself.',
711
- { key },
712
- )
713
- return installer ?? itself
714
- },
715
- })
716
- },
717
- fetch: (_caller, bundle) => {
718
- const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
719
- return {
720
- fetch: async (input, init) => {
721
- const url = new URL(input instanceof Request ? input.url : String(input))
722
- const origins = declaredOrigins(pkg)
723
- const event = {
724
- extensionId: bundle.id,
725
- ...personOf(_caller),
726
- kind: 'request' as const,
727
- area: url.host,
728
- verb: (init?.method ?? 'GET').toUpperCase(),
729
- }
730
- if (!origins.includes(url.origin)) {
731
- activity.record({ ...event, kind: 'refused', outcome: 'refused' })
732
- throw new OutboundRefused(
733
- `${bundle.id} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
734
- )
735
- }
736
- return timed(activity, event, () =>
737
- pinnedFetch(input, init, {
738
- allowPrivateAddresses: config.allowPrivateAddresses,
739
- }),
740
- )
741
- },
742
- }
743
- },
744
- media: (caller, bundle) => {
745
- bundleMedia ??= createBundleMedia({
746
- db,
747
- operations: operations.media,
748
- files: mediaFiles,
749
- cache: mediaCache,
750
- folders: (id) => bundleMediaFolders.get(id) ?? [],
751
- bundleName: (id) => bundles?.mounted.find((b) => b.id === id)?.name ?? id,
752
- stream: (src, search) =>
753
- hooks.streamMemberFile?.(src, search) ??
754
- Promise.resolve(new Response(null, { status: 404 })),
755
- })
756
- return bundleMedia(caller, bundle)
757
- },
778
+ )
758
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 })),
759
793
  })
760
- : undefined
761
- if (bundles) {
794
+ return bundleMedia(caller, bundle)
795
+ },
796
+ },
797
+ })
798
+ {
762
799
  // A declared folder that is not there would fail on the first upload; the
763
800
  // boot says so instead, naming the bundle and the path.
764
801
  const names = new Map(bundles.mounted.map((bundle) => [bundle.id, bundle.name]))
@@ -774,6 +811,171 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
774
811
  bundleMediaFolders = resolved.folders
775
812
  }
776
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
+
777
979
  const poller = new CacheInstructionPoller({
778
980
  db,
779
981
  nodeId: schema.nodeId,
@@ -783,6 +985,10 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
783
985
  // definitions. `views` changes the code that renders it, which is a new
784
986
  // snapshot rather than anything in the published cache.
785
987
  onInstruction: (kind, payload) => {
988
+ if (kind === 'extensions') {
989
+ if (typeof payload.id === 'string') void settle(payload.id)
990
+ return
991
+ }
786
992
  if (kind === 'public-files') return hooks.onSiteFiles?.('public')
787
993
  if (kind !== 'components') return cache.invalidate()
788
994
  // The hash only says when to stop looking eagerly; the snapshot is always
@@ -878,7 +1084,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
878
1084
  id: bundle.id,
879
1085
  handlers: new Map(Object.entries(bundle.jobs ?? {})) as Map<string, JobHandler>,
880
1086
  schedules: bundle.schedules ?? [],
881
- context: () => ({ bundle: bundles?.jobContext(bundle.id) }),
1087
+ context: () => ({ bundle: bundles.jobContext(bundle.id) }),
882
1088
  on: () => bundleGrants.isOn(bundle.id),
883
1089
  })),
884
1090
  ]
@@ -937,9 +1143,29 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
937
1143
  activity,
938
1144
  /** Stops one extension's process on this node, as removing it does (story 328). */
939
1145
  async stopExtension(id: string) {
940
- await Promise.all(
941
- 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
+ }),
942
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
943
1169
  },
944
1170
  /** The server's own handler, which `api` calls through once the server is built (story 308). */
945
1171
  setBundleDispatch(dispatch: (request: Request) => Promise<Response>) {
@@ -4,7 +4,7 @@
4
4
  * The alternative is an operator finding out when an invitation never arrives,
5
5
  * which is the worst moment and the hardest to diagnose: nothing errored.
6
6
  */
7
- import type { EmailAvailability } from './email.ts'
7
+ import { EMAIL_SETUP_HINT, type EmailAvailability } from './email.ts'
8
8
 
9
9
  export interface EmailNoticeLog {
10
10
  info(message: string, properties?: Record<string, unknown>): void
@@ -28,7 +28,7 @@ export function noticeAboutEmail(
28
28
  const message = 'No e-mail provider is configured, so {affected} unavailable. {hint}'
29
29
  const properties = {
30
30
  affected: `${availability.affects.join(', ')} ${availability.affects.length === 1 ? 'is' : 'are'}`,
31
- hint: availability.reason,
31
+ hint: `Set one up in Settings, under E-mail, or: ${EMAIL_SETUP_HINT}`,
32
32
  }
33
33
  // In development this is the expected state and not worth a warning.
34
34
  if (options.development) log.info(message, properties)