@crombolo/server 0.45.0 → 0.47.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.45.0",
3
+ "version": "0.47.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,32 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.45.0",
35
- "@crombolo/api-management": "0.45.0",
36
- "@crombolo/auth": "0.45.0",
37
- "@crombolo/backoffice-host": "0.45.0",
38
- "@crombolo/common": "0.45.0",
39
- "@crombolo/content": "0.45.0",
40
- "@crombolo/contracts": "0.45.0",
41
- "@crombolo/core": "0.45.0",
42
- "@crombolo/data": "0.45.0",
43
- "@crombolo/render": "0.45.0",
44
- "@crombolo/schema": "0.45.0",
45
- "@crombolo/transfer": "0.45.0",
34
+ "@crombolo/api-delivery": "0.47.0",
35
+ "@crombolo/api-management": "0.47.0",
36
+ "@crombolo/auth": "0.47.0",
37
+ "@crombolo/backoffice-host": "0.47.0",
38
+ "@crombolo/common": "0.47.0",
39
+ "@crombolo/content": "0.47.0",
40
+ "@crombolo/contracts": "0.47.0",
41
+ "@crombolo/core": "0.47.0",
42
+ "@crombolo/data": "0.47.0",
43
+ "@crombolo/render": "0.47.0",
44
+ "@crombolo/schema": "0.47.0",
45
+ "@crombolo/transfer": "0.47.0",
46
46
  "@logtape/logtape": "^2.3.8",
47
+ "@opentelemetry/api": "1.10.0",
48
+ "@opentelemetry/context-async-hooks": "3.0.0",
49
+ "@opentelemetry/core": "3.0.0",
50
+ "@opentelemetry/exporter-logs-otlp-http": "0.300.0",
51
+ "@opentelemetry/exporter-logs-otlp-proto": "0.300.0",
52
+ "@opentelemetry/exporter-metrics-otlp-http": "0.300.0",
53
+ "@opentelemetry/exporter-metrics-otlp-proto": "0.300.0",
54
+ "@opentelemetry/exporter-trace-otlp-http": "0.300.0",
55
+ "@opentelemetry/exporter-trace-otlp-proto": "0.300.0",
56
+ "@opentelemetry/resources": "3.0.0",
57
+ "@opentelemetry/sdk-logs": "3.0.0",
58
+ "@opentelemetry/sdk-metrics": "3.0.0",
59
+ "@opentelemetry/sdk-trace": "3.0.0",
47
60
  "@sigstore/bundle": "^3.1.0",
48
61
  "@sigstore/core": "^2.0.0",
49
62
  "@sigstore/protobuf-specs": "^0.4.3",
@@ -32,6 +32,7 @@ import { type EmailPort, emailAvailability } from '../email.ts'
32
32
  import type { MediaStore } from '../media-store.ts'
33
33
  import { restartPending } from '../restart-pending.ts'
34
34
  import { backofficeVersion } from '../status.ts'
35
+ import { type TelemetryStatus, telemetryStatus } from '../telemetry.ts'
35
36
 
36
37
  export const UPGRADE_PACKAGE = '@crombolo/crombolo'
37
38
 
@@ -476,6 +477,7 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
476
477
  availability.available ? (availability.description ?? undefined) : 'Not configured',
477
478
  ],
478
479
  ['Log level', config.logLevel],
480
+ ['Telemetry', describeTelemetry(telemetryStatus())],
479
481
  ['Time zone', Intl.DateTimeFormat().resolvedOptions().timeZone],
480
482
  ['Server time', now().toISOString()],
481
483
  ]
@@ -525,3 +527,9 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
525
527
  },
526
528
  }
527
529
  }
