@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/package.json +26 -13
- package/src/adapters/documents.ts +60 -10
- package/src/adapters/elements.ts +20 -3
- package/src/adapters/health.ts +44 -0
- package/src/adapters/public-access.ts +14 -3
- package/src/component-snippets.ts +48 -0
- package/src/config.ts +53 -3
- package/src/core.ts +17 -3
- package/src/database.ts +29 -0
- package/src/index.ts +1 -0
- package/src/jobs.ts +46 -7
- package/src/logging.ts +6 -1
- package/src/member-auth.ts +6 -0
- package/src/owner-jobs.ts +18 -1
- package/src/ports.ts +1 -0
- package/src/server.ts +515 -55
- package/src/settings.ts +117 -0
- package/src/site-assets.ts +72 -0
- package/src/site-search.ts +2 -2
- package/src/telemetry.ts +541 -0
- package/src/webhooks.ts +24 -2
- package/src/worker.ts +2 -0
package/src/telemetry.ts
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Traces, metrics and logs over OpenTelemetry (story 262), sent to whatever
|
|
3
|
+
* collector the site names, and nothing at all without one. The SDK is loaded
|
|
4
|
+
* only when an endpoint is set; until then `@opentelemetry/api` answers every
|
|
5
|
+
* span and instrument with a no-op. Spans are made by hand at the server's own
|
|
6
|
+
* seams, since automatic instrumentation does not run on Bun.
|
|
7
|
+
* docs/operations.md, "Telemetry".
|
|
8
|
+
*
|
|
9
|
+
* What is sent is shapes and ids: never a member, an e-mail address, a form's
|
|
10
|
+
* answer, a query string's values or a page's content.
|
|
11
|
+
* `tests/telemetry.test.ts` holds every attribute to its allow-list.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { type Db, queryFor } from '@crombolo/data'
|
|
15
|
+
import type { Sink } from '@logtape/logtape'
|
|
16
|
+
import {
|
|
17
|
+
type Attributes,
|
|
18
|
+
type Context,
|
|
19
|
+
type Counter,
|
|
20
|
+
context,
|
|
21
|
+
type Histogram,
|
|
22
|
+
logs,
|
|
23
|
+
metrics,
|
|
24
|
+
propagation,
|
|
25
|
+
ROOT_CONTEXT,
|
|
26
|
+
type Span,
|
|
27
|
+
SpanKind,
|
|
28
|
+
SpanStatusCode,
|
|
29
|
+
trace,
|
|
30
|
+
} from '@opentelemetry/api'
|
|
31
|
+
import { VERSION } from './config.ts'
|
|
32
|
+
import type { EmailPort } from './email.ts'
|
|
33
|
+
|
|
34
|
+
export interface TelemetryOptions {
|
|
35
|
+
/** The collector's base address, as `OTEL_EXPORTER_OTLP_ENDPOINT`, which wins. */
|
|
36
|
+
endpoint?: string
|
|
37
|
+
/** The service's name, as `OTEL_SERVICE_NAME`, which wins; the site's name otherwise. */
|
|
38
|
+
serviceName?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Whether anything is sent, where, and as what: for the diagnostics screen. */
|
|
42
|
+
export interface TelemetryStatus {
|
|
43
|
+
enabled: boolean
|
|
44
|
+
endpoint?: string
|
|
45
|
+
serviceName?: string
|
|
46
|
+
role?: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type Environment = Record<string, string | undefined>
|
|
50
|
+
|
|
51
|
+
let status: TelemetryStatus = { enabled: false }
|
|
52
|
+
let shutdown: (() => Promise<void>) | undefined
|
|
53
|
+
let flush: (() => Promise<void>) | undefined
|
|
54
|
+
|
|
55
|
+
export const telemetryStatus = (): TelemetryStatus => status
|
|
56
|
+
|
|
57
|
+
/** The collector named by the standard variables or the site's config; undefined for none. Pure. */
|
|
58
|
+
export function telemetryEndpoint(
|
|
59
|
+
options: TelemetryOptions | undefined,
|
|
60
|
+
env: Environment = process.env,
|
|
61
|
+
): string | undefined {
|
|
62
|
+
const named =
|
|
63
|
+
env.OTEL_EXPORTER_OTLP_ENDPOINT ||
|
|
64
|
+
env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ||
|
|
65
|
+
env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT ||
|
|
66
|
+
env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT ||
|
|
67
|
+
options?.endpoint
|
|
68
|
+
return named?.trim() || undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const instruments = {
|
|
72
|
+
requestDuration: undefined as Histogram | undefined,
|
|
73
|
+
renderDuration: undefined as Histogram | undefined,
|
|
74
|
+
cacheLookups: undefined as Counter | undefined,
|
|
75
|
+
jobRuns: undefined as Counter | undefined,
|
|
76
|
+
jobDuration: undefined as Histogram | undefined,
|
|
77
|
+
webhookDeliveries: undefined as Counter | undefined,
|
|
78
|
+
webhookRetries: undefined as Counter | undefined,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Starts the SDK when a collector is named, for this node's role. Once per
|
|
83
|
+
* process: a second server in the same process shares the first's.
|
|
84
|
+
*/
|
|
85
|
+
export async function startTelemetry(options: {
|
|
86
|
+
telemetry?: TelemetryOptions
|
|
87
|
+
siteName: string
|
|
88
|
+
role: string
|
|
89
|
+
nodeId: string
|
|
90
|
+
db?: Db
|
|
91
|
+
env?: Environment
|
|
92
|
+
}): Promise<TelemetryStatus> {
|
|
93
|
+
const env = options.env ?? process.env
|
|
94
|
+
const endpoint = telemetryEndpoint(options.telemetry, env)
|
|
95
|
+
if (!endpoint || status.enabled) return status
|
|
96
|
+
const [
|
|
97
|
+
{ AsyncLocalStorageContextManager },
|
|
98
|
+
{ W3CTraceContextPropagator },
|
|
99
|
+
{ resourceFromAttributes },
|
|
100
|
+
{ TracerProvider, BatchSpanProcessor },
|
|
101
|
+
{ MeterProvider, PeriodicExportingMetricReader },
|
|
102
|
+
{ LoggerProvider, BatchLogRecordProcessor },
|
|
103
|
+
exporters,
|
|
104
|
+
] = await Promise.all([
|
|
105
|
+
import('@opentelemetry/context-async-hooks'),
|
|
106
|
+
import('@opentelemetry/core'),
|
|
107
|
+
import('@opentelemetry/resources'),
|
|
108
|
+
import('@opentelemetry/sdk-trace'),
|
|
109
|
+
import('@opentelemetry/sdk-metrics'),
|
|
110
|
+
import('@opentelemetry/sdk-logs'),
|
|
111
|
+
loadExporters(env),
|
|
112
|
+
])
|
|
113
|
+
const serviceName = env.OTEL_SERVICE_NAME || options.telemetry?.serviceName || options.siteName
|
|
114
|
+
const resource = resourceFromAttributes({
|
|
115
|
+
'service.name': serviceName,
|
|
116
|
+
'service.version': VERSION,
|
|
117
|
+
'service.instance.id': options.nodeId,
|
|
118
|
+
'crombolo.node.role': options.role,
|
|
119
|
+
}).merge(resourceFromAttributes(pairsOf(env.OTEL_RESOURCE_ATTRIBUTES)))
|
|
120
|
+
// The variables name the collector's base; the config's does too, so each signal's path is added.
|
|
121
|
+
const url = (signal: string) =>
|
|
122
|
+
env.OTEL_EXPORTER_OTLP_ENDPOINT ||
|
|
123
|
+
env[`OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_ENDPOINT`] ||
|
|
124
|
+
!options.telemetry?.endpoint
|
|
125
|
+
? undefined
|
|
126
|
+
: `${options.telemetry.endpoint.replace(/\/+$/, '')}/v1/${signal}`
|
|
127
|
+
// Read here, not left to the exporters, so a reader of this file sees every variable.
|
|
128
|
+
const headers = pairsOf(env.OTEL_EXPORTER_OTLP_HEADERS)
|
|
129
|
+
const at = (signal: string) => {
|
|
130
|
+
const address = url(signal)
|
|
131
|
+
return { ...(address ? { url: address } : {}), headers }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const contextManager = new AsyncLocalStorageContextManager().enable()
|
|
135
|
+
context.setGlobalContextManager(contextManager)
|
|
136
|
+
propagation.setGlobalPropagator(new W3CTraceContextPropagator())
|
|
137
|
+
const tracerProvider = new TracerProvider({
|
|
138
|
+
resource,
|
|
139
|
+
sampler: await samplerFromEnv(env),
|
|
140
|
+
spanProcessors: [new BatchSpanProcessor({ exporter: new exporters.Trace(at('traces')) })],
|
|
141
|
+
})
|
|
142
|
+
trace.setGlobalTracerProvider(tracerProvider)
|
|
143
|
+
const meterProvider = new MeterProvider({
|
|
144
|
+
resource,
|
|
145
|
+
readers: [
|
|
146
|
+
new PeriodicExportingMetricReader({
|
|
147
|
+
exporter: new exporters.Metric(at('metrics')),
|
|
148
|
+
exportIntervalMillis: Number(env.OTEL_METRIC_EXPORT_INTERVAL) || 60_000,
|
|
149
|
+
}),
|
|
150
|
+
],
|
|
151
|
+
})
|
|
152
|
+
metrics.setGlobalMeterProvider(meterProvider)
|
|
153
|
+
const loggerProvider = new LoggerProvider({
|
|
154
|
+
resource,
|
|
155
|
+
processors: [new BatchLogRecordProcessor({ exporter: new exporters.Log(at('logs')) })],
|
|
156
|
+
})
|
|
157
|
+
logs.setGlobalLoggerProvider(loggerProvider)
|
|
158
|
+
createInstruments(options.db)
|
|
159
|
+
|
|
160
|
+
status = {
|
|
161
|
+
enabled: true,
|
|
162
|
+
endpoint: url('traces')?.replace(/\/v1\/traces$/, '') ?? endpoint,
|
|
163
|
+
serviceName,
|
|
164
|
+
role: options.role,
|
|
165
|
+
}
|
|
166
|
+
flush = async () => {
|
|
167
|
+
await Promise.all([
|
|
168
|
+
tracerProvider.forceFlush(),
|
|
169
|
+
meterProvider.forceFlush(),
|
|
170
|
+
loggerProvider.forceFlush(),
|
|
171
|
+
])
|
|
172
|
+
}
|
|
173
|
+
shutdown = async () => {
|
|
174
|
+
await Promise.all([
|
|
175
|
+
tracerProvider.shutdown(),
|
|
176
|
+
meterProvider.shutdown(),
|
|
177
|
+
loggerProvider.shutdown(),
|
|
178
|
+
]).catch(() => {})
|
|
179
|
+
trace.disable()
|
|
180
|
+
metrics.disable()
|
|
181
|
+
logs.disable()
|
|
182
|
+
propagation.disable()
|
|
183
|
+
context.disable()
|
|
184
|
+
for (const name of Object.keys(instruments))
|
|
185
|
+
instruments[name as keyof typeof instruments] = undefined
|
|
186
|
+
status = { enabled: false }
|
|
187
|
+
}
|
|
188
|
+
return status
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Sends what is waiting now; for a test, and before a node stops. */
|
|
192
|
+
export const flushTelemetry = async (): Promise<void> => flush?.()
|
|
193
|
+
|
|
194
|
+
/** Stops the SDK, sending what is waiting. */
|
|
195
|
+
export async function stopTelemetry(): Promise<void> {
|
|
196
|
+
const stop = shutdown
|
|
197
|
+
shutdown = undefined
|
|
198
|
+
flush = undefined
|
|
199
|
+
await stop?.()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** `a=1,b=two%20words`, as the specification writes headers and resource attributes. Pure. */
|
|
203
|
+
export function pairsOf(text: string | undefined): Record<string, string> {
|
|
204
|
+
const pairs: Record<string, string> = {}
|
|
205
|
+
for (const part of (text ?? '').split(',')) {
|
|
206
|
+
const at = part.indexOf('=')
|
|
207
|
+
if (at <= 0) continue
|
|
208
|
+
const name = part.slice(0, at).trim()
|
|
209
|
+
const value = part.slice(at + 1).trim()
|
|
210
|
+
try {
|
|
211
|
+
pairs[decodeURIComponent(name)] = decodeURIComponent(value)
|
|
212
|
+
} catch {
|
|
213
|
+
pairs[name] = value
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return pairs
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The exporters for `OTEL_EXPORTER_OTLP_PROTOCOL`: protobuf, as the specification's default, or JSON. */
|
|
220
|
+
async function loadExporters(env: Environment) {
|
|
221
|
+
const protocol = (signal: string) =>
|
|
222
|
+
env[`OTEL_EXPORTER_OTLP_${signal}_PROTOCOL`] ||
|
|
223
|
+
env.OTEL_EXPORTER_OTLP_PROTOCOL ||
|
|
224
|
+
'http/protobuf'
|
|
225
|
+
const json = (signal: string) => protocol(signal) === 'http/json'
|
|
226
|
+
const [traces, metricsExporter, logsExporter] = await Promise.all([
|
|
227
|
+
json('TRACES')
|
|
228
|
+
? import('@opentelemetry/exporter-trace-otlp-http')
|
|
229
|
+
: import('@opentelemetry/exporter-trace-otlp-proto'),
|
|
230
|
+
json('METRICS')
|
|
231
|
+
? import('@opentelemetry/exporter-metrics-otlp-http')
|
|
232
|
+
: import('@opentelemetry/exporter-metrics-otlp-proto'),
|
|
233
|
+
json('LOGS')
|
|
234
|
+
? import('@opentelemetry/exporter-logs-otlp-http')
|
|
235
|
+
: import('@opentelemetry/exporter-logs-otlp-proto'),
|
|
236
|
+
])
|
|
237
|
+
return {
|
|
238
|
+
Trace: traces.OTLPTraceExporter,
|
|
239
|
+
Metric: metricsExporter.OTLPMetricExporter,
|
|
240
|
+
Log: logsExporter.OTLPLogExporter,
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** `OTEL_TRACES_SAMPLER` and its argument, as the specification names them; every trace by default. */
|
|
245
|
+
async function samplerFromEnv(env: Environment) {
|
|
246
|
+
const { AlwaysOffSampler, AlwaysOnSampler, ParentBasedSampler, TraceIdRatioBasedSampler } =
|
|
247
|
+
await import('@opentelemetry/sdk-trace')
|
|
248
|
+
const ratio = () => {
|
|
249
|
+
const value = Number(env.OTEL_TRACES_SAMPLER_ARG)
|
|
250
|
+
return new TraceIdRatioBasedSampler(
|
|
251
|
+
Number.isFinite(value) && value >= 0 && value <= 1 ? value : 1,
|
|
252
|
+
)
|
|
253
|
+
}
|
|
254
|
+
switch (env.OTEL_TRACES_SAMPLER?.trim()) {
|
|
255
|
+
case 'always_on':
|
|
256
|
+
return new AlwaysOnSampler()
|
|
257
|
+
case 'always_off':
|
|
258
|
+
return new AlwaysOffSampler()
|
|
259
|
+
case 'traceidratio':
|
|
260
|
+
return ratio()
|
|
261
|
+
case 'parentbased_always_off':
|
|
262
|
+
return new ParentBasedSampler({ root: new AlwaysOffSampler() })
|
|
263
|
+
case 'parentbased_traceidratio':
|
|
264
|
+
return new ParentBasedSampler({ root: ratio() })
|
|
265
|
+
default:
|
|
266
|
+
return new ParentBasedSampler({ root: new AlwaysOnSampler() })
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function createInstruments(db: Db | undefined) {
|
|
271
|
+
const meter = metrics.getMeter('crombolo', VERSION)
|
|
272
|
+
instruments.requestDuration = meter.createHistogram('http.server.request.duration', {
|
|
273
|
+
unit: 's',
|
|
274
|
+
description: 'How long the server took to answer a request.',
|
|
275
|
+
})
|
|
276
|
+
instruments.renderDuration = meter.createHistogram('crombolo.render.duration', {
|
|
277
|
+
unit: 's',
|
|
278
|
+
description: 'How long a page took to render.',
|
|
279
|
+
})
|
|
280
|
+
instruments.cacheLookups = meter.createCounter('crombolo.published_cache.lookups', {
|
|
281
|
+
description: 'Reads of the published content, answered from the snapshot or after building it.',
|
|
282
|
+
})
|
|
283
|
+
instruments.jobRuns = meter.createCounter('crombolo.job.runs', {
|
|
284
|
+
description: 'Background job runs, by outcome.',
|
|
285
|
+
})
|
|
286
|
+
instruments.jobDuration = meter.createHistogram('crombolo.job.duration', {
|
|
287
|
+
unit: 's',
|
|
288
|
+
description: 'How long a background job ran.',
|
|
289
|
+
})
|
|
290
|
+
instruments.webhookDeliveries = meter.createCounter('crombolo.webhook.deliveries', {
|
|
291
|
+
description: 'Webhook deliveries, by outcome.',
|
|
292
|
+
})
|
|
293
|
+
instruments.webhookRetries = meter.createCounter('crombolo.webhook.retries', {
|
|
294
|
+
description: 'Webhook deliveries that will be tried again.',
|
|
295
|
+
})
|
|
296
|
+
if (db) {
|
|
297
|
+
const queue = meter.createObservableGauge('crombolo.job.queue.depth', {
|
|
298
|
+
description: 'Background jobs waiting to run.',
|
|
299
|
+
})
|
|
300
|
+
queue.addCallback(async (result) => {
|
|
301
|
+
const { JobRepository } = await import('@crombolo/data')
|
|
302
|
+
const { total } = await new JobRepository(db).list({ state: 'queued', take: 0 })
|
|
303
|
+
result.observe(total)
|
|
304
|
+
})
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const tracer = () => trace.getTracer('crombolo', VERSION)
|
|
309
|
+
|
|
310
|
+
/** Runs `fn` in a span of its own, ending it however `fn` ends. */
|
|
311
|
+
export async function inSpan<T>(
|
|
312
|
+
name: string,
|
|
313
|
+
attributes: Attributes,
|
|
314
|
+
fn: (span: Span) => Promise<T>,
|
|
315
|
+
options: { kind?: SpanKind; parent?: Context } = {},
|
|
316
|
+
): Promise<T> {
|
|
317
|
+
return tracer().startActiveSpan(
|
|
318
|
+
name,
|
|
319
|
+
{ kind: options.kind ?? SpanKind.INTERNAL, attributes },
|
|
320
|
+
options.parent ?? context.active(),
|
|
321
|
+
async (span) => {
|
|
322
|
+
try {
|
|
323
|
+
return await fn(span)
|
|
324
|
+
} catch (error) {
|
|
325
|
+
span.recordException({ name: error instanceof Error ? error.name : 'Error' })
|
|
326
|
+
span.setStatus({ code: SpanStatusCode.ERROR })
|
|
327
|
+
throw error
|
|
328
|
+
} finally {
|
|
329
|
+
span.end()
|
|
330
|
+
}
|
|
331
|
+
},
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The span running now, if there is one. */
|
|
336
|
+
export const activeSpan = (): Span | undefined => trace.getActiveSpan()
|
|
337
|
+
|
|
338
|
+
/** Sets attributes on the span running now, if there is one. */
|
|
339
|
+
export function noteOnSpan(attributes: Attributes): void {
|
|
340
|
+
trace.getActiveSpan()?.setAttributes(attributes)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The trace a request continues: its `traceparent` from a trusted proxy, or a new one. */
|
|
344
|
+
export function requestContext(request: Request, trusted: boolean): Context {
|
|
345
|
+
if (!trusted || !request.headers.has('traceparent')) return ROOT_CONTEXT
|
|
346
|
+
return propagation.extract(ROOT_CONTEXT, Object.fromEntries(request.headers))
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The trace a context continues, if any. */
|
|
350
|
+
export const traceIdOf = (continued: Context): string | undefined =>
|
|
351
|
+
trace.getSpanContext(continued)?.traceId
|
|
352
|
+
|
|
353
|
+
/** `headers` with this trace's `traceparent`, so a receiver can join it. */
|
|
354
|
+
export function withTraceHeaders(headers: Record<string, string>): Record<string, string> {
|
|
355
|
+
const carrier: Record<string, string> = {}
|
|
356
|
+
propagation.inject(context.active(), carrier)
|
|
357
|
+
return { ...headers, ...carrier }
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** The route a request is counted under: a template, never the address itself. Pure. */
|
|
361
|
+
export function routeOf(pathname: string, backOfficePath: string): string {
|
|
362
|
+
if (pathname === '/health') return '/health'
|
|
363
|
+
if (pathname.startsWith('/umbraco/delivery/api/')) return '/umbraco/delivery/api/*'
|
|
364
|
+
if (pathname.startsWith(`${backOfficePath}/management/api/`))
|
|
365
|
+
return `${backOfficePath}/management/api/*`
|
|
366
|
+
if (pathname === backOfficePath || pathname.startsWith(`${backOfficePath}/`))
|
|
367
|
+
return `${backOfficePath}/*`
|
|
368
|
+
if (pathname.startsWith('/umbraco/')) return '/umbraco/*'
|
|
369
|
+
if (pathname.startsWith('/media/')) return '/media/*'
|
|
370
|
+
if (pathname.startsWith('/css/')) return '/css/*'
|
|
371
|
+
if (pathname.startsWith('/scripts/')) return '/scripts/*'
|
|
372
|
+
if (pathname.startsWith('/crombolo/')) return '/crombolo/*'
|
|
373
|
+
return '/{page}'
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export const recordRequest = (seconds: number, attributes: Attributes) =>
|
|
377
|
+
instruments.requestDuration?.record(seconds, attributes)
|
|
378
|
+
export const recordRender = (seconds: number, attributes: Attributes) =>
|
|
379
|
+
instruments.renderDuration?.record(seconds, attributes)
|
|
380
|
+
export const recordCacheLookup = (hit: boolean) =>
|
|
381
|
+
instruments.cacheLookups?.add(1, { 'crombolo.cache.result': hit ? 'hit' : 'miss' })
|
|
382
|
+
export const recordJob = (seconds: number, attributes: Attributes) => {
|
|
383
|
+
instruments.jobRuns?.add(1, attributes)
|
|
384
|
+
instruments.jobDuration?.record(seconds, attributes)
|
|
385
|
+
}
|
|
386
|
+
export const recordWebhook = (outcome: 'delivered' | 'failed', retry: boolean) => {
|
|
387
|
+
instruments.webhookDeliveries?.add(1, { 'crombolo.webhook.outcome': outcome })
|
|
388
|
+
if (retry) instruments.webhookRetries?.add(1)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** `fn` as a job whose every run is a span and a count, by outcome. */
|
|
392
|
+
export function tracedJob<A extends unknown[], R>(
|
|
393
|
+
name: string,
|
|
394
|
+
fn: (...args: A) => Promise<R>,
|
|
395
|
+
): (...args: A) => Promise<R> {
|
|
396
|
+
return async (...args) => {
|
|
397
|
+
const started = performance.now()
|
|
398
|
+
let outcome = 'succeeded'
|
|
399
|
+
try {
|
|
400
|
+
return await inSpan(`job ${name}`, { 'crombolo.job.name': name }, () => fn(...args))
|
|
401
|
+
} catch (error) {
|
|
402
|
+
outcome = 'failed'
|
|
403
|
+
throw error
|
|
404
|
+
} finally {
|
|
405
|
+
if (status.enabled)
|
|
406
|
+
recordJob((performance.now() - started) / 1000, {
|
|
407
|
+
'crombolo.job.name': name,
|
|
408
|
+
'crombolo.job.outcome': outcome,
|
|
409
|
+
})
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** A statement as a span names it: its operation and first table, never its values. Pure. */
|
|
415
|
+
export function statementSummary(sql: string): { operation: string; summary: string } {
|
|
416
|
+
const text = sql.trim().replace(/\s+/g, ' ')
|
|
417
|
+
const operation = (/^\w+/.exec(text)?.[0] ?? 'QUERY').toUpperCase()
|
|
418
|
+
const table = /\b(?:from|into|update|join|table)\s+"?([A-Za-z_][\w.]*)"?/i.exec(text)?.[1]
|
|
419
|
+
return { operation, summary: table ? `${operation} ${table}` : operation }
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* `db` with each statement a span (story 262): its operation, first table and
|
|
424
|
+
* text with placeholders, which never holds a value. Transactions and
|
|
425
|
+
* snapshots hand on a traced handle too.
|
|
426
|
+
*/
|
|
427
|
+
export function tracedDb(db: Db): Db {
|
|
428
|
+
if (!status.enabled) return db
|
|
429
|
+
const system = db.dialect.name === 'postgres' ? 'postgresql' : 'sqlite'
|
|
430
|
+
const run = <T>(sql: string, fn: () => Promise<T>) => {
|
|
431
|
+
// Only under a request's or a job's span: a poller's statements would each be a trace of their own.
|
|
432
|
+
if (!trace.getActiveSpan()) return fn()
|
|
433
|
+
const { operation, summary } = statementSummary(sql)
|
|
434
|
+
return inSpan(
|
|
435
|
+
summary,
|
|
436
|
+
{
|
|
437
|
+
'db.system.name': system,
|
|
438
|
+
'db.operation.name': operation,
|
|
439
|
+
'db.query.summary': summary,
|
|
440
|
+
'db.query.text': sql,
|
|
441
|
+
},
|
|
442
|
+
() => fn(),
|
|
443
|
+
{ kind: SpanKind.CLIENT },
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
const wrap = (handle: Db): Db => ({
|
|
447
|
+
dialect: handle.dialect,
|
|
448
|
+
locks: handle.locks,
|
|
449
|
+
get q() {
|
|
450
|
+
return queryFor(this)
|
|
451
|
+
},
|
|
452
|
+
query: (sql, params) => run(sql, () => handle.query(sql, params)),
|
|
453
|
+
exec: (sql, params) => run(sql, () => handle.exec(sql, params)),
|
|
454
|
+
transaction: (fn) => handle.transaction((tx) => fn(wrap(tx))),
|
|
455
|
+
readSnapshot: (fn) => handle.readSnapshot((reader) => fn(wrap(reader))),
|
|
456
|
+
close: () => handle.close(),
|
|
457
|
+
...(handle.confine
|
|
458
|
+
? {
|
|
459
|
+
confine: (role: string, schema: string) =>
|
|
460
|
+
wrap((handle.confine as NonNullable<Db['confine']>).call(handle, role, schema)),
|
|
461
|
+
}
|
|
462
|
+
: {}),
|
|
463
|
+
...(handle.listen ? { listen: handle.listen.bind(handle) } : {}),
|
|
464
|
+
})
|
|
465
|
+
return wrap(db)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** The site's e-mail with each message a span: its provider and outcome, never its addresses. */
|
|
469
|
+
export function tracedEmail<T extends EmailPort | undefined>(email: T): T {
|
|
470
|
+
if (!email) return email
|
|
471
|
+
return {
|
|
472
|
+
description: email.description,
|
|
473
|
+
provider: email.provider,
|
|
474
|
+
send: (message) =>
|
|
475
|
+
inSpan(
|
|
476
|
+
'email send',
|
|
477
|
+
{ 'crombolo.email.provider': email.provider },
|
|
478
|
+
async (span) => {
|
|
479
|
+
const result = await email.send(message)
|
|
480
|
+
span.setAttribute('crombolo.email.sent', result.ok)
|
|
481
|
+
return result
|
|
482
|
+
},
|
|
483
|
+
{ kind: SpanKind.CLIENT },
|
|
484
|
+
),
|
|
485
|
+
} as T
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const SEVERITY = { trace: 1, debug: 5, info: 9, warning: 13, error: 17, fatal: 21 } as const
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Log lines over OpenTelemetry, under the span they were written in: the
|
|
492
|
+
* message's template, never its values, which can name a member or an
|
|
493
|
+
* address, and the logger's category.
|
|
494
|
+
*/
|
|
495
|
+
export function telemetryLogSink(): Sink {
|
|
496
|
+
return (record) => {
|
|
497
|
+
if (!status.enabled) return
|
|
498
|
+
const template =
|
|
499
|
+
typeof record.rawMessage === 'string' ? record.rawMessage : record.rawMessage.join('{}')
|
|
500
|
+
logs.getLogger('crombolo', VERSION).emit({
|
|
501
|
+
timestamp: record.timestamp,
|
|
502
|
+
severityNumber: SEVERITY[record.level],
|
|
503
|
+
severityText: record.level.toUpperCase(),
|
|
504
|
+
body: template,
|
|
505
|
+
attributes: { 'crombolo.log.category': record.category.join('.') },
|
|
506
|
+
context: context.active(),
|
|
507
|
+
})
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** The trace and span ids a log line is written under, for the CLEF file; empty outside a span. */
|
|
512
|
+
export function activeTraceIds(): { TraceId?: string; SpanId?: string } {
|
|
513
|
+
const span = trace.getActiveSpan()?.spanContext()
|
|
514
|
+
if (!span || !status.enabled || span.traceId === '00000000000000000000000000000000') return {}
|
|
515
|
+
return { TraceId: span.traceId, SpanId: span.spanId }
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export { SpanKind }
|
|
519
|
+
|
|
520
|
+
/** Whether an address is one of the trusted proxies: an exact address, or an IPv4 range. Pure. */
|
|
521
|
+
export function isTrustedProxy(address: string | undefined, proxies: readonly string[]): boolean {
|
|
522
|
+
if (!address || proxies.length === 0) return false
|
|
523
|
+
const bare = address.replace(/^::ffff:/, '')
|
|
524
|
+
return proxies.some((proxy) => {
|
|
525
|
+
const [base, bits] = proxy.split('/')
|
|
526
|
+
if (bits === undefined) return base === bare || base === address
|
|
527
|
+
const prefix = Number(bits)
|
|
528
|
+
const from = ipv4(base ?? '')
|
|
529
|
+
const at = ipv4(bare)
|
|
530
|
+
if (from === undefined || at === undefined || !(prefix >= 0 && prefix <= 32)) return false
|
|
531
|
+
const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0
|
|
532
|
+
return (from & mask) === (at & mask)
|
|
533
|
+
})
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function ipv4(address: string): number | undefined {
|
|
537
|
+
const parts = address.split('.').map(Number)
|
|
538
|
+
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255))
|
|
539
|
+
return undefined
|
|
540
|
+
return parts.reduce((value, part) => ((value << 8) | part) >>> 0, 0)
|
|
541
|
+
}
|
package/src/webhooks.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
import { retryAfter, type WorkflowRunReport } from './form-workflows.ts'
|
|
19
19
|
import { logger } from './logging.ts'
|
|
20
20
|
import { openSecret, SECRET_KEY_VARIABLE, sealSecret, usableSecretKey } from './secrets.ts'
|
|
21
|
+
import { inSpan, recordWebhook, SpanKind, withTraceHeaders } from './telemetry.ts'
|
|
21
22
|
import {
|
|
22
23
|
envReference,
|
|
23
24
|
parseWebhookFile,
|
|
@@ -356,7 +357,27 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
|
|
|
356
357
|
return out
|
|
357
358
|
}
|
|
358
359
|
|
|
359
|
-
|
|
360
|
+
/** Story 262: each delivery a span, counted by outcome, with retries counted too. */
|
|
361
|
+
const deliverToWebhook = (
|
|
362
|
+
delivery: WebhookDelivery,
|
|
363
|
+
webhook: WebhookDefinition,
|
|
364
|
+
): Promise<{ ok: true } | { ok: false; error: string; retry: boolean }> =>
|
|
365
|
+
inSpan(
|
|
366
|
+
'webhook delivery',
|
|
367
|
+
{
|
|
368
|
+
'crombolo.webhook.event': delivery.eventAlias,
|
|
369
|
+
'crombolo.webhook.attempt': delivery.attempts,
|
|
370
|
+
},
|
|
371
|
+
async (span) => {
|
|
372
|
+
const result = await sendToWebhook(delivery, webhook)
|
|
373
|
+
span.setAttribute('crombolo.webhook.outcome', result.ok ? 'delivered' : 'failed')
|
|
374
|
+
recordWebhook(result.ok ? 'delivered' : 'failed', !result.ok && result.retry)
|
|
375
|
+
return result
|
|
376
|
+
},
|
|
377
|
+
{ kind: SpanKind.CLIENT },
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
const sendToWebhook = async (
|
|
360
381
|
delivery: WebhookDelivery,
|
|
361
382
|
webhook: WebhookDefinition,
|
|
362
383
|
): Promise<{ ok: true } | { ok: false; error: string; retry: boolean }> => {
|
|
@@ -386,7 +407,8 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
|
|
|
386
407
|
}
|
|
387
408
|
let headers: Record<string, string>
|
|
388
409
|
try {
|
|
389
|
-
|
|
410
|
+
// The receiver can join the trace; logged above without it, as it names no secret.
|
|
411
|
+
headers = withTraceHeaders({ ...resolveHeaders(webhook.headers), ...fixed })
|
|
390
412
|
} catch (error) {
|
|
391
413
|
const message = error instanceof Error ? error.message : String(error)
|
|
392
414
|
await deliveries.log({
|
package/src/worker.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { logger } from './logging.ts'
|
|
|
15
15
|
import type { JobRunner } from './owner-jobs.ts'
|
|
16
16
|
import type { SchemaBoot } from './schema.ts'
|
|
17
17
|
import { createSeoHost } from './seo.ts'
|
|
18
|
+
import { stopTelemetry } from './telemetry.ts'
|
|
18
19
|
|
|
19
20
|
export interface WorkerHealth {
|
|
20
21
|
/** False once the database is ahead of this node, as on any node that writes. */
|
|
@@ -133,6 +134,7 @@ export async function createWorker(config: CromboloConfig): Promise<WorkerHandle
|
|
|
133
134
|
poller.stop()
|
|
134
135
|
await closeTables(core.chains)
|
|
135
136
|
await db.close()
|
|
137
|
+
await stopTelemetry()
|
|
136
138
|
},
|
|
137
139
|
}
|
|
138
140
|
}
|