@crombolo/server 0.36.2 → 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 (83) hide show
  1. package/package.json +15 -13
  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 +33 -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-files.ts +6 -1
  21. package/src/adapters/template-query.ts +1 -1
  22. package/src/adapters/users.ts +13 -13
  23. package/src/adapters/webhooks.ts +1 -1
  24. package/src/anonymise-rules.ts +83 -0
  25. package/src/approvals-api.ts +1 -1
  26. package/src/approvals.ts +75 -38
  27. package/src/back-office-url.ts +20 -0
  28. package/src/backup.ts +26 -2
  29. package/src/bundle-code.ts +1 -1
  30. package/src/bundle-grants.ts +265 -0
  31. package/src/bundle-install.ts +13 -2
  32. package/src/bundle-media.ts +12 -11
  33. package/src/bundles.ts +258 -444
  34. package/src/component-snippets.ts +1 -1
  35. package/src/components.ts +48 -7
  36. package/src/config.ts +141 -4
  37. package/src/content-notifications.ts +13 -9
  38. package/src/content-operations.ts +23 -65
  39. package/src/content-query.ts +1 -1
  40. package/src/core.ts +663 -0
  41. package/src/cron.ts +139 -0
  42. package/src/custom-tables.ts +274 -0
  43. package/src/database.ts +22 -14
  44. package/src/dictionary-transfer.ts +1 -1
  45. package/src/git-routes.ts +1 -1
  46. package/src/identity-provider-overrides.ts +18 -16
  47. package/src/imaging.ts +65 -15
  48. package/src/index.ts +14 -1
  49. package/src/islands.ts +197 -0
  50. package/src/job-wake.ts +23 -0
  51. package/src/live-reload.ts +195 -0
  52. package/src/log-viewer.ts +6 -1
  53. package/src/marketplace.ts +82 -10
  54. package/src/media-access.ts +12 -9
  55. package/src/member-auth.ts +6 -4
  56. package/src/middleware.ts +236 -0
  57. package/src/models-builder.ts +1 -1
  58. package/src/node-operations.ts +122 -0
  59. package/src/owner-jobs.ts +428 -0
  60. package/src/ports.ts +39 -154
  61. package/src/preview-tokens.ts +6 -12
  62. package/src/remote.ts +3 -1
  63. package/src/routes.ts +420 -0
  64. package/src/schema.ts +8 -3
  65. package/src/seed/compile.ts +7 -5
  66. package/src/seed/export.ts +6 -4
  67. package/src/seo.ts +2 -2
  68. package/src/server.ts +866 -483
  69. package/src/settings.ts +49 -2
  70. package/src/site-data.ts +195 -0
  71. package/src/site-file.ts +30 -4
  72. package/src/site-queries.ts +140 -0
  73. package/src/site-replace.ts +25 -19
  74. package/src/site-sections.ts +1 -1
  75. package/src/site-services.ts +116 -0
  76. package/src/status-pages.ts +142 -0
  77. package/src/status.ts +11 -9
  78. package/src/url-settings.ts +1 -2
  79. package/src/webhook-files.ts +18 -1
  80. package/src/webhooks.ts +83 -15
  81. package/src/worker-watch.ts +73 -0
  82. package/src/worker.ts +138 -0
  83. package/src/bundle-tables.ts +0 -161
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `site()` for a page render (story 206): the site's services acting as
3
+ * whoever is asking. Media the visitor may not read answers `notFound`, never
4
+ * `forbidden`, as `/media/` answers 404. docs/rendering.md, "Server code".
5
+ */
6
+ import {
7
+ type MediaMember,
8
+ type MediaRule,
9
+ memberMay,
10
+ nearestMediaRule,
11
+ ObjectTypes,
12
+ Outcome,
13
+ ok,
14
+ type Result,
15
+ } from '@crombolo/core'
16
+ import { type Db, MediaAccessRepository } from '@crombolo/data'
17
+ import {
18
+ markPersonal,
19
+ type PublishedCache,
20
+ type PublishedMedia,
21
+ type RequestMember,
22
+ type SiteJobs,
23
+ type SiteMembers,
24
+ type SiteQueries,
25
+ type SiteServices,
26
+ unavailableServices,
27
+ } from '@crombolo/render'
28
+
29
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
30
+
31
+ export interface SiteServicesDeps {
32
+ db: Db
33
+ cache: PublishedCache
34
+ /** `site().jobs`, recording who queued (story 187). */
35
+ jobs?: (queuedBy: () => Promise<string>) => SiteJobs
36
+ /** `site().queries` for a member or a visitor (story 189). */
37
+ queries?: (
38
+ member: RequestMember | undefined | (() => Promise<RequestMember | undefined>),
39
+ ) => SiteQueries
40
+ }
41
+
42
+ /** Builds `site()`'s services for one request; undefined `member` is a visitor or a previewing editor. */
43
+ export function createSiteServices(deps: SiteServicesDeps) {
44
+ const { db, cache } = deps
45
+ const access = new MediaAccessRepository(db)
46
+
47
+ return (
48
+ member: RequestMember | undefined | (() => Promise<RequestMember | undefined>),
49
+ ): (() => SiteServices) => {
50
+ // Middleware asks for the member only when it reads something personal (story 210).
51
+ let reader: Promise<MediaMember | undefined> | undefined
52
+ const readerOf = () => {
53
+ reader ??= (typeof member === 'function' ? member() : Promise.resolve(member)).then(
54
+ (found) => (found ? { key: found.key, groups: found.roles } : undefined),
55
+ )
56
+ return reader
57
+ }
58
+ let rules: Promise<Map<number, MediaRule>> | undefined
59
+ const ruleAt = async (path: string) => {
60
+ rules ??= access.allRules().then((all) => new Map(all.map((r) => [r.nodeId, r])))
61
+ return nearestMediaRule(path, await rules)
62
+ }
63
+
64
+ /** Whether the visitor may read it; reading anything closed to strangers makes the page personal. */
65
+ const readable = async (item: PublishedMedia): Promise<boolean> => {
66
+ const rule = await ruleAt(item.path)
67
+ if (memberMay('read', item.access, rule, undefined)) return true
68
+ markPersonal()
69
+ return memberMay('read', item.access, rule, await readerOf())
70
+ }
71
+
72
+ const notFound = Outcome.notFound()
73
+
74
+ const media: SiteServices['media'] = {
75
+ async get(key: string): Promise<Result<PublishedMedia, 404>> {
76
+ if (!UUID.test(key)) return notFound
77
+ const item = await cache.media?.byKey(key)
78
+ if (!item || !(await readable(item))) return notFound
79
+ return ok(item)
80
+ },
81
+ async children(folderKey: string): Promise<Result<PublishedMedia[], 404>> {
82
+ if (!UUID.test(folderKey)) return notFound
83
+ const folder = await cache.media?.byKey(folderKey)
84
+ if (!folder || !(await readable(folder))) return notFound
85
+ const rows = await db.q
86
+ .selectFrom('node')
87
+ .select('unique_id')
88
+ .where('parent_id', '=', folder.id)
89
+ .where('node_object_type', '=', ObjectTypes.Media)
90
+ .where('trashed', '=', db.dialect.boolValue(false) as boolean)
91
+ .orderBy('sort_order')
92
+ .orderBy('id')
93
+ .execute()
94
+ const found = (await cache.media?.byKeys(rows.map((row) => row.unique_id))) ?? new Map()
95
+ const items: PublishedMedia[] = []
96
+ for (const row of rows) {
97
+ const item = found.get(row.unique_id.toLowerCase())
98
+ if (item && (await readable(item))) items.push(item)
99
+ }
100
+ return ok(items)
101
+ },
102
+ }
103
+
104
+ const services: SiteServices = {
105
+ media,
106
+ queries: deps.queries?.(member) ?? ({} as SiteQueries),
107
+ jobs:
108
+ deps.jobs?.(async () => {
109
+ const who = await (typeof member === 'function' ? member() : Promise.resolve(member))
110
+ return who ? `member ${who.username}` : 'a visitor'
111
+ }) ?? unavailableServices<SiteJobs>('jobs'),
112
+ members: unavailableServices<SiteMembers>('members'),
113
+ }
114
+ return () => services
115
+ }
116
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The pages that answer a status a page's code ends with (story 206): a page in
3
+ * the content tree named by path in `pages`, rendered at the address asked for,
4
+ * else a generic page for the status. docs/rendering.md, "Status pages".
5
+ */
6
+ import {
7
+ escapeHtml,
8
+ type PageOutcome,
9
+ type PublishedCache,
10
+ type PublishedContent,
11
+ } from '@crombolo/render'
12
+ import type { StatusPage, StatusPageRule, StatusPagesConfig } from './config.ts'
13
+
14
+ export type StatusPageKind = keyof StatusPagesConfig
15
+
16
+ /** Which configured page answers a status: 404 and 401 their own, the rest the error page. */
17
+ export function statusPageKind(status: number): StatusPageKind {
18
+ if (status === 404) return 'notFound'
19
+ if (status === 401) return 'unauthorized'
20
+ return 'error'
21
+ }
22
+
23
+ /** A configured page as rules, the bare path standing for one that matches everything. Pure. */
24
+ export function statusPageRules(page: StatusPage | undefined): StatusPageRule[] {
25
+ if (page === undefined) return []
26
+ if (typeof page === 'string') return page.trim() ? [{ path: page.trim() }] : []
27
+ return page.filter((rule) => typeof rule?.path === 'string' && rule.path.trim())
28
+ }
29
+
30
+ /** The most specific rule for a request: hostname and language, then either, then neither. Pure. */
31
+ export function chooseStatusPageRule(
32
+ rules: readonly StatusPageRule[],
33
+ host: string,
34
+ culture: string | null,
35
+ ): StatusPageRule | undefined {
36
+ const bare = host.toLowerCase().replace(/:\d+$/, '')
37
+ const hostMatches = (r: StatusPageRule) =>
38
+ r.host === undefined || [bare, host.toLowerCase()].includes(r.host.trim().toLowerCase())
39
+ const cultureMatches = (r: StatusPageRule) =>
40
+ r.culture === undefined || r.culture.toLowerCase() === (culture ?? '').toLowerCase()
41
+ const score = (r: StatusPageRule) => (r.host ? 2 : 0) + (r.culture ? 1 : 0)
42
+ return rules
43
+ .filter((r) => hostMatches(r) && cultureMatches(r))
44
+ .sort((a, b) => score(b) - score(a))[0]
45
+ }
46
+
47
+ /**
48
+ * The configured page for a status on this request, in the request's culture;
49
+ * undefined when none is configured or its path resolves to nothing.
50
+ */
51
+ export async function resolveStatusPage(
52
+ cache: PublishedCache,
53
+ pages: StatusPagesConfig | undefined,
54
+ kind: StatusPageKind,
55
+ host: string,
56
+ pathname: string,
57
+ ): Promise<{ content: PublishedContent; culture: string | null } | undefined> {
58
+ const rules = statusPageRules(pages?.[kind])
59
+ if (rules.length === 0) return undefined
60
+ const culture = await cache.cultureFor(host, pathname)
61
+ const rule = chooseStatusPageRule(rules, host, culture)
62
+ if (!rule) return undefined
63
+ const resolved = await cache.resolve(host, rule.path)
64
+ if (!resolved) return undefined
65
+ const localised = culture ? await cache.byKey(resolved.content.key, culture) : undefined
66
+ return localised
67
+ ? { content: localised, culture }
68
+ : { content: resolved.content, culture: resolved.culture }
69
+ }
70
+
71
+ /** Each configured path that resolves to nothing on any hostname, for the boot to warn about. */
72
+ export async function unresolvedStatusPages(
73
+ cache: PublishedCache,
74
+ pages: StatusPagesConfig | undefined,
75
+ ): Promise<Array<{ kind: StatusPageKind; path: string }>> {
76
+ const missing: Array<{ kind: StatusPageKind; path: string }> = []
77
+ for (const kind of ['notFound', 'unauthorized', 'error'] as const)
78
+ for (const rule of statusPageRules(pages?.[kind]))
79
+ if (!(await cache.resolve(rule.host ?? '', rule.path)))
80
+ missing.push({ kind, path: rule.path })
81
+ return missing
82
+ }
83
+
84
+ const HEADINGS: Record<number, string> = {
85
+ 400: 'This request could not be used',
86
+ 401: 'Please sign in',
87
+ 403: 'You do not have access to this page',
88
+ 404: 'Page not found',
89
+ 410: 'This page is no longer available',
90
+ 422: 'Some details need correcting',
91
+ 500: 'Something went wrong',
92
+ }
93
+
94
+ /** A page for a status when the site has none of its own, or its own failed. Pure. */
95
+ export function genericStatusPage(outcome: PageOutcome): string {
96
+ const heading = HEADINGS[outcome.status] ?? 'Something went wrong'
97
+ const parts = [`<h1>${escapeHtml(heading)}</h1>`]
98
+ if (outcome.message) parts.push(`<p>${escapeHtml(outcome.message)}</p>`)
99
+ if (outcome.errors.length > 0)
100
+ parts.push(
101
+ `<ul>${outcome.errors
102
+ .map((e) => `<li><strong>${escapeHtml(e.field)}</strong>: ${escapeHtml(e.message)}</li>`)
103
+ .join('')}</ul>`,
104
+ )
105
+ if (outcome.details) {
106
+ const { message, location, code, components, stack } = outcome.details
107
+ parts.push(`<p>${escapeHtml(message)}</p>`)
108
+ if (location) parts.push(`<p><code>${escapeHtml(location)}</code></p>`)
109
+ if (code) parts.push(codeFrame(code))
110
+ if (components?.length)
111
+ parts.push(`<p>While rendering <code>${escapeHtml(components.join(' › '))}</code></p>`)
112
+ if (stack) parts.push(`<pre>${escapeHtml(stack)}</pre>`)
113
+ }
114
+ if (outcome.reference)
115
+ parts.push(`<p>Reference: <code>${escapeHtml(outcome.reference)}</code></p>`)
116
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(heading)}</title><style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5;color:#222}pre{overflow:auto;background:#f4f4f4;padding:1rem;font-size:.85rem}.code span{display:block}.code .at{background:#fde2e2;font-weight:600}</style></head><body><main>${parts.join('')}</main></body></html>`
117
+ }
118
+
119
+ /** The lines around a failing one, numbered, that line marked. */
120
+ function codeFrame(code: NonNullable<PageOutcome['details']>['code'] & object): string {
121
+ const width = String(code.lines.at(-1)?.number ?? code.line).length
122
+ const rows = code.lines.map(({ number, text }) => {
123
+ const mark = number === code.line ? '>' : ' '
124
+ const label = `${mark} ${String(number).padStart(width)} | `
125
+ return `<span${number === code.line ? ' class="at"' : ''}>${escapeHtml(label + text)}</span>`
126
+ })
127
+ return `<pre class="code">${rows.join('')}</pre>`
128
+ }
129
+
130
+ const REDIRECT_NAMES: Record<number, string> = {
131
+ 301: 'Moved Permanently',
132
+ 302: 'Found',
133
+ 303: 'See Other',
134
+ 307: 'Temporary Redirect',
135
+ 308: 'Permanent Redirect',
136
+ }
137
+
138
+ /** What an editor previewing a page that redirects sees, rather than the frame navigating away. Pure. */
139
+ export function previewRedirectNotice(status: number, location: string): string {
140
+ const name = REDIRECT_NAMES[status] ?? 'Redirect'
141
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>This page redirects</title><style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5}</style></head><body><main><h1>This page redirects</h1><p>Visitors are sent to <a href="${escapeHtml(location)}" target="_top">${escapeHtml(location)}</a> with ${status} ${escapeHtml(name)}.</p></main></body></html>`
142
+ }
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'
@@ -25,8 +25,15 @@ export interface WebhookDefinition {
25
25
  contentTypeKeys: string[]
26
26
  /** A value is either `env:NAME` or, kept in the database only, the secret itself. */
27
27
  headers: Record<string, string>
28
+ /**
29
+ * What is posted: Umbraco's Minimal `{ Id }`, or `crombolo`, which adds the
30
+ * item's content type and its ancestors' keys (story 208). Set in the file only.
31
+ */
32
+ payload?: WebhookPayload
28
33
  }
29
34
 
35
+ export type WebhookPayload = 'minimal' | 'crombolo'
36
+
30
37
  const ENV_REFERENCE = /^env:([A-Za-z_][A-Za-z0-9_]*)$/
31
38
  const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/
32
39
  /** Set on every delivery, so a webhook may not set them itself. */
@@ -51,6 +58,10 @@ export function webhookProblems(webhook: WebhookDefinition, store: WebhookStore)
51
58
  if (!/^https?:\/\/[^\s/]+/.test(webhook.url))
52
59
  problems.push('The URL must be a web address starting http:// or https://.')
53
60
  if (webhook.events.length === 0) problems.push('Choose at least one event.')
61
+ if (webhook.payload === 'crombolo' && store === 'database')
62
+ problems.push(
63
+ "This webhook sends Crombolo's payload, which is set in its file, so it stays with the site's files.",
64
+ )
54
65
  for (const event of webhook.events)
55
66
  if (!WEBHOOK_EVENT_ALIASES.has(event))
56
67
  problems.push(`"${event}" is not an event this site raises.`)
@@ -102,6 +113,7 @@ export function writeWebhookFile(
102
113
  if (!webhook.enabled) out.push('enabled = false')
103
114
  out.push(`events = ${list(webhook.events)}`)
104
115
  if (contentTypes.length > 0) out.push(`content-types = ${list(contentTypes)}`)
116
+ if (webhook.payload === 'crombolo') out.push('payload = "crombolo"')
105
117
  const headers = Object.keys(webhook.headers).sort()
106
118
  if (headers.length > 0) {
107
119
  out.push('', '[webhook.headers]')
@@ -120,6 +132,7 @@ const KEYS = new Set([
120
132
  'events',
121
133
  'content-types',
122
134
  'headers',
135
+ 'payload',
123
136
  ])
124
137
 
125
138
  /** A file back to a webhook, or what is wrong with it. Unknown keys are refused, as in every schema file. */
@@ -151,6 +164,9 @@ export function parseWebhookFile(
151
164
  for (const [name, value] of Object.entries(table.headers as Record<string, unknown>))
152
165
  if (typeof value === 'string') headers[name] = value
153
166
  else problems.push(`${file}: webhook.headers.${name} must be text`)
167
+ const payload = text('payload')
168
+ if (table.payload !== undefined && payload !== 'minimal' && payload !== 'crombolo')
169
+ problems.push(`${file}: webhook.payload must be "minimal" or "crombolo"`)
154
170
  const webhookAlias = text('alias') ?? undefined
155
171
  const written = text('key')
156
172
  if (written !== null && !/^[0-9a-f-]{36}$/i.test(written))
@@ -169,6 +185,7 @@ export function parseWebhookFile(
169
185
  /^[0-9a-f-]{36}$/i.test(value) ? value.toLowerCase() : value,
170
186
  ),
171
187
  headers,
188
+ ...(payload === 'crombolo' ? { payload } : {}),
172
189
  }
173
190
  problems.push(...webhookProblems(webhook, 'files').map((message) => `${file}: ${message}`))
174
191
  return problems.length > 0 ? { problems } : { webhook, problems }
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,11 +142,29 @@ 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
- /** An event as a webhook delivers it, with the item's type as it was when it happened. */
149
+ /** An event as a webhook delivers it, with the item's type and place as they were when it happened. */
148
150
  export interface WebhookFacts extends RaisedWebhookEvent {
149
151
  contentTypeKey?: string
152
+ contentTypeAlias?: string
153
+ /** Its ancestors' keys, nearest first, for Crombolo's payload (story 208). */
154
+ ancestors?: string[]
155
+ }
156
+
157
+ /** What a webhook is posted. Pure. */
158
+ export function webhookPayload(
159
+ facts: WebhookFacts,
160
+ payload: WebhookDefinition['payload'],
161
+ ): Record<string, unknown> {
162
+ if (payload !== 'crombolo') return { Id: facts.key }
163
+ return {
164
+ Id: facts.key,
165
+ ContentType: facts.contentTypeAlias ?? null,
166
+ Ancestors: facts.ancestors ?? [],
167
+ }
150
168
  }
151
169
 
152
170
  export interface WebhookService {
@@ -420,6 +438,13 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
420
438
  delivery: WebhookDelivery,
421
439
  bundleId: string,
422
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
+ }
423
448
  const handler = bundles.find((bundle) => bundle.id === bundleId)?.events?.[delivery.eventAlias]
424
449
  const entry = {
425
450
  deliveryId: delivery.id,
@@ -498,6 +523,10 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
498
523
  ...definition,
499
524
  key: existing.key,
500
525
  headers: unmask(definition.headers, existing.headers),
526
+ // The back office has no field for it, so an edit there keeps the file's choice.
527
+ ...((definition.payload ?? existing.payload)
528
+ ? { payload: definition.payload ?? existing.payload }
529
+ : {}),
501
530
  }
502
531
  return store(next, existing.store)
503
532
  },
@@ -522,17 +551,20 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
522
551
  return written
523
552
  },
524
553
  async factsFor(db, event) {
525
- const contentTypeKey = await itemType(db, event.key)
526
- return contentTypeKey ? { ...event, contentTypeKey } : { ...event }
554
+ const item = await itemFacts(db, event.key)
555
+ return item ? { ...event, ...item } : { ...event }
527
556
  },
528
557
  async enqueueFor(db, eventId, facts) {
529
- const subscribers = subscribersFor(facts, facts.contentTypeKey, await all(), bundles)
558
+ const webhooks = await all()
559
+ const subscribers = subscribersFor(facts, facts.contentTypeKey, webhooks, bundles)
530
560
  if (subscribers.length === 0) return 0
561
+ const payloadOf = (subscriber: string) =>
562
+ webhookPayload(facts, webhooks.find((webhook) => webhook.key === subscriber)?.payload)
531
563
  const queued = await new WebhookDeliveryRepository(db).enqueue(
532
564
  subscribers.map((subscriber) => ({
533
565
  subscriber,
534
566
  eventAlias: facts.alias,
535
- payload: { Id: facts.key },
567
+ payload: payloadOf(subscriber),
536
568
  eventId,
537
569
  })),
538
570
  now(),
@@ -579,13 +611,49 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
579
611
  }
580
612
 
581
613
  /** An item's type, while it still exists. */
582
- async function itemType(db: Db, key: string): Promise<string | undefined> {
583
- const rows = await db.query<{ type_key: string }>(
584
- `SELECT tn.unique_id AS type_key FROM node n
585
- JOIN content c ON c.node_id = n.id
586
- JOIN node tn ON tn.id = c.content_type_id
587
- WHERE n.unique_id = ?`,
588
- [key],
589
- )
590
- return rows[0] ? String(rows[0].type_key).toLowerCase() : undefined
614
+ /** The item's type and ancestors, read in the change's transaction so a delete still knows them. */
615
+ async function itemFacts(
616
+ db: Db,
617
+ key: string,
618
+ ): Promise<Pick<WebhookFacts, 'contentTypeKey' | 'contentTypeAlias' | 'ancestors'> | undefined> {
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()
639
+ const row = rows[0]
640
+ if (!row) return undefined
641
+ // In the recycle bin its path is the bin's, so its ancestors are where it was.
642
+ const chain = row.original_path
643
+ ? String(row.original_path).split(',')
644
+ : String(row.path).split(',').slice(0, -1)
645
+ const ids = chain.map(Number).filter((id) => id > 0)
646
+ const found =
647
+ ids.length === 0
648
+ ? []
649
+ : await db.q.selectFrom('node').select(['id', 'unique_id']).where('id', 'in', ids).execute()
650
+ const keyOf = new Map(found.map((r) => [Number(r.id), String(r.unique_id).toLowerCase()]))
651
+ return {
652
+ contentTypeKey: String(row.type_key).toLowerCase(),
653
+ ...(row.type_alias ? { contentTypeAlias: String(row.type_alias) } : {}),
654
+ ancestors: ids
655
+ .reverse()
656
+ .map((id) => keyOf.get(id))
657
+ .filter((k): k is string => Boolean(k)),
658
+ }
591
659
  }
@@ -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
+ }