530
+
531
+ /** Where traces, metrics and logs go, or that they go nowhere (story 262); never the headers. */
532
+ export function describeTelemetry(status: TelemetryStatus): string {
533
+ if (!status.enabled) return 'Not sent anywhere'
534
+ return `Sent to ${status.endpoint} as ${status.serviceName} (${status.role})`
535
+ }
@@ -7,7 +7,6 @@ import type { MediaPort } from '@crombolo/api-management/domain'
7
7
  import {
8
8
  type ContentTypeAggregate,
9
9
  DEFAULT_UPLOAD_SETTINGS,
10
- type DocumentAggregate,
11
10
  IMAGE_CROPPER_EDITOR_ALIAS,
12
11
  mediaFileOf,
13
12
  normaliseUuid,
@@ -18,11 +17,21 @@ import {
18
17
  DataTypeRepository,
19
18
  type Db,
20
19
  DocumentRepository,
20
+ MediaListingRepository,
21
+ type MediaSortField,
21
22
  type NodeRow,
22
23
  type NodeSchemaState,
23
24
  type ValueIntake,
24
25
  } from '@crombolo/data'
25
26
 
27
+ /** The folder view's `orderBy`, as the listing sorts; anything else is sort order. */
28
+ const COLLECTION_SORTS: Record<string, MediaSortField> = {
29
+ name: 'name',
30
+ createDate: 'createDate',
31
+ updateDate: 'updateDate',
32
+ sortOrder: 'sortOrder',
33
+ }
34
+
26
35
  /** The Media section's reads; its writes go through the media operations (story 165). */
27
36
  export function createMediaPort(
28
37
  db: Db,
@@ -109,50 +118,35 @@ export function createMediaPort(
109
118
  return { total: page.total, items: await tree(page.items) }
110
119
  },
111
120
 
121
+ /**
122
+ * The folder view (story 246): counted, filtered, sorted and paged in the
123
+ * database, so a folder of a million files costs a page, not the folder.
124
+ * Only the page's items are loaded, and their creators in one query.
125
+ */
112
126
  async collection(parentKey, options) {
113
- const children = await repo.children(parentKey, 0, Number.MAX_SAFE_INTEGER)
114
- const filter = options.filter?.trim().toLowerCase()
115
- const loaded: Array<DocumentAggregate & { sortOrder: number; creator: string | null }> = []
116
- for (const node of children.items) {
117
- const media = await repo.load(node)
118
- if (!media) continue
119
- const name = media.variants[0]?.name ?? node.text ?? ''
120
- if (filter && !name.toLowerCase().includes(filter)) continue
121
- const latest = (await repo.versions(node.key))[0]
122
- const creator = latest?.userKey
123
- ? ((
124
- await db.q
125
- .selectFrom('user_account')
126
- .select('user_name')
127
- .where('key', '=', latest.userKey)
128
- .execute()
129
- )[0]?.user_name ?? null)
130
- : null
131
- loaded.push({ ...media, sortOrder: node.sortOrder, creator })
132
- }
133
- const keyOf = (m: (typeof loaded)[number]): string | number => {
134
- const variant = m.variants[0]
135
- switch (options.orderBy) {
136
- case 'name':
137
- return (variant?.name ?? '').toLowerCase()
138
- case 'createDate':
139
- return variant?.createDate.getTime() ?? 0
140
- case 'updateDate':
141
- return variant?.updateDate.getTime() ?? 0
142
- default:
143
- return m.sortOrder
144
- }
145
- }
146
- loaded.sort((a, b) => {
147
- const x = keyOf(a)
148
- const y = keyOf(b)
149
- const order = x < y ? -1 : x > y ? 1 : 0
150
- return options.orderDirection === 'Descending' ? -order : order
127
+ const listing = new MediaListingRepository(db)
128
+ const parent = parentKey ? await listing.byKey(parentKey) : { id: -1, path: '-1' }
129
+ if (!parent) return { total: 0, items: [] }
130
+ const filter = options.filter?.trim()
131
+ const page = await listing.children({
132
+ parentId: parent.id,
133
+ parentPath: parent.path,
134
+ names: filter ? [filter] : [],
135
+ sort: {
136
+ field: COLLECTION_SORTS[options.orderBy ?? ''] ?? 'sortOrder',
137
+ ascending: options.orderDirection !== 'Descending',
138
+ },
139
+ skip: options.skip,
140
+ take: options.take,
151
141
  })
152
- return {
153
- total: loaded.length,
154
- items: loaded.slice(options.skip, options.skip + options.take),
155
- }
142
+ const [loaded, creators] = await Promise.all([
143
+ Promise.all(page.keys.map((key) => repo.byKey(key))),
144
+ listing.creators(page.keys),
145
+ ])
146
+ const items = loaded.flatMap((media) =>
147
+ media ? [{ ...media, creator: creators.get(media.key) ?? null }] : [],
148
+ )
149
+ return { total: page.total, items }
156
150
  },
157
151
 
158
152
  async typesForExtension(raw) {
@@ -17,6 +17,7 @@ import type {
17
17
  } from '@crombolo/api-management/domain'
18
18
  import { ObjectTypes } from '@crombolo/core'
19
19
  import {
20
+ appendCacheInstruction,
20
21
  type Db,
21
22
  MemberRepository,
22
23
  NodeRepository,
@@ -26,9 +27,19 @@ import {
26
27
 
27
28
  export function createPublicAccessPort(
28
29
  db: Db,
29
- options: { onChange?: () => void | Promise<void> } = {},
30
+ options: { nodeId?: string; onChange?: () => void | Promise<void> } = {},
30
31
  ): PublicAccessPort {
31
32
  const access = new PublicAccessRepository(db)
33
+ // A page that leaves out what a visitor may not open changes with the rules,
34
+ // so they move the checkpoint, and with it every page's ETag (story 258).
35
+ const changed = async () => {
36
+ await appendCacheInstruction(db, {
37
+ kind: 'content',
38
+ payload: { publicAccess: true },
39
+ by: options.nodeId,
40
+ })
41
+ await options.onChange?.()
42
+ }
32
43
  const members = new MemberRepository(db)
33
44
  const nodes = new NodeRepository(db)
34
45
 
@@ -104,14 +115,14 @@ export function createPublicAccessPort(
104
115
  memberUserNames: input.memberUserNames,
105
116
  })
106
117
  if (!saved) return 'content-not-found'
107
- await options.onChange?.()
118
+ await changed()
108
119
  return 'ok'
109
120
  },
110
121
 
111
122
  async remove(documentKey): Promise<PublicAccessStatus> {
112
123
  if (!(await isDocument(documentKey))) return 'content-not-found'
113
124
  if (!(await access.remove(documentKey))) return 'entry-not-found'
114
- await options.onChange?.()
125
+ await changed()
115
126
  return 'ok'
116
127
  },
117
128
  }
@@ -158,6 +158,54 @@ export default function SiteMap({ nav }: Pick<PageProps, 'nav'>) {
158
158
  )
159
159
  return <div class="sitemap">{branch(nav.root())}</div>
160
160
  }
161
+ `,
162
+ },
163
+ {
164
+ id: 'PersonalisedPart',
165
+ name: 'Personalised part',
166
+ // Story 264: a part fetched for each visitor, so the page around it is shared.
167
+ content: `'use deferred'
168
+ // A personalised part: it shows the signed-in visitor, and is fetched for each
169
+ // visitor after the page loads, so the rest of the page can be the same for
170
+ // everyone and kept by a CDN. Use one for a greeting, a basket or an account
171
+ // link. For something that runs in the browser, such as a counter or a map,
172
+ // start from "Interactive part" instead.
173
+ //
174
+ // Use it with what to show until it arrives, which is what is shared:
175
+ // <Greeting fallback={<a href="/sign-in">Sign in</a>} />
176
+ // Its props travel in its address, so pass data only: text, numbers, lists.
177
+ import { usePage } from '@crombolo/crombolo'
178
+
179
+ export default function Greeting() {
180
+ const { member } = usePage()
181
+ if (!member) return <a href="/sign-in">Sign in</a>
182
+ return <a href="/account">Hi {member.name}</a>
183
+ }
184
+ `,
185
+ },
186
+ {
187
+ id: 'InteractivePart',
188
+ name: 'Interactive part',
189
+ // Story 264: an island, which React runs in the browser.
190
+ content: `/** @jsxImportSource react */
191
+ 'use client'
192
+ // An interactive part: React runs it in the browser, so it can respond to
193
+ // clicks and typing. The site needs react and react-dom installed. For
194
+ // something that shows the signed-in visitor, start from "Personalised part"
195
+ // instead: an interactive part sees only the props it is given.
196
+ //
197
+ // Use it with what to show until it runs:
198
+ // <Counter start={0} fallback={<p>0</p>} />
199
+ import { useState } from 'react'
200
+
201
+ export default function Counter({ start = 0 }: { start?: number }) {
202
+ const [count, setCount] = useState(start)
203
+ return (
204
+ <button type="button" onClick={() => setCount(count + 1)}>
205
+ {count}
206
+ </button>
207
+ )
208
+ }
161
209
  `,
162
210
  },
163
211
  ]
package/src/config.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  type RequestMember,
16
16
  type SiteServices,
17
17
  type SnapshotLimits,
18
+ type Validator,
18
19
  } from '@crombolo/render'
19
20
  import type { ServerBundle } from './bundles.ts'
20
21
  import type { EmailPort } from './email.ts'
@@ -27,6 +28,7 @@ import type { ProvenancePolicy, SignaturePolicy } from './provenance.ts'
27
28
  import type { SchemaStore } from './schema-store.ts'
28
29
  import { setting } from './settings.ts'
29
30
  import type { SiteDatabaseConfig, SiteQueryModules } from './site-queries.ts'
31
+ import type { TelemetryOptions } from './telemetry.ts'
30
32
 
31
33
  /**
32
34
  * Runtime settings for a site. Umbraco's equivalents live in appsettings.json;
@@ -455,10 +457,24 @@ export interface CromboloConfig {
455
457
  /**
456
458
  * How long pages, Delivery API answers and media may be kept by browsers and a
457
459
  * CDN (story 057; `docs/operations.md`, "Behind a CDN"). Nothing is kept unless
458
- * set. `CROMBOLO_CACHE_MAX_AGE`, `CROMBOLO_CACHE_STALE_WHILE_REVALIDATE` and
459
- * `CROMBOLO_CACHE_TAG_HEADER`; per type alias in code only.
460
+ * set. `CROMBOLO_CACHE_MAX_AGE`, `CROMBOLO_CACHE_STALE_WHILE_REVALIDATE`,
461
+ * `CROMBOLO_CACHE_TAG_HEADER`, `CROMBOLO_CACHE_VALIDATOR`, `CROMBOLO_CACHE_MODE`,
462
+ * `CROMBOLO_CACHE_STALE_IF_ERROR` and `CROMBOLO_CACHE_CHECK_FLOOR`; per type
463
+ * alias in code only.
460
464
  */
461
465
  cache: CacheOptions
466
+ /**
467
+ * Where traces, metrics and logs are sent over OpenTelemetry (story 262;
468
+ * `docs/operations.md`, "Telemetry"). `OTEL_EXPORTER_OTLP_ENDPOINT` and
469
+ * `OTEL_SERVICE_NAME` win; unset, nothing is sent.
470
+ */
471
+ telemetry: TelemetryOptions
472
+ /**
473
+ * The load balancers or CDN in front of the site, as addresses or IPv4
474
+ * ranges (`10.0.0.0/8`). A request's `traceparent` is followed only from one
475
+ * of them. `CROMBOLO_TRUSTED_PROXIES`.
476
+ */
477
+ trustedProxies: string[]
462
478
  /**
463
479
  * Bundles whose server half this site runs, each the result of calling the
464
480
  * factory its package exports. Imported and listed here by hand on purpose:
@@ -898,10 +914,19 @@ export function loadConfig(
898
914
  : Number(setting('CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES')),
899
915
  }),
900
916
  }),
917
+ telemetry: {},
918
+ trustedProxies: (setting('CROMBOLO_TRUSTED_PROXIES') ?? '')
919
+ .split(',')
920
+ .map((proxy) => proxy.trim())
921
+ .filter(Boolean),
901
922
  cache: stripUndefined({
902
923
  maxAge: numberSetting('CROMBOLO_CACHE_MAX_AGE'),
903
924
  staleWhileRevalidate: numberSetting('CROMBOLO_CACHE_STALE_WHILE_REVALIDATE'),
904
925
  tagHeader: setting('CROMBOLO_CACHE_TAG_HEADER') || undefined,
926
+ validator: validatorSetting('CROMBOLO_CACHE_VALIDATOR'),
927
+ mode: setting('CROMBOLO_CACHE_MODE') === 'check' ? ('check' as const) : undefined,
928
+ staleIfError: numberSetting('CROMBOLO_CACHE_STALE_IF_ERROR'),
929
+ checkFloor: numberSetting('CROMBOLO_CACHE_CHECK_FLOOR'),
905
930
  }),
906
931
  // No environment variable: a bundle is an import, which is code.
907
932
  bundles: [],
@@ -1041,7 +1066,7 @@ export function describeDatabase(
1041
1066
  }
1042
1067
  }
1043
1068
 
1044
- export const VERSION = '0.45.0'
1069
+ export const VERSION = '0.47.0'
1045
1070
 
1046
1071
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1047
1072
  /** A positive number from a setting, else the default. */
@@ -1050,6 +1075,11 @@ function positiveNumber(raw: string | undefined, fallback: number): number {
1050
1075
  return raw !== undefined && raw !== '' && Number.isFinite(value) && value > 0 ? value : fallback
1051
1076
  }
1052
1077
 
1078
+ function validatorSetting(name: Parameters<typeof setting>[0]): Validator | undefined {
1079
+ const raw = setting(name)?.trim()
1080
+ return raw === 'published' || raw === 'body' ? raw : undefined
1081
+ }
1082
+
1053
1083
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
1054
1084
  const raw = setting(name)
1055
1085
  if (raw === undefined || raw.trim() === '') return undefined
package/src/core.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { ServerEvent } from '@crombolo/api-management/domain'
8
8
  import { createBackOfficePaths, createExtensionRegistry } from '@crombolo/backoffice-host/registry'
9
+ import { mediaJobHandlers } from '@crombolo/content'
9
10
  import { ObjectTypes } from '@crombolo/core'
10
11
  import {
11
12
  appendCacheInstruction,
@@ -18,6 +19,7 @@ import {
18
19
  import {
19
20
  DEFAULT_MEDIA_CACHE_MEGABYTES,
20
21
  DEVELOPMENT_LIMITS,
22
+ deferredTransform,
21
23
  enableComponentStack,
22
24
  ISLANDS_PATH,
23
25
  islandTransform,
@@ -65,6 +67,7 @@ import { MediaFileStore } from './media-files.ts'
65
67
  import { mediaStoreFromEnvironment } from './media-store.ts'
66
68
  import { createNodeOperations } from './node-operations.ts'
67
69
  import {
70
+ CORE_JOB_OWNER,
68
71
  createJobRunner,
69
72
  type JobHandler,
70
73
  type JobOwner,
@@ -77,6 +80,7 @@ import { bootSchema, CacheInstructionPoller } from './schema.ts'
77
80
  import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
78
81
  import { createSiteQueries, queryProblems } from './site-queries.ts'
79
82
  import { createSiteServices } from './site-services.ts'
83
+ import { recordCacheLookup, startTelemetry, tracedDb, tracedEmail } from './telemetry.ts'
80
84
  import { redirectAfterUrlChange, type UrlChangeContext } from './url-settings.ts'
81
85
  import { assertViewRuntime } from './view-runtime.ts'
82
86
  import { bundleEventProblems, createWebhookService } from './webhooks.ts'
@@ -159,9 +163,19 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
159
163
  // bundle's; a worker runs bundles' jobs, so it opens every owner's.
160
164
  const siteChains = chains.filter((chain) => chain.id === SITE_OWNER)
161
165
  const opened = config.role === 'web' ? siteChains : chains
162
- const { db, seededAdminPassword } = owns
166
+ const booted = owns
163
167
  ? await bootstrapDatabase(config, chains)
164
168
  : await attachDatabase(config, opened)
169
+ const { seededAdminPassword } = booted
170
+ // Story 262: on every role, before anything reads, so each statement is a span.
171
+ await startTelemetry({
172
+ telemetry: config.telemetry,
173
+ siteName: config.siteName,
174
+ role: config.role,
175
+ nodeId: config.nodeId,
176
+ db: booted.db,
177
+ })
178
+ const db = tracedDb(booted.db)
165
179
  await openTables(db, config, opened, { provision: owns })
166
180
  // Stories 222 and 225: wiring a bundle approves it; an administrator can disable it.
167
181
  const bundleGrants = createBundleGrants({
@@ -239,6 +253,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
239
253
  const cache = new PublishedCache(publishedSource, {
240
254
  ...cacheOptions,
241
255
  onInvalidate: () => hooks.onCacheInvalidate?.(),
256
+ onRead: recordCacheLookup,
242
257
  })
243
258
  // A sync or a Settings change that alters how URLs are built moves every URL:
244
259
  // the old ones redirect, as a rename's do.
@@ -290,7 +305,8 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
290
305
  },
291
306
  // Story 209: a `'use client'` view is a stub on the server, and its browser
292
307
  // code is built with the generation, unless a site's Vite build supplies it.
293
- transform: islandTransform,
308
+ // Story 263: a `'use deferred'` view is a placeholder in the page, its source kept beside it.
309
+ transform: (key, bytes) => islandTransform(key, bytes) ?? deferredTransform(key, bytes),
294
310
  beforeSwap: async (generation) => {
295
311
  if (!hooks.buildIslands) return
296
312
  if (config.islands?.manifest || (config.development && config.islands?.devServer)) return
@@ -332,7 +348,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
332
348
  )
333
349
  // Resolved once: constructing it twice would warn twice about a provider that
334
350
  // is half-configured, and the adapters are cheap but not free of side effects.
335
- const email = resolveEmailPort(config)
351
+ const email = tracedEmail(resolveEmailPort(config))
336
352
  // Story 045: a change queues the e-mails its subscribers asked for. Nothing is
337
353
  // queued on a site that cannot send; development sends to the console.
338
354
  const notifier = createContentNotifier(db, { canSend: Boolean(email) })
@@ -390,6 +406,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
390
406
  webhooks,
391
407
  nudgeEvents: () => wake('events'),
392
408
  backOfficeUrl: backOfficeUrl(config),
409
+ background: (queuedBy) => jobRunner.jobsFor(CORE_JOB_OWNER, queuedBy),
393
410
  })
394
411
 
395
412
  /**
@@ -537,6 +554,14 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
537
554
  const siteJobs = siteJobHandlers(config.jobs)
538
555
  /** Every owner with jobs: the site's given its tables and `site()` as a visitor; a bundle's, its capabilities for no caller. */
539
556
  const jobOwners = (): JobOwner[] => [
557
+ // Core's own queued work: a large media branch's trash, move or delete (story 246).
558
+ {
559
+ id: CORE_JOB_OWNER,
560
+ handlers: mediaJobHandlers(operations.media) as Map<string, JobHandler>,
561
+ schedules: [],
562
+ context: () => ({}),
563
+ on: () => true,
564
+ },
540
565
  ...(siteJobs.size > 0
541
566
  ? [
542
567
  {
package/src/index.ts CHANGED
@@ -115,12 +115,14 @@ export * from './site-sections.ts'
115
115
  export * from './status.ts'
116
116
  export * from './status-pages.ts'
117
117
  export * from './tar.ts'
118
+ export * from './telemetry.ts'
118
119
  export * from './transfer-dashboard.ts'
119
120
  export * from './two-factor.ts'
120
121
  export * from './udt.ts'
121
122
  export * from './upgrade-summary.ts'
122
123
  export * from './url-settings.ts'
123
124
  export * from './view-runtime.ts'
125
+ export * from './webhook-edit.ts'
124
126
  export * from './webhook-files.ts'
125
127
  export * from './webhooks.ts'
126
128
  export * from './worker.ts'
package/src/jobs.ts CHANGED
@@ -30,6 +30,7 @@ import type {
30
30
  import type { WorkflowRunner, WorkflowRunReport } from './form-workflows.ts'
31
31
  import { logger } from './logging.ts'
32
32
  import type { MediaFileStore } from './media-files.ts'
33
+ import { tracedJob } from './telemetry.ts'
33
34
  import type { WebhookService } from './webhooks.ts'
34
35
 
35
36
  export interface JobsOptions {
@@ -133,7 +134,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
133
134
  return run
134
135
  }
135
136
 
136
- async function runScheduledPublishing(now = new Date()): Promise<ScheduledRun> {
137
+ async function runScheduledPublishingUntraced(now = new Date()): Promise<ScheduledRun> {
137
138
  const run: ScheduledRun = { published: [], unpublished: [], failed: [] }
138
139
  for (const due of await documents.dueSchedules(now)) {
139
140
  if (!(await documents.claimSchedule(due.id))) continue
@@ -159,7 +160,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
159
160
  return run
160
161
  }
161
162
 
162
- async function runEvents(now?: Date): Promise<WorkflowRunReport> {
163
+ async function runEventsUntraced(now?: Date): Promise<WorkflowRunReport> {
163
164
  // A run a commit already started finishes first, so this sees what it left.
164
165
  await options.dispatcher?.settled()
165
166
  return (
@@ -191,19 +192,21 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
191
192
  await pruneCacheInstructions(options.db, new Date(now.getTime() - 86_400_000))
192
193
  }
193
194
 
194
- async function runContentNotifications(now = new Date()): Promise<ContentNotificationRunReport> {
195
+ async function runContentNotificationsUntraced(
196
+ now = new Date(),
197
+ ): Promise<ContentNotificationRunReport> {
195
198
  // What is waiting in the outbox is queued first, so it goes in this run.
196
199
  await runEvents(now)
197
200
  const runner = options.contentNotifications
198
201
  return runner ? runner.runDue(now) : { claimed: 0, sent: 0, skipped: 0, retrying: 0, failed: 0 }
199
202
  }
200
203
 
201
- async function runAuditRetention(now = new Date()): Promise<number> {
204
+ async function runAuditRetentionUntraced(now = new Date()): Promise<number> {
202
205
  const before = auditRetainedSince(options.auditRetentionDays ?? 0, now)
203
206
  return before ? new AuditLog(options.db).prune(before) : 0
204
207
  }
205
208
 
206
- async function runVersionCleanup(now = new Date()) {
209
+ async function runVersionCleanupUntraced(now = new Date()) {
207
210
  return documents.cleanupVersions(now, options.versionCleanup)
208
211
  }
209
212
 
@@ -211,7 +214,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
211
214
  const notBefore = (asked: Date | undefined) =>
212
215
  new Date(Math.max(asked?.getTime() ?? 0, Date.now()))
213
216
 
214
- async function runWebhooks(now?: Date): Promise<WorkflowRunReport> {
217
+ async function runWebhooksUntraced(now?: Date): Promise<WorkflowRunReport> {
215
218
  await runEvents(now)
216
219
  return (
217
220
  (await options.webhooks?.runDue(notBefore(now))) ?? {
@@ -223,7 +226,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
223
226
  )
224
227
  }
225
228
 
226
- async function runFormWorkflows(now = new Date()): Promise<WorkflowRunReport> {
229
+ async function runFormWorkflowsUntraced(now = new Date()): Promise<WorkflowRunReport> {
227
230
  return (
228
231
  (await options.formWorkflows?.runDue(now)) ?? {
229
232
  claimed: 0,
@@ -271,6 +274,20 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
271
274
  timers.push(timer)
272
275
  }
273
276
 
277
+ // Story 262: each run a span and a count, on the role that ran it. The search
278
+ // indexing tick and the queue's upkeep, every few seconds whether or not there
279
+ // is work, are left out, so a quiet site sends nothing.
280
+ const runScheduledPublishing = tracedJob('scheduled publishing', runScheduledPublishingUntraced)
281
+ const runEvents = tracedJob('events', runEventsUntraced)
282
+ const runContentNotifications = tracedJob(
283
+ 'content notifications',
284
+ runContentNotificationsUntraced,
285
+ )
286
+ const runAuditRetention = tracedJob('audit retention', runAuditRetentionUntraced)
287
+ const runVersionCleanup = tracedJob('version cleanup', runVersionCleanupUntraced)
288
+ const runWebhooks = tracedJob('webhooks', runWebhooksUntraced)
289
+ const runFormWorkflows = tracedJob('form workflows', runFormWorkflowsUntraced)
290
+
274
291
  return {
275
292
  runScheduledPublishing,
276
293
  runVersionCleanup,
package/src/logging.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  type LogRecord,
19
19
  type Sink,
20
20
  } from '@logtape/logtape'
21
+ import { activeTraceIds, telemetryLogSink } from './telemetry.ts'
21
22
 
22
23
  /** Serilog's level names, which the log viewer filters and counts by. */
23
24
  export const SERILOG_LEVELS: Record<LogLevel, string> = {
@@ -56,6 +57,8 @@ export function toClef(record: LogRecord): Record<string, unknown> {
56
57
  error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : String(error)
57
58
  for (const [name, value] of Object.entries(properties)) event[name] = renderValue(value)
58
59
  event.SourceContext = record.category.join('.')
60
+ // Story 262: the trace it was written under, to find it beside its spans.
61
+ Object.assign(event, activeTraceIds())
59
62
  event.MachineName = hostname()
60
63
  event.ProcessId = process.pid
61
64
  return event
@@ -95,12 +98,14 @@ export function configureLogging(options: LoggingOptions): void {
95
98
  sinks: {
96
99
  file: getClefFileSink(options.logsDir),
97
100
  console: getConsoleSink(),
101
+ // Story 262: sends nothing until telemetry has started with a collector to send to.
102
+ telemetry: telemetryLogSink(),
98
103
  },
99
104
  loggers: [
100
105
  {
101
106
  category: ['crombolo'],
102
107
  lowestLevel: options.level,
103
- sinks: options.console ? ['file', 'console'] : ['file'],
108
+ sinks: options.console ? ['file', 'console', 'telemetry'] : ['file', 'telemetry'],
104
109
  },
105
110
  // The development 501 log prints its own line; its events only go to the file
106
111
  {