@crombolo/server 0.63.0 → 0.64.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.63.0",
3
+ "version": "0.64.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,19 +31,19 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.63.0",
35
- "@crombolo/api-management": "0.63.0",
36
- "@crombolo/auth": "0.63.0",
37
- "@crombolo/backoffice-host": "0.63.0",
38
- "@crombolo/common": "0.63.0",
39
- "@crombolo/content": "0.63.0",
40
- "@crombolo/contracts": "0.63.0",
41
- "@crombolo/core": "0.63.0",
42
- "@crombolo/data": "0.63.0",
43
- "@crombolo/extension": "0.63.0",
44
- "@crombolo/render": "0.63.0",
45
- "@crombolo/schema": "0.63.0",
46
- "@crombolo/transfer": "0.63.0",
34
+ "@crombolo/api-delivery": "0.64.0",
35
+ "@crombolo/api-management": "0.64.0",
36
+ "@crombolo/auth": "0.64.0",
37
+ "@crombolo/backoffice-host": "0.64.0",
38
+ "@crombolo/common": "0.64.0",
39
+ "@crombolo/content": "0.64.0",
40
+ "@crombolo/contracts": "0.64.0",
41
+ "@crombolo/core": "0.64.0",
42
+ "@crombolo/data": "0.64.0",
43
+ "@crombolo/extension": "0.64.0",
44
+ "@crombolo/render": "0.64.0",
45
+ "@crombolo/schema": "0.64.0",
46
+ "@crombolo/transfer": "0.64.0",
47
47
  "@logtape/logtape": "^2.3.8",
48
48
  "@opentelemetry/api": "1.10.0",
49
49
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -43,7 +43,7 @@ import { aliasFromName } from '@crombolo/schema'
43
43
  import { readContentTypeUdt, writeContentTypeUdt } from '../content-type-udt.ts'
44
44
  import { classifyTypeChange } from '../schema-classify.ts'
45
45
  import { contentTypeJsonSchema, schemaForStorage, valueTypeName } from '../value-schemas.ts'
46
- import { createSchemaFileWriter, type SchemaFiles } from './schema-files.ts'
46
+ import { createSchemaFileWriter, type SchemaFiles, schemaProblems } from './schema-files.ts'
47
47
 
48
48
  async function toTreeItems(
49
49
  nodes: NodeRepository,
@@ -150,6 +150,43 @@ export function underSchemaLock<P extends object>(
150
150
  return locked
151
151
  }
152
152
 
153
+ class InvalidSchemaSave extends Error {
154
+ constructor(readonly problems: readonly string[]) {
155
+ super(problems.join('; '))
156
+ }
157
+ }
158
+
159
+ /**
160
+ * A save of a type or data type, in a transaction kept only when it leaves the
161
+ * definitions the schema files are written from no worse than it found them.
162
+ * Otherwise nothing is kept, and the save is refused saying why, so a file is
163
+ * never left behind its row. Problems that were there before are not its own.
164
+ */
165
+ export async function savedIfValid<T>(
166
+ db: Db,
167
+ files: SchemaFiles | undefined,
168
+ work: (tx: Db) => Promise<T>,
169
+ ): Promise<{ ok: true; value: T } | PortFailure> {
170
+ if (!files) return { ok: true, value: await work(db) }
171
+ const before = new Set(await schemaProblems(db, files))
172
+ try {
173
+ const value = await db.transaction(async (tx) => {
174
+ const value = await work(tx)
175
+ const added = (await schemaProblems(tx, files)).filter((p) => !before.has(p))
176
+ if (added.length > 0) throw new InvalidSchemaSave(added)
177
+ return value
178
+ })
179
+ return { ok: true, value }
180
+ } catch (error) {
181
+ if (!(error instanceof InvalidSchemaSave)) throw error
182
+ return {
183
+ ok: false,
184
+ status: 400,
185
+ reason: `This wasn't saved, because the site's definitions would no longer be valid: ${error.problems.join('; ')}`,
186
+ }
187
+ }
188
+ }
189
+
153
190
  export function createFolderPort(
154
191
  folders: FolderRepository,
155
192
  tree: ReturnType<typeof createSettingsTree>,
@@ -221,6 +258,9 @@ export function createContentTypePort(
221
258
  ): ContentTypePort {
222
259
  const kind = options.kind ?? 'document'
223
260
  const repo = new ContentTypeRepository(db, { nodeState: options.nodeState, kind })
261
+ /** The same repository over a transaction's handle, for a checked save. */
262
+ const repoOn = (handle: Db) =>
263
+ new ContentTypeRepository(handle, { nodeState: options.nodeState, kind })
224
264
  const nodes = repo.nodes
225
265
  const objectType = repo.objectType
226
266
  const containerType = CONTENT_TYPE_OBJECT_TYPES[kind].container
@@ -253,10 +293,11 @@ export function createContentTypePort(
253
293
  }
254
294
  const refused = files?.refuse(aggregate)
255
295
  if (refused) return refused
256
- // A new type can only be additive, and the version moves before the write so
257
- // the file that lands carries the version it belongs to.
296
+ const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
297
+ if (!saved.ok) return saved
298
+ // A new type can only be additive, and the version moves before the file is
299
+ // written so the file that lands carries the version it belongs to.
258
300
  await files?.bumpVersion('additive')
259
- await repo.save(aggregate)
260
301
  await files?.write(aggregate)
261
302
  void principal
262
303
  return { ok: true as const }
@@ -271,10 +312,17 @@ export function createContentTypePort(
271
312
  const before = await repo.byKey(key)
272
313
  // Classified here, while the database still holds the old type: once it is
273
314
  // saved there is nothing left to compare it with.
274
- if (files)
275
- await files.bumpVersion(await classifyTypeChange(db, before, { ...aggregate, key }))
315
+ const change = files ? await classifyTypeChange(db, before, { ...aggregate, key }) : 'none'
276
316
  // The editor does not send tree placement; keep what the type has.
277
- await repo.save({ ...aggregate, key, parentKey: before?.parentKey ?? aggregate.parentKey })
317
+ const saved = await savedIfValid(db, schemaFiles, (tx) =>
318
+ repoOn(tx).save({
319
+ ...aggregate,
320
+ key,
321
+ parentKey: before?.parentKey ?? aggregate.parentKey,
322
+ }),
323
+ )
324
+ if (!saved.ok) return saved
325
+ await files?.bumpVersion(change)
278
326
  await files?.write({ ...aggregate, key }, before?.alias)
279
327
  void principal
280
328
  return { ok: true as const }
@@ -360,7 +408,8 @@ export function createContentTypePort(
360
408
  ? saved.key
361
409
  : aggregate.defaultComponentKey,
362
410
  }
363
- await repo.save(updated)
411
+ const kept = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(updated))
412
+ if (!kept.ok) return kept
364
413
  await files?.write(updated)
365
414
  void principal
366
415
  return { ok: true as const, key: saved.key }
@@ -505,7 +554,8 @@ export function createContentTypePort(
505
554
 
506
555
  if (!existing && (await repo.aliasExists(aggregate.alias)))
507
556
  return { status: 'invalid', reason: `The alias '${aggregate.alias}' is already in use.` }
508
- await repo.save(aggregate)
557
+ const saved = await savedIfValid(db, schemaFiles, (tx) => repoOn(tx).save(aggregate))
558
+ if (!saved.ok) return { status: 'invalid', reason: saved.reason }
509
559
  await files?.write(aggregate)
510
560
  return { status: 'ok', key: aggregate.key }
511
561
  },
@@ -608,8 +658,13 @@ export function createDataTypePort(db: Db, schemaFiles?: SchemaFiles): DataTypeP
608
658
  }
609
659
  },
610
660
  async save(model: DataTypeModel) {
611
- const saved = await repo.save(await withAlias(model))
612
- await files?.writeDataType(saved)
661
+ const aliased = await withAlias(model)
662
+ const saved = await savedIfValid(db, schemaFiles, (tx) =>
663
+ new DataTypeRepository(tx).save(aliased),
664
+ )
665
+ if (!saved.ok) return saved
666
+ await files?.writeDataType(saved.value)
667
+ return undefined
613
668
  },
614
669
  async remove(key) {
615
670
  const before = await repo.byKey(key)
@@ -96,7 +96,7 @@ export function createDocumentPort(
96
96
  /** The site's own directory: where `domains.toml` is, when the site keeps one. */
97
97
  siteDir?: string,
98
98
  /** Whether the site can send the e-mails a subscription asks for (story 045). */
99
- notificationsAvailable = true,
99
+ notificationsAvailable: boolean | (() => boolean) = true,
100
100
  ): DocumentPort {
101
101
  const repo = new DocumentRepository(db, options)
102
102
  const domains = new DomainRepository(db)
@@ -442,7 +442,11 @@ export function createDocumentPort(
442
442
  const userId = await userIdOf(principal)
443
443
  if (!node || node.objectType !== repo.objectType || userId === undefined) return 'notFound'
444
444
  // Clearing is always allowed; asking for something the site cannot send is not.
445
- if (!notificationsAvailable) {
445
+ if (
446
+ !(typeof notificationsAvailable === 'function'
447
+ ? notificationsAvailable()
448
+ : notificationsAvailable)
449
+ ) {
446
450
  const had = new Set(await notifications.subscribed(userId, node.id))
447
451
  if (actionIds.some((id) => !had.has(id))) return 'unavailable'
448
452
  }
@@ -72,6 +72,23 @@ export interface SchemaFileWriter {
72
72
  * `schema/content-types/`, media types `schema/media-types/`. Data types,
73
73
  * languages and the rewrite are the same whichever kind asks.
74
74
  */
75
+ /**
76
+ * What is wrong with the definitions as the files would be written from the
77
+ * database `db` sees. A save compares it before and after, inside its
78
+ * transaction, and refuses what it adds, so a file is never left behind its row.
79
+ */
80
+ export async function schemaProblems(db: Db, files: SchemaFiles): Promise<string[]> {
81
+ if (!existsSync(files.schemaDir) || !files.writable) return []
82
+ const set = await exportSchemaSet(
83
+ db,
84
+ loadSchemaDirectory(files.schemaDir, { formTypes: files.formTypes }).set.version,
85
+ )
86
+ return validateSchemaSet(set, {
87
+ componentAliases: files.componentAliases(),
88
+ types: files.formTypes,
89
+ }).map((p) => `${p.file}${p.path ? ` (${p.path})` : ''}: ${p.message}`)
90
+ }
91
+
75
92
  export function createSchemaFileWriter(
76
93
  db: Db,
77
94
  files: SchemaFiles,
@@ -134,18 +151,8 @@ export function createSchemaFileWriter(
134
151
  : (set.memberTypes ?? [])
135
152
  const type = list.find((t) => t.key === aggregate.key)
136
153
  if (!type) return
137
- const problems = validateSchemaSet(set, {
138
- componentAliases: files.componentAliases(),
139
- types: files.formTypes,
140
- })
141
- if (problems.length > 0) {
142
- const detail = problems.map((p) => `${p.file}: ${p.message}`).join('; ')
143
- logger('schema').error('Not writing {file}: {detail}', {
144
- file: fileNameFor(aggregate.alias),
145
- detail,
146
- })
147
- return
148
- }
154
+ // Checked before the save, which `schemaProblems` refuses, so the file always
155
+ // follows the database.
149
156
  mkdirSync(dir, { recursive: true })
150
157
  if (previousAlias && previousAlias !== aggregate.alias)
151
158
  rmSync(fileFor(previousAlias), { force: true })
@@ -172,21 +179,6 @@ export function createSchemaFileWriter(
172
179
  await settle()
173
180
  return
174
181
  }
175
- // The same guard `write` applies to a content type: a set that does not
176
- // validate never reaches the disk, because the file is what every other
177
- // node reads and what a deploy boots from.
178
- const problems = validateSchemaSet(set, {
179
- componentAliases: files.componentAliases(),
180
- types: files.formTypes,
181
- })
182
- if (problems.length > 0) {
183
- const detail = problems.map((p) => `${p.file}: ${p.message}`).join('; ')
184
- logger('schema').error('Not writing {file}: {detail}', {
185
- file: fileNameFor(model.alias),
186
- detail,
187
- })
188
- return
189
- }
190
182
  mkdirSync(join(files.schemaDir, 'data-types'), { recursive: true })
191
183
  writeFileSync(
192
184
  join(files.schemaDir, 'data-types', fileNameFor(model.alias)),
package/src/approvals.ts CHANGED
@@ -47,7 +47,7 @@ import {
47
47
  UserGroupRepository,
48
48
  } from '@crombolo/data'
49
49
  import type { ContentNotifier } from './content-notifications.ts'
50
- import type { EmailPort } from './email.ts'
50
+ import { type EmailPort, emailReady } from './email.ts'
51
51
 
52
52
  /** What publishing and unpublishing go through when approval says yes. */
53
53
  export interface ApprovalPublisher {
@@ -388,7 +388,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
388
388
  subject: string,
389
389
  body: string,
390
390
  ) => {
391
- if (!options.email) return
391
+ if (!emailReady(options.email)) return
392
392
  let emails: string[] = []
393
393
  if (to === 'editor') {
394
394
  const rows = await db.q
package/src/config.ts CHANGED
@@ -91,6 +91,25 @@ export interface RemoteSettings {
91
91
  oidcIssuers?: string[]
92
92
  }
93
93
 
94
+ export type ContentMode = 'development' | 'production'
95
+
96
+ /** `CROMBOLO_CONTENT_MODE`, refusing the switch it replaced so locked files never quietly unlock. */
97
+ function contentModeSetting(): ContentMode {
98
+ // Read directly: it is no longer a setting, only a name to refuse.
99
+ if (Bun.env.CROMBOLO_CONTENT_FILES_READONLY !== undefined)
100
+ throw new Error(
101
+ 'CROMBOLO_CONTENT_FILES_READONLY has gone: set CROMBOLO_CONTENT_MODE to production to keep templates, stylesheets and scripts read-only, or to development (story 343).',
102
+ )
103
+ const value = (setting('CROMBOLO_CONTENT_MODE') ?? 'development').trim().toLowerCase()
104
+ if (value !== 'development' && value !== 'production')
105
+ throw new Error(`CROMBOLO_CONTENT_MODE is "${value}": it is development or production.`)
106
+ return value
107
+ }
108
+
109
+ /** Whether the back office must leave templates, stylesheets and scripts alone. */
110
+ export const contentFilesLocked = (config: Pick<CromboloConfig, 'contentMode'>) =>
111
+ config.contentMode === 'production'
112
+
94
113
  /** `CROMBOLO_REMOTE_ACCESS`, refusing the switch it replaced so a site does not quietly stop being a remote. */
95
114
  function remoteAccessSetting(): RemoteAccess {
96
115
  // Read directly: it is no longer a setting, only a name to refuse.
@@ -342,11 +361,11 @@ export interface CromboloConfig {
342
361
  */
343
362
  schemaWritable: boolean
344
363
  /**
345
- * The back office may not change templates, stylesheets or scripts (story 337):
346
- * for a site whose files come from its repository. Off unless set, in
347
- * production too. `CROMBOLO_CONTENT_FILES_READONLY`.
364
+ * `production` keeps templates, stylesheets and scripts read-only in the back
365
+ * office, for a site whose files come from its repository (stories 337, 343).
366
+ * `development` unless set, in production too. `CROMBOLO_CONTENT_MODE`.
348
367
  */
349
- contentFilesReadOnly: boolean
368
+ contentMode: ContentMode
350
369
  /** Sync `schema/` at boot; a pipeline that runs `crombolo types sync` turns this off. */
351
370
  syncSchemaAtBoot: boolean
352
371
  /** Which database engine; from CROMBOLO_DB. */
@@ -904,7 +923,7 @@ export function loadConfig(
904
923
  ? setting('CROMBOLO_SCHEMA_WRITABLE') === 'true'
905
924
  : setting('NODE_ENV') !== 'production',
906
925
  syncSchemaAtBoot: setting('CROMBOLO_SYNC_SCHEMA_AT_BOOT') !== 'false',
907
- contentFilesReadOnly: setting('CROMBOLO_CONTENT_FILES_READONLY') === 'true',
926
+ contentMode: contentModeSetting(),
908
927
  dialect: setting('CROMBOLO_DB') === 'postgres' ? 'postgres' : 'sqlite',
909
928
  pgDump: setting('CROMBOLO_PG_DUMP'),
910
929
  upgradePolicy:
@@ -1057,6 +1076,11 @@ export function loadConfig(
1057
1076
  host: undefined,
1058
1077
  }
1059
1078
  const merged: CromboloConfig = { ...fromEnv, ...stripUndefined(overrides) }
1079
+ // The file is checked as the environment is: an unknown mode must not fall back to editable.
1080
+ if (merged.contentMode !== 'development' && merged.contentMode !== 'production')
1081
+ throw new Error(
1082
+ `contentMode is "${String(merged.contentMode)}" in crombolo.config.ts: it is development or production.`,
1083
+ )
1060
1084
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
1061
1085
  checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
1062
1086
  // Field by field, so a site setting its title suffix keeps the environment's switches.
@@ -1200,7 +1224,7 @@ export function describeDatabase(
1200
1224
  }
1201
1225
  }
1202
1226
 
1203
- export const VERSION = '0.63.0'
1227
+ export const VERSION = '0.64.0'
1204
1228
 
1205
1229
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1206
1230
  /** A positive number from a setting, else the default. */
@@ -40,7 +40,7 @@ export interface Actor {
40
40
 
41
41
  export interface ContentNotifierOptions {
42
42
  /** False when the site cannot send e-mail: nothing is queued, and nothing piles up. */
43
- canSend: boolean
43
+ canSend: boolean | (() => boolean)
44
44
  delayMs?: number
45
45
  }
46
46
 
@@ -82,6 +82,9 @@ const pathIds = (path: string): number[] =>
82
82
  .filter((id) => Number.isFinite(id) && id > 0)
83
83
 
84
84
  export function createContentNotifier(db: Db, options: ContentNotifierOptions): ContentNotifier {
85
+ // Asked each time: e-mail set up in Settings starts and stops without a restart (story 340).
86
+ const canSend = () =>
87
+ typeof options.canSend === 'function' ? options.canSend() : options.canSend
85
88
  const factsFor: ContentNotifier['factsFor'] = async (on, change, actor, detail) => {
86
89
  const nodes = new NodeRepository(on)
87
90
  const documents = new DocumentRepository(on)
@@ -126,7 +129,7 @@ export function createContentNotifier(db: Db, options: ContentNotifierOptions):
126
129
 
127
130
  const enqueueFor: ContentNotifier['enqueueFor'] = async (on, eventId, facts) => {
128
131
  // A site that cannot send e-mail queues nothing, so nothing piles up.
129
- if (!options.canSend) return
132
+ if (!canSend()) return
130
133
  const subscriptions = new NotificationRepository(on)
131
134
  const actorId = facts.actorUserKey
132
135
  ? (await new UserRepository(on).byKey(facts.actorUserKey))?.id
@@ -165,7 +168,7 @@ export function createContentNotifier(db: Db, options: ContentNotifierOptions):
165
168
  factsFor,
166
169
  enqueueFor,
167
170
  async raise(change, actor, detail) {
168
- if (!options.canSend) return
171
+ if (!canSend()) return
169
172
  try {
170
173
  const facts = await factsFor(db, change, actor, detail)
171
174
  if (facts) await enqueueFor(db, undefined, facts)
@@ -14,7 +14,8 @@ import { backOfficeUrl } from './back-office-url.ts'
14
14
  import type { CromboloConfig } from './config.ts'
15
15
  import { createContentEventSink } from './content-events.ts'
16
16
  import { createContentNotifier } from './content-notifications.ts'
17
- import { resolveEmailPort } from './email.ts'
17
+ import { emailReady } from './email.ts'
18
+ import { siteEmail } from './email-settings.ts'
18
19
  import { MediaFileStore, mediaStoreFor } from './media-files.ts'
19
20
  import { createNodeOperations } from './node-operations.ts'
20
21
  import { createWebhookService } from './webhooks.ts'
@@ -31,8 +32,8 @@ export async function siteDocumentOperations(
31
32
  ): Promise<SiteOperations> {
32
33
  const state = await currentSchemaState(db)
33
34
  const nodeState = { version: state.version, revision: state.revision }
34
- const email = resolveEmailPort(config)
35
- const notifier = createContentNotifier(db, { canSend: Boolean(email) })
35
+ const email = await siteEmail(db, config)
36
+ const notifier = createContentNotifier(db, { canSend: () => emailReady(email) })
36
37
  const webhooks = createWebhookService({
37
38
  db,
38
39
  schemaDir: config.schemaDir,
package/src/core.ts CHANGED
@@ -66,7 +66,8 @@ import { createContentNotificationRunner, createContentNotifier } from './conten
66
66
  import { databaseFor, openTables, siteTablesProblems, tablesChains } from './custom-tables.ts'
67
67
  import { attachDatabase, bootstrapDatabase } from './database.ts'
68
68
  import { createDiagnostics } from './diagnostics.ts'
69
- import { resolveEmailPort } from './email.ts'
69
+ import { emailReady } from './email.ts'
70
+ import { siteEmail } from './email-settings.ts'
70
71
  import { createActivityRecorder, personOf, timed } from './extension-activity.ts'
71
72
  import { createExtensionComponents } from './extension-components.ts'
72
73
  import {
@@ -492,10 +493,11 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
492
493
  )
493
494
  // Resolved once: constructing it twice would warn twice about a provider that
494
495
  // is half-configured, and the adapters are cheap but not free of side effects.
495
- const email = tracedEmail(resolveEmailPort(config))
496
+ // Story 340: the config's, or one that follows Settings without a restart.
497
+ const email = tracedEmail(await siteEmail(db, config))
496
498
  // Story 045: a change queues the e-mails its subscribers asked for. Nothing is
497
499
  // queued on a site that cannot send; development sends to the console.
498
- const notifier = createContentNotifier(db, { canSend: Boolean(email) })
500
+ const notifier = createContentNotifier(db, { canSend: () => emailReady(email) })
499
501
  const mediaFiles = new MediaFileStore(mediaStore)
500
502
  const webhooks = createWebhookService({
501
503
  db,
@@ -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)