@crombolo/server 0.46.1 → 0.48.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/src/jobs.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  } from '@crombolo/data'
22
22
  import type { PublishedCache } from '@crombolo/render'
23
23
  import { auditRetainedSince } from './adapters/audit.ts'
24
+ import { createElementPort } from './adapters/elements.ts'
24
25
  import type { Approvals } from './approvals.ts'
25
26
  import type { ContentDispatcher } from './content-dispatch.ts'
26
27
  import type {
@@ -30,6 +31,7 @@ import type {
30
31
  import type { WorkflowRunner, WorkflowRunReport } from './form-workflows.ts'
31
32
  import { logger } from './logging.ts'
32
33
  import type { MediaFileStore } from './media-files.ts'
34
+ import { tracedJob } from './telemetry.ts'
33
35
  import type { WebhookService } from './webhooks.ts'
34
36
 
35
37
  export interface JobsOptions {
@@ -121,6 +123,16 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
121
123
  nodeState: options.nodeState,
122
124
  nodeId: options.nodeId,
123
125
  })
126
+ const elementRows = new DocumentRepository(options.db, {
127
+ nodeState: options.nodeState,
128
+ nodeId: options.nodeId,
129
+ kind: 'element',
130
+ })
131
+ const elements = createElementPort(options.db, {
132
+ nodeState: options.nodeState,
133
+ nodeId: options.nodeId,
134
+ onChange: () => options.cache.invalidate(),
135
+ })
124
136
  const timers: Array<ReturnType<typeof setInterval>> = []
125
137
  const search = new SearchIndex(options.db)
126
138
  let indexing: Promise<number> | undefined
@@ -133,7 +145,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
133
145
  return run
134
146
  }
135
147
 
136
- async function runScheduledPublishing(now = new Date()): Promise<ScheduledRun> {
148
+ async function runScheduledPublishingUntraced(now = new Date()): Promise<ScheduledRun> {
137
149
  const run: ScheduledRun = { published: [], unpublished: [], failed: [] }
138
150
  for (const due of await documents.dueSchedules(now)) {
139
151
  if (!(await documents.claimSchedule(due.id))) continue
@@ -154,12 +166,23 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
154
166
  result.ok ? { ok: true } : { ok: false, reason: result.reason },
155
167
  )
156
168
  }
169
+ // Library elements: no approvals and no redirects, so the port publishes them directly.
170
+ for (const due of await elementRows.dueSchedules(now)) {
171
+ if (!(await elementRows.claimSchedule(due.id))) continue
172
+ const cultures = due.culture ? [due.culture] : null
173
+ const result =
174
+ due.action === 'Release'
175
+ ? await elements.publish(due.key, cultures)
176
+ : await elements.unpublish(due.key, cultures)
177
+ if (result.ok) (due.action === 'Release' ? run.published : run.unpublished).push(due.key)
178
+ else run.failed.push({ key: due.key, reason: result.reason })
179
+ }
157
180
  await options.approvals?.sweepScheduled(now.getTime())
158
181
  // The operations recorded, announced and refreshed what they did themselves.
159
182
  return run
160
183
  }
161
184
 
162
- async function runEvents(now?: Date): Promise<WorkflowRunReport> {
185
+ async function runEventsUntraced(now?: Date): Promise<WorkflowRunReport> {
163
186
  // A run a commit already started finishes first, so this sees what it left.
164
187
  await options.dispatcher?.settled()
165
188
  return (
@@ -191,19 +214,21 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
191
214
  await pruneCacheInstructions(options.db, new Date(now.getTime() - 86_400_000))
192
215
  }
193
216
 
194
- async function runContentNotifications(now = new Date()): Promise<ContentNotificationRunReport> {
217
+ async function runContentNotificationsUntraced(
218
+ now = new Date(),
219
+ ): Promise<ContentNotificationRunReport> {
195
220
  // What is waiting in the outbox is queued first, so it goes in this run.
196
221
  await runEvents(now)
197
222
  const runner = options.contentNotifications
198
223
  return runner ? runner.runDue(now) : { claimed: 0, sent: 0, skipped: 0, retrying: 0, failed: 0 }
199
224
  }
200
225
 
201
- async function runAuditRetention(now = new Date()): Promise<number> {
226
+ async function runAuditRetentionUntraced(now = new Date()): Promise<number> {
202
227
  const before = auditRetainedSince(options.auditRetentionDays ?? 0, now)
203
228
  return before ? new AuditLog(options.db).prune(before) : 0
204
229
  }
205
230
 
206
- async function runVersionCleanup(now = new Date()) {
231
+ async function runVersionCleanupUntraced(now = new Date()) {
207
232
  return documents.cleanupVersions(now, options.versionCleanup)
208
233
  }
209
234
 
@@ -211,7 +236,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
211
236
  const notBefore = (asked: Date | undefined) =>
212
237
  new Date(Math.max(asked?.getTime() ?? 0, Date.now()))
213
238
 
214
- async function runWebhooks(now?: Date): Promise<WorkflowRunReport> {
239
+ async function runWebhooksUntraced(now?: Date): Promise<WorkflowRunReport> {
215
240
  await runEvents(now)
216
241
  return (
217
242
  (await options.webhooks?.runDue(notBefore(now))) ?? {
@@ -223,7 +248,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
223
248
  )
224
249
  }
225
250
 
226
- async function runFormWorkflows(now = new Date()): Promise<WorkflowRunReport> {
251
+ async function runFormWorkflowsUntraced(now = new Date()): Promise<WorkflowRunReport> {
227
252
  return (
228
253
  (await options.formWorkflows?.runDue(now)) ?? {
229
254
  claimed: 0,
@@ -271,6 +296,20 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
271
296
  timers.push(timer)
272
297
  }
273
298
 
299
+ // Story 262: each run a span and a count, on the role that ran it. The search
300
+ // indexing tick and the queue's upkeep, every few seconds whether or not there
301
+ // is work, are left out, so a quiet site sends nothing.
302
+ const runScheduledPublishing = tracedJob('scheduled publishing', runScheduledPublishingUntraced)
303
+ const runEvents = tracedJob('events', runEventsUntraced)
304
+ const runContentNotifications = tracedJob(
305
+ 'content notifications',
306
+ runContentNotificationsUntraced,
307
+ )
308
+ const runAuditRetention = tracedJob('audit retention', runAuditRetentionUntraced)
309
+ const runVersionCleanup = tracedJob('version cleanup', runVersionCleanupUntraced)
310
+ const runWebhooks = tracedJob('webhooks', runWebhooksUntraced)
311
+ const runFormWorkflows = tracedJob('form workflows', runFormWorkflowsUntraced)
312
+
274
313
  return {
275
314
  runScheduledPublishing,
276
315
  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
  {
@@ -99,6 +99,8 @@ export interface MemberAuth {
99
99
  * error page for one who is signed in but not allowed.
100
100
  */
101
101
  decide(content: PublishedContent, member: RequestMember | undefined): Promise<AccessDecision>
102
+ /** A member by key, as a page sees them, for previewing as them (story 264). */
103
+ byKey(key: string): Promise<RequestMember | undefined>
102
104
  /** Handles the member endpoints, or undefined when the path is not one. */
103
105
  handle(request: Request, pathname: string): Promise<Response | undefined>
104
106
  /** The `Set-Cookie` value that ends a member's site session. */
@@ -586,6 +588,10 @@ export function createMemberAuth(
586
588
  resolve,
587
589
  session,
588
590
  decide,
591
+ async byKey(key) {
592
+ const member = await members.byKey(key)
593
+ return member ? asRequestMember(member) : undefined
594
+ },
589
595
  signOutCookie: () => expireCookie(cookie, config.secureCookies),
590
596
  externalSignInUrl: (providerId, returnUrl) =>
591
597
  config.memberIdentityProviders.some((p) => p.oidc.id === providerId)
package/src/owner-jobs.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  } from '@crombolo/data'
15
15
  import { type Cron, isTimezone, nextOccurrence, parseCron } from './cron.ts'
16
16
  import { logger } from './logging.ts'
17
+ import { inSpan, recordJob } from './telemetry.ts'
17
18
 
18
19
  /**
19
20
  * Core's own queued work (story 246). A bundle's id is letters, digits and
@@ -273,14 +274,26 @@ export function createJobRunner(options: {
273
274
  enqueue: (name: string, payload?: unknown) =>
274
275
  enqueue(owner.id, name, payload, `job ${job.id}`),
275
276
  })
277
+ // Story 262: each run a span, on the role that ran it, and counted by outcome.
278
+ const started = performance.now()
279
+ const attributes = { 'crombolo.job.name': `${job.owner}/${job.name}` }
280
+ let outcome = 'succeeded'
276
281
  try {
277
- await handler(job.payload, { ...owner.context(), job: info })
282
+ await inSpan(
283
+ `job ${job.owner}/${job.name}`,
284
+ { ...attributes, 'crombolo.job.attempt': job.attempts },
285
+ async () => {
286
+ await handler(job.payload, { ...owner.context(), job: info })
287
+ },
288
+ )
278
289
  await jobs.succeed(job.id)
279
290
  } catch (error) {
280
291
  if (signal.aborted) {
292
+ outcome = 'released'
281
293
  await jobs.release(job.id)
282
294
  return
283
295
  }
296
+ outcome = 'failed'
284
297
  const message = (error instanceof Error ? error.message : String(error)).slice(0, MAX_ERROR)
285
298
  const retryAt =
286
299
  job.attempts < job.maxAttempts
@@ -295,6 +308,10 @@ export function createJobRunner(options: {
295
308
  })
296
309
  } finally {
297
310
  clearInterval(heartbeat)
311
+ recordJob((performance.now() - started) / 1000, {
312
+ ...attributes,
313
+ 'crombolo.job.outcome': outcome,
314
+ })
298
315
  }
299
316
  }
300
317
 
package/src/ports.ts CHANGED
@@ -587,6 +587,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
587
587
  ).memberAuthorization.clientCredentialsFlow.associatedMembers.map((m) => m.userName),
588
588
  })
589
589
  deps.publicAccess = createPublicAccessPort(options.db, {
590
+ nodeId: options.schema?.nodeId,
590
591
  onChange: () => options.cache?.invalidate(),
591
592
  })
592
593
  deps.elements = createElementPort(options.db, {