@danylohotvianskyi/bobra-framework 0.5.1 → 0.6.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.
@@ -0,0 +1,53 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { BobraMetricsCoordinator, collectObservabilityMetricGroups, mergeMetricFamilies, parseMetricsDuration, serializePrometheus } from './index';
3
+
4
+ describe('metrics battery', () => {
5
+ it('serializes stable Prometheus 0.0.4 text', () => {
6
+ expect(serializePrometheus([{ name: 'example_value', help: 'an example', type: 'gauge', samples: [{ labels: { z: 'two', a: 'one' }, value: 2 }] }]))
7
+ .toBe('# HELP example_value an example\n# TYPE example_value gauge\nexample_value{a="one",z="two"} 2\n');
8
+ });
9
+
10
+ it('omits conflicting samples and incompatible families', () => {
11
+ expect(mergeMetricFamilies([
12
+ [{ name: 'same', help: 'help', type: 'gauge', samples: [{ labels: { a: '1' }, value: 1 }] }],
13
+ [{ name: 'same', help: 'help', type: 'gauge', samples: [{ labels: { a: '1' }, value: 2 }] }],
14
+ [{ name: 'same', help: 'help', type: 'gauge', samples: [{ labels: { a: '1' }, value: 1 }] }],
15
+ [{ name: 'broken', help: 'one', type: 'gauge', samples: [] }],
16
+ [{ name: 'broken', help: 'two', type: 'gauge', samples: [] }],
17
+ ])).toEqual([{ name: 'same', help: 'help', type: 'gauge', samples: [] }]);
18
+ });
19
+
20
+ it('parses configured durations', () => {
21
+ expect(parseMetricsDuration('1.5m')).toBe(90_000);
22
+ expect(() => parseMetricsDuration('forever')).toThrow('Invalid metrics duration');
23
+ });
24
+
25
+ it('treats an empty successful provider response as valid but all failures as an error', async () => {
26
+ const config = `server: { name: test, version: '1', description: test }\ncors: { origin: ['*'], allowMethods: ['GET'], allowHeaders: ['Content-Type'] }\nmetrics: { enabled: true, internal_token_binding: APP_TOKEN }\nworkers:\n source: { name: source, handlers: [source], metrics: { enabled: true } }\n metrics: { name: metrics, handlers: [observability], metrics: { enabled: true } }\nrouter: { name: router, routes: [] }`;
27
+ const env = { CONFIG_CONTENT: config, APP_TOKEN: 'secret', SOURCE: { fetch: async () => new Response(JSON.stringify({ families: [] })) } };
28
+ await expect(collectObservabilityMetricGroups({ env, workerName: 'metrics', handlerName: 'observability' })).resolves.toEqual({ families: [], successfulProviders: 1 });
29
+ const failedEnv = { ...env, SOURCE: { fetch: async () => new Response('no', { status: 503 }) } };
30
+ const state = createState();
31
+ const coordinator = new BobraMetricsCoordinator(state as never, failedEnv);
32
+ await expect(coordinator.refresh()).rejects.toThrow('No metrics provider returned a successful response');
33
+ });
34
+
35
+ it('returns a valid stale merged snapshot when another refresh owns the coordinator lease', async () => {
36
+ const state = createState();
37
+ await state.storage.put('snapshot:merged', { collectedAt: Date.now(), families: [] });
38
+ await state.storage.put('lease:merged', { holder: 'other', expiresAt: Date.now() + 10_000 });
39
+ const config = `server: { name: test, version: '1', description: test }\ncors: { origin: ['*'], allowMethods: ['GET'], allowHeaders: ['Content-Type'] }\nmetrics: { enabled: true }\nworkers:\n metrics: { name: metrics, handlers: [observability], metrics: { enabled: true } }\nrouter: { name: router, routes: [] }`;
40
+ const coordinator = new BobraMetricsCoordinator(state as never, { CONFIG_CONTENT: config });
41
+ await expect(coordinator.refresh()).resolves.toEqual({ collectedAt: expect.any(Number), families: [] });
42
+ });
43
+ });
44
+
45
+ function createState() {
46
+ const values = new Map<string, unknown>();
47
+ return { storage: {
48
+ get: async <T>(key: string) => values.get(key) as T | undefined,
49
+ put: async <T>(key: string, value: T) => { values.set(key, value); },
50
+ delete: async (key: string) => values.delete(key),
51
+ setAlarm: async () => undefined,
52
+ } };
53
+ }
@@ -0,0 +1,209 @@
1
+ import * as v from 'valibot';
2
+ import { getWorkerMetricsConfig, loadConfig, serviceToBindingName } from '../../core/config';
3
+
4
+ export const METRICS_CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
5
+ const metricName = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
6
+ const labelName = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
7
+
8
+ export type MetricType = 'counter' | 'gauge';
9
+ export interface MetricSample { labels?: Record<string, string>; value: number; }
10
+ export interface MetricFamily { name: string; help: string; type: MetricType; samples: MetricSample[]; }
11
+ export interface MetricsCollectionContext { env: Record<string, unknown>; workerName: string; handlerName: string; request?: Request; }
12
+ export interface MetricsProvider { collect(context: MetricsCollectionContext): Promise<MetricFamily[]>; }
13
+
14
+ export const metricSampleSchema = v.object({ labels: v.optional(v.record(v.string(), v.string())), value: v.number() });
15
+ export const metricFamilySchema = v.object({ name: v.string(), help: v.string(), type: v.picklist(['counter', 'gauge']), samples: v.array(metricSampleSchema) });
16
+
17
+ export function parseMetricsDuration(value: string): number {
18
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(value);
19
+ if (!match) throw new Error(`Invalid metrics duration '${value}'`);
20
+ const multipliers: Record<string, number> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 };
21
+ return Number(match[1]) * multipliers[match[2]]!;
22
+ }
23
+
24
+ function escapeHelp(value: string): string { return value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); }
25
+ function escapeLabel(value: string): string { return value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"'); }
26
+ function sampleKey(labels: Record<string, string>): string { return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join(','); }
27
+
28
+ export function validateMetricFamilies(families: MetricFamily[]): MetricFamily[] {
29
+ for (const family of families) {
30
+ v.parse(metricFamilySchema, family);
31
+ if (!metricName.test(family.name)) throw new Error(`Invalid Prometheus metric name '${family.name}'`);
32
+ for (const sample of family.samples) {
33
+ if (!Number.isFinite(sample.value)) throw new Error(`Metric '${family.name}' has a non-finite value`);
34
+ for (const label of Object.keys(sample.labels || {})) if (!labelName.test(label)) throw new Error(`Invalid Prometheus label name '${label}'`);
35
+ }
36
+ }
37
+ return families;
38
+ }
39
+
40
+ export function addMetricLabels(families: MetricFamily[], labels: Record<string, string>): MetricFamily[] {
41
+ return families.map((family) => ({ ...family, samples: family.samples.map((sample) => {
42
+ const sampleLabels = sample.labels || {};
43
+ for (const [key, value] of Object.entries(labels)) if (sampleLabels[key] !== undefined && sampleLabels[key] !== value) throw new Error(`Metric '${family.name}' label '${key}' conflicts with configured source label`);
44
+ return { ...sample, labels: { ...labels, ...sampleLabels } };
45
+ }) }));
46
+ }
47
+
48
+ export function mergeMetricFamilies(input: MetricFamily[][]): MetricFamily[] {
49
+ const merged = new Map<string, MetricFamily>();
50
+ const invalidFamilies = new Set<string>();
51
+ const values = new Map<string, number>();
52
+ const conflictedSamples = new Set<string>();
53
+ for (const group of input) for (const family of validateMetricFamilies(group)) {
54
+ const current = merged.get(family.name);
55
+ if (!current) merged.set(family.name, { ...family, samples: [] });
56
+ else if (current.help !== family.help || current.type !== family.type) { invalidFamilies.add(family.name); continue; }
57
+ const destination = merged.get(family.name)!;
58
+ for (const sample of family.samples) {
59
+ const key = `${family.name}|${sampleKey(sample.labels || {})}`;
60
+ if (conflictedSamples.has(key)) continue;
61
+ const existing = values.get(key);
62
+ if (existing === undefined) { values.set(key, sample.value); destination.samples.push({ ...sample, labels: { ...(sample.labels || {}) } }); }
63
+ else if (existing !== sample.value) {
64
+ conflictedSamples.add(key);
65
+ values.delete(key);
66
+ destination.samples = destination.samples.filter((entry) => sampleKey(entry.labels || {}) !== sampleKey(sample.labels || {}));
67
+ }
68
+ }
69
+ }
70
+ return [...merged.values()].filter((family) => !invalidFamilies.has(family.name)).sort((a, b) => a.name.localeCompare(b.name)).map((family) => ({ ...family, samples: [...family.samples].sort((a, b) => sampleKey(a.labels || {}).localeCompare(sampleKey(b.labels || {}))) }));
71
+ }
72
+
73
+ export function serializePrometheus(families: MetricFamily[]): string {
74
+ const lines: string[] = [];
75
+ for (const family of mergeMetricFamilies([families])) {
76
+ lines.push(`# HELP ${family.name} ${escapeHelp(family.help)}`, `# TYPE ${family.name} ${family.type}`);
77
+ for (const sample of family.samples) {
78
+ const labels = sample.labels || {};
79
+ const rendered = Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}="${escapeLabel(value)}"`).join(',');
80
+ lines.push(`${family.name}${rendered ? `{${rendered}}` : ''} ${sample.value}`);
81
+ }
82
+ }
83
+ return lines.length ? `${lines.join('\n')}\n` : '';
84
+ }
85
+
86
+ export interface MetricsSnapshot { collectedAt: number; families: MetricFamily[]; }
87
+ export interface MetricsLease { holder: string; expiresAt: number; }
88
+ export interface MetricsDurableEnv { [key: string]: unknown; }
89
+
90
+ type MetricsDurableStorage = {
91
+ get<T>(key: string): Promise<T | undefined>;
92
+ put<T>(key: string, value: T): Promise<void>;
93
+ delete(key: string): Promise<boolean>;
94
+ setAlarm(scheduledTime: number | Date): Promise<void>;
95
+ };
96
+
97
+ class MetricsDurableObjectBase {
98
+ readonly ctx: { storage: MetricsDurableStorage };
99
+ readonly env: MetricsDurableEnv;
100
+ constructor(...args: [ctx: { storage: MetricsDurableStorage }, env: MetricsDurableEnv]) {
101
+ [this.ctx, this.env] = args;
102
+ }
103
+ }
104
+
105
+ // TypeScript mixins require an any[] constructor; runtime inputs remain the
106
+ // typed Durable Object state/environment pair defined above.
107
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
108
+ export type MetricsDurableObjectConstructor = new (...args: any[]) => MetricsDurableObjectBase;
109
+
110
+ /** Creates a cache class using the runtime DurableObject base supplied by the Worker entrypoint. */
111
+ export function createBobraMetricsCacheClass<TBase extends MetricsDurableObjectConstructor>(DurableObjectBase: TBase) {
112
+ return class BobraMetricsCache extends DurableObjectBase {
113
+ async readSnapshot(key: string): Promise<MetricsSnapshot | undefined> { return this.ctx.storage.get<MetricsSnapshot>(`snapshot:${key}`); }
114
+ async writeSnapshot(key: string, snapshot: MetricsSnapshot): Promise<void> { await this.ctx.storage.put(`snapshot:${key}`, snapshot); }
115
+ async deleteSnapshot(key: string): Promise<void> { await this.ctx.storage.delete(`snapshot:${key}`); }
116
+ async acquireLease(key: string, holder: string, ttlMs: number): Promise<boolean> {
117
+ const leaseKey = `lease:${key}`;
118
+ const current = await this.ctx.storage.get<MetricsLease>(leaseKey);
119
+ const now = Date.now();
120
+ if (current && current.expiresAt > now && current.holder !== holder) return false;
121
+ await this.ctx.storage.put(leaseKey, { holder, expiresAt: now + ttlMs } satisfies MetricsLease);
122
+ return true;
123
+ }
124
+ async releaseLease(key: string, holder: string): Promise<void> {
125
+ const leaseKey = `lease:${key}`;
126
+ const current = await this.ctx.storage.get<MetricsLease>(leaseKey);
127
+ if (current?.holder === holder) await this.ctx.storage.delete(leaseKey);
128
+ }
129
+ };
130
+ }
131
+
132
+ /** Coordinator owns the next alarm timestamp; application code performs collection through Service Bindings. */
133
+ export function createBobraMetricsCoordinatorClass<TBase extends MetricsDurableObjectConstructor>(DurableObjectBase: TBase) {
134
+ const BobraMetricsCache = createBobraMetricsCacheClass(DurableObjectBase);
135
+ return class BobraMetricsCoordinator extends BobraMetricsCache {
136
+ async scheduleNext(at: number): Promise<void> { await this.ctx.storage.put('next_alarm_at', at); await this.ctx.storage.setAlarm(at); }
137
+ async readMergedSnapshot(): Promise<MetricsSnapshot | undefined> { return this.readSnapshot('merged'); }
138
+ async refresh(): Promise<MetricsSnapshot> {
139
+ const config = await loadConfig(this.env);
140
+ const workerName = Object.entries(config.workers).find(([, worker]) => worker.handlers.includes('observability'))?.[0] || String(this.env.WORKER_NAME || 'observability');
141
+ const policy = config.workers[workerName] ? getWorkerMetricsConfig(config, workerName).cache : undefined;
142
+ const holder = crypto.randomUUID();
143
+ const leaseTtl = policy?.provider_timeout ? parseMetricsDuration(policy.provider_timeout) : 15_000;
144
+ if (!await this.acquireLease('merged', holder, leaseTtl)) {
145
+ const existing = await this.readMergedSnapshot();
146
+ const maxStaleness = policy?.max_staleness ? parseMetricsDuration(policy.max_staleness) : 120_000;
147
+ if (existing && Date.now() - existing.collectedAt <= maxStaleness) return existing;
148
+ throw new Error('Metrics aggregation refresh already in progress');
149
+ }
150
+ try {
151
+ const result = await collectObservabilityMetricGroups({ env: this.env, workerName, handlerName: 'observability' });
152
+ if (result.successfulProviders === 0) throw new Error('No metrics provider returned a successful response');
153
+ const snapshot = { collectedAt: Date.now(), families: result.families } satisfies MetricsSnapshot;
154
+ await this.writeSnapshot('merged', snapshot);
155
+ return snapshot;
156
+ } finally {
157
+ await this.releaseLease('merged', holder);
158
+ }
159
+ }
160
+ async alarm(): Promise<void> {
161
+ const config = await loadConfig(this.env);
162
+ const workerName = Object.entries(config.workers).find(([, worker]) => worker.handlers.includes('observability'))?.[0] || String(this.env.WORKER_NAME || 'observability');
163
+ const policy = config.workers[workerName] ? getWorkerMetricsConfig(config, workerName).cache : undefined;
164
+ try { await this.refresh(); }
165
+ finally {
166
+ const delay = policy?.freshness ? parseMetricsDuration(policy.freshness) : 60_000;
167
+ await this.scheduleNext(Date.now() + delay);
168
+ }
169
+ }
170
+ };
171
+ }
172
+
173
+ // Node-safe classes for configuration/tests. Worker entrypoints must create
174
+ // their exports with cloudflare:workers DurableObject to enable RPC.
175
+ export class BobraMetricsCache extends createBobraMetricsCacheClass(MetricsDurableObjectBase) {}
176
+ export class BobraMetricsCoordinator extends createBobraMetricsCoordinatorClass(MetricsDurableObjectBase) {}
177
+
178
+ type InternalServiceBinding = { fetch(url: string, init?: RequestInit): Promise<Response> };
179
+
180
+ /** Provider for a normal `observability` handler. It performs one Service Binding call per participating Worker. */
181
+ export function createObservabilityMetricsProvider(): MetricsProvider {
182
+ return {
183
+ async collect(context): Promise<MetricFamily[]> {
184
+ const result = await collectObservabilityMetricGroups(context);
185
+ if (result.successfulProviders === 0) throw new Error('No metrics provider returned a successful response');
186
+ return result.families;
187
+ }
188
+ };
189
+ }
190
+
191
+ export async function collectObservabilityMetricGroups(context: MetricsCollectionContext): Promise<{ families: MetricFamily[]; successfulProviders: number }> {
192
+ const config = await loadConfig(context.env);
193
+ const groups: MetricFamily[][] = [];
194
+ let successfulProviders = 0;
195
+ await Promise.all(Object.entries(config.workers).filter(([workerName, worker]) => workerName !== context.workerName && worker.metrics?.enabled).map(async ([workerName]) => {
196
+ const binding = context.env[serviceToBindingName(workerName)] as InternalServiceBinding | undefined;
197
+ if (!binding) return;
198
+ const token = config.metrics?.internal_token_binding ? context.env[config.metrics.internal_token_binding] : undefined;
199
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
200
+ if (typeof token === 'string') headers['X-Internal-Token'] = token;
201
+ const response = await binding.fetch('http://internal/_bobra/metrics/collect', { method: 'POST', headers, body: '{}' });
202
+ if (!response.ok) return;
203
+ const payload = await response.json() as { families?: MetricFamily[] };
204
+ if (!payload.families) return;
205
+ successfulProviders += 1;
206
+ groups.push(payload.families);
207
+ }));
208
+ return { families: mergeMetricFamilies(groups), successfulProviders };
209
+ }
package/core/config.ts CHANGED
@@ -184,6 +184,7 @@ export interface WorkerConfig {
184
184
  cf_routes?: CloudflareRoute[];
185
185
  assets?: AssetsConfig;
186
186
  placement?: WorkerPlacementConfig;
187
+ metrics?: WorkerMetricsConfig;
187
188
  observability?: {
188
189
  logs?: {
189
190
  enabled?: boolean;
@@ -237,10 +238,52 @@ export interface AppConfig {
237
238
  pgEdge: PgEdgeConfig;
238
239
  vars?: Record<string, string | number | boolean | JSONValue>;
239
240
  placement?: WorkerPlacementConfig;
241
+ metrics?: MetricsConfig;
240
242
  workers: Record<string, WorkerConfig>;
241
243
  router: RouterConfig;
242
244
  }
243
245
 
246
+ export interface MetricsCacheConfig {
247
+ enabled: boolean;
248
+ backend: 'durable-object';
249
+ freshness: string;
250
+ max_staleness: string;
251
+ provider_timeout: string;
252
+ force_refresh_cooldown: string;
253
+ adaptive: { enabled: boolean; recurring_request_count: number; recurring_window: string };
254
+ alarm: { enabled: boolean; retry_initial: string; retry_max: string; retry_multiplier: number; jitter_percent: number };
255
+ discovery: { refresh_interval: string };
256
+ }
257
+
258
+ export interface MetricsLabelsConfig {
259
+ source: { enabled: boolean; app: string; worker: string; handler: string };
260
+ static: Record<string, string | null>;
261
+ }
262
+
263
+ export interface MetricsConfig {
264
+ enabled: boolean;
265
+ endpoint_path: string;
266
+ /** Existing app init-token binding used only for stateless Worker-to-Worker collection. */
267
+ internal_token_binding?: string;
268
+ cache: MetricsCacheConfig;
269
+ labels: MetricsLabelsConfig;
270
+ }
271
+
272
+ /** Worker policy can override collection behavior, but collection authentication is application-global. */
273
+ export type WorkerMetricsConfig = Omit<Partial<MetricsConfig>, 'internal_token_binding'>;
274
+
275
+ export const defaultMetricsConfig: MetricsConfig = {
276
+ enabled: false,
277
+ endpoint_path: '/metrics',
278
+ cache: {
279
+ enabled: true, backend: 'durable-object', freshness: '60s', max_staleness: '120s', provider_timeout: '15s', force_refresh_cooldown: '10s',
280
+ adaptive: { enabled: true, recurring_request_count: 2, recurring_window: '120s' },
281
+ alarm: { enabled: true, retry_initial: '5s', retry_max: '5m', retry_multiplier: 2, jitter_percent: 10 },
282
+ discovery: { refresh_interval: '5m' },
283
+ },
284
+ labels: { source: { enabled: true, app: 'bobra_app', worker: 'bobra_worker', handler: 'bobra_handler' }, static: {} },
285
+ };
286
+
244
287
  // Default configuration — apps should override these via their config.yml
245
288
  export const defaultConfig: AppConfig = {
246
289
  cors: {
@@ -260,6 +303,7 @@ export const defaultConfig: AppConfig = {
260
303
  },
261
304
  db_engine: 'postgres',
262
305
  vars: {},
306
+ metrics: defaultMetricsConfig,
263
307
  workers: {},
264
308
  router: {
265
309
  name: 'example-app-router-worker',
@@ -296,6 +340,7 @@ export function parseConfig(yamlContent: string, env?: Record<string, unknown>):
296
340
  ...parsed.pgEdge,
297
341
  },
298
342
  logging: parsed.logging,
343
+ metrics: mergeMetricsConfig(defaultMetricsConfig, parsed.metrics),
299
344
  vars: parsed.vars || {},
300
345
  workers: parsed.workers || {},
301
346
  router: {
@@ -317,6 +362,26 @@ export function parseConfig(yamlContent: string, env?: Record<string, unknown>):
317
362
  }
318
363
  }
319
364
 
365
+ function mergeMetricsConfig(base: MetricsConfig, override?: Partial<MetricsConfig>): MetricsConfig {
366
+ return {
367
+ ...base, ...override,
368
+ cache: { ...base.cache, ...override?.cache, adaptive: { ...base.cache.adaptive, ...override?.cache?.adaptive }, alarm: { ...base.cache.alarm, ...override?.cache?.alarm }, discovery: { ...base.cache.discovery, ...override?.cache?.discovery } },
369
+ labels: { ...base.labels, ...override?.labels, source: { ...base.labels.source, ...override?.labels?.source }, static: { ...base.labels.static, ...override?.labels?.static } },
370
+ };
371
+ }
372
+
373
+ /** Effective metrics policy follows the same global -> worker hierarchy as logging. */
374
+ export function getWorkerMetricsConfig(config: AppConfig, workerName: string): MetricsConfig {
375
+ // Generator callers receive raw YAML while Worker runtime receives parsed
376
+ // config. Start from defaults in both cases so partial global policy is safe.
377
+ const globalMetrics = mergeMetricsConfig(defaultMetricsConfig, config.metrics);
378
+ const effective = mergeMetricsConfig(globalMetrics, config.workers?.[workerName]?.metrics);
379
+ effective.internal_token_binding = globalMetrics.internal_token_binding;
380
+ // Global enable is a master switch; a Worker opts in explicitly, matching logging's worker ownership.
381
+ effective.enabled = Boolean(globalMetrics.enabled && config.workers?.[workerName]?.metrics?.enabled);
382
+ return effective;
383
+ }
384
+
320
385
  // Cache for parsed configuration to avoid repeated decompression/parsing
321
386
  let configCache: { content: string; config: AppConfig } | null = null;
322
387
 
@@ -535,6 +600,11 @@ export function validateConfig(config: AppConfig): void {
535
600
  const allHandlerIds = new Set<string>();
536
601
  const allServiceIds = new Set<string>();
537
602
 
603
+ const metricsWorkers = Object.entries(config.workers || {}).filter(([workerName]) => getWorkerMetricsConfig(config, workerName).enabled);
604
+ if (metricsWorkers.length > 0 && !config.metrics?.internal_token_binding) {
605
+ throw new Error('Metrics-enabled workers require metrics.internal_token_binding for internal collection');
606
+ }
607
+
538
608
  for (const [workerName, worker] of Object.entries(config.workers || {})) {
539
609
  for (const handlerId of worker.handlers || []) {
540
610
  if (allHandlerIds.has(handlerId)) {
@@ -555,6 +625,17 @@ export function validateConfig(config: AppConfig): void {
555
625
  allServiceIds.add(service.service);
556
626
  }
557
627
  }
628
+
629
+ for (const [workerName, worker] of Object.entries(config.workers || {})) {
630
+ const metrics = getWorkerMetricsConfig(config, workerName);
631
+ if (!metrics.enabled) continue;
632
+ if (!worker.handlers?.length) throw new Error(`Metrics-enabled worker '${workerName}' must declare handlers`);
633
+ if (!metrics.endpoint_path.startsWith('/')) throw new Error(`Metrics endpoint_path for worker '${workerName}' must start with '/'`);
634
+ const durationKeys = [metrics.cache.freshness, metrics.cache.max_staleness, metrics.cache.provider_timeout, metrics.cache.force_refresh_cooldown, metrics.cache.adaptive.recurring_window, metrics.cache.alarm.retry_initial, metrics.cache.alarm.retry_max, metrics.cache.discovery.refresh_interval];
635
+ for (const value of durationKeys) if (!/^\d+(?:\.\d+)?(?:ms|s|m|h)$/.test(value)) throw new Error(`Invalid metrics duration '${value}' for worker '${workerName}'`);
636
+ if (metrics.cache.adaptive.recurring_request_count < 1 || metrics.cache.alarm.retry_multiplier < 1 || metrics.cache.alarm.jitter_percent < 0) throw new Error(`Invalid metrics retry/adaptive policy for worker '${workerName}'`);
637
+ if (!metrics.labels.source.app || !metrics.labels.source.worker || !metrics.labels.source.handler) throw new Error(`Metrics source labels for worker '${workerName}' must be non-empty`);
638
+ }
558
639
  }
559
640
 
560
641
  // Helper function to get service binding with direct call fallback
package/core/discovery.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Hono } from 'hono';
2
2
  import type { LoggerConfig } from '../logging/logger';
3
+ import type { MetricsProvider } from '../batteries/metrics';
3
4
 
4
5
  type HandlerEnv = Record<string, unknown>;
5
6
  type HonoEnv = { Bindings: HandlerEnv; Variables?: Record<string, unknown> };
@@ -30,6 +31,8 @@ export interface AppHandler {
30
31
  ignoreWorkerBasePath?: boolean;
31
32
  // Optional scheduled handler
32
33
  scheduled?: (event: ScheduledEvent, env: HandlerEnv, ctx: ExecutionCtx) => Promise<void> | void;
34
+ /** Optional, business-owned Prometheus metric collection. Operational policy belongs in config.yml. */
35
+ metrics?: MetricsProvider;
33
36
  }
34
37
 
35
38
  /**
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { Hono } from 'hono';
3
+ import { parseConfig } from './config';
4
+ // This isolates an unrelated optional hono-openapi peer dependency. No cloudflare:workers mock is used.
5
+ vi.mock('hono-openapi', () => ({ generateSpecs: vi.fn() }));
6
+
7
+ describe('factory consumer import', () => {
8
+ it('loads without a cloudflare:workers module mock', async () => {
9
+ const { AppWorker } = await import('./factory');
10
+ expect(AppWorker).toBeTypeOf('function');
11
+ });
12
+
13
+ it('allows a metrics provider when the global metrics kill switch is off', async () => {
14
+ const { AppWorker } = await import('./factory');
15
+ const config = parseConfig(`server: { name: test, version: '1', description: test }\ncors: { origin: ['*'], allowMethods: ['GET'], allowHeaders: ['Content-Type'] }\nmetrics: { enabled: false }\nworkers:\n source: { name: source, handlers: [source], metrics: { enabled: true } }\nrouter: { name: router, routes: [] }`);
16
+ const worker = new AppWorker(new Hono() as never, config, 'source', '/');
17
+ await expect(worker.add({ default: { name: 'source', version: '1', routes: new Hono() as never, metrics: { collect: async () => [] } } })).resolves.toBe(worker);
18
+ });
19
+ });
package/core/factory.ts CHANGED
@@ -15,7 +15,9 @@ import {
15
15
  getRouterBasePath,
16
16
  getWorkerQueueBindings,
17
17
  getServiceDiscovery,
18
+ getWorkerMetricsConfig,
18
19
  } from './config';
20
+ import { addMetricLabels, mergeMetricFamilies, parseMetricsDuration, serializePrometheus, type MetricFamily, type MetricsSnapshot } from '../batteries/metrics';
19
21
  import { serviceDiscoveryMiddleware } from '../network/service-discovery';
20
22
  import { generateSpecs } from 'hono-openapi';
21
23
  import type { OpenAPIV3 } from 'openapi-types';
@@ -39,6 +41,9 @@ type WorkerExecutionCtx = ExecutionContext;
39
41
  type ScheduledEvent = ScheduledController;
40
42
  type SchemaMap = Record<string, OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject>;
41
43
  type SecuritySchemeMap = Record<string, OpenAPIV3.SecuritySchemeObject | OpenAPIV3.ReferenceObject>;
44
+ type MetricsCacheStub = { readSnapshot(key: string): Promise<MetricsSnapshot | undefined>; writeSnapshot(key: string, snapshot: MetricsSnapshot): Promise<void>; deleteSnapshot(key: string): Promise<void>; acquireLease(key: string, holder: string, ttlMs: number): Promise<boolean>; releaseLease(key: string, holder: string): Promise<void> };
45
+ type MetricsCoordinatorStub = MetricsCacheStub & { readMergedSnapshot(): Promise<MetricsSnapshot | undefined>; refresh(): Promise<MetricsSnapshot>; scheduleNext(at: number): Promise<void> };
46
+ type MetricsCacheNamespace = { getByName(name: string): MetricsCacheStub };
42
47
 
43
48
  interface RequestWithCf extends Request {
44
49
  cf?: Record<string, unknown> & {
@@ -308,6 +313,92 @@ export class AppWorker {
308
313
  private initialized = false;
309
314
  private startupStack = new LogStack();
310
315
 
316
+ private async collectHandlerMetrics(handler: AppHandler, env: WorkerEnv, request?: Request): Promise<MetricFamily[]> {
317
+ if (!handler.metrics) return [];
318
+ const metrics = getWorkerMetricsConfig(this.config, this.workerName);
319
+ const labels: Record<string, string> = {};
320
+ if (metrics.labels.source.enabled) {
321
+ labels[metrics.labels.source.app] = this.config.server.name;
322
+ labels[metrics.labels.source.worker] = this.workerName;
323
+ labels[metrics.labels.source.handler] = handler.name;
324
+ }
325
+ for (const [key, value] of Object.entries(metrics.labels.static)) if (value !== null) labels[key] = value;
326
+ const families = await handler.metrics.collect({ env, workerName: this.workerName, handlerName: handler.name, request });
327
+ return addMetricLabels(families, labels);
328
+ }
329
+
330
+ private getMetricsCache(env: WorkerEnv, coordinator = false): MetricsCacheStub | undefined {
331
+ const binding = env[coordinator ? 'BOBRA_METRICS_COORDINATOR' : 'BOBRA_METRICS_CACHE'] as MetricsCacheNamespace | undefined;
332
+ return binding?.getByName(`${this.config.server.name}:${this.workerName}`);
333
+ }
334
+
335
+ private getMetricsCoordinator(env: WorkerEnv): MetricsCoordinatorStub | undefined {
336
+ return this.getMetricsCache(env, true) as MetricsCoordinatorStub | undefined;
337
+ }
338
+
339
+ private async getObservabilityMetrics(handler: AppHandler, env: WorkerEnv, request: Request): Promise<MetricFamily[]> {
340
+ const policy = getWorkerMetricsConfig(this.config, this.workerName);
341
+ const localProviders = this.handlers.filter((candidate) => candidate.name !== 'observability' && candidate.metrics);
342
+ const localFamilies = localProviders.length > 0
343
+ ? await Promise.all(localProviders.map((provider) => this.getDirectMetrics(provider, env, request)))
344
+ : [];
345
+ const hasExternalProviders = Object.entries(this.config.workers).some(([name, worker]) => name !== this.workerName && getWorkerMetricsConfig(this.config, name).enabled && !worker.handlers.includes('observability'));
346
+ if (!hasExternalProviders) return mergeMetricFamilies(localFamilies);
347
+ if (!policy.cache.enabled) return mergeMetricFamilies([await handler.metrics!.collect({ env, workerName: this.workerName, handlerName: handler.name, request }), ...localFamilies]);
348
+ const coordinator = policy.cache.enabled ? this.getMetricsCoordinator(env) : undefined;
349
+ if (!coordinator) throw new Error('Observability metrics require the configured coordinator Durable Object');
350
+ const now = Date.now();
351
+ const snapshot = await coordinator.readMergedSnapshot();
352
+ if (snapshot && now - snapshot.collectedAt <= parseMetricsDuration(policy.cache.freshness)) return mergeMetricFamilies([snapshot.families, ...localFamilies]);
353
+ const refreshed = await coordinator.refresh();
354
+ await coordinator.scheduleNext(Date.now() + parseMetricsDuration(policy.cache.freshness));
355
+ return mergeMetricFamilies([refreshed.families, ...localFamilies]);
356
+ }
357
+
358
+ private async getDirectMetrics(handler: AppHandler, env: WorkerEnv, request: Request): Promise<MetricFamily[]> {
359
+ const policy = getWorkerMetricsConfig(this.config, this.workerName);
360
+ const cache = policy.cache.enabled ? this.getMetricsCache(env) ?? this.getMetricsCoordinator(env) : undefined;
361
+ const key = `handler:${handler.name}`;
362
+ const now = Date.now();
363
+ let stale: MetricsSnapshot | undefined;
364
+ if (cache) {
365
+ const stored = await cache.readSnapshot(key);
366
+ if (stored) {
367
+ if (now - stored.collectedAt <= parseMetricsDuration(policy.cache.freshness)) return stored.families;
368
+ stale = stored;
369
+ }
370
+ }
371
+ const holder = crypto.randomUUID();
372
+ if (cache && !await cache.acquireLease(key, holder, parseMetricsDuration(policy.cache.provider_timeout))) {
373
+ if (stale && now - stale.collectedAt <= parseMetricsDuration(policy.cache.max_staleness)) return stale.families;
374
+ throw new Error(`Metrics refresh already in progress for handler '${handler.name}'`);
375
+ }
376
+ try {
377
+ const families = await this.collectHandlerMetrics(handler, env, request);
378
+ if (cache) await cache.writeSnapshot(key, { collectedAt: now, families });
379
+ return families;
380
+ } finally {
381
+ if (cache) await cache.releaseLease(key, holder);
382
+ }
383
+ }
384
+
385
+ private async hasInternalMetricsAuth(request: Request, env: WorkerEnv): Promise<boolean> {
386
+ const binding = this.config.metrics?.internal_token_binding;
387
+ const expected = binding ? env[binding] : undefined;
388
+ const provided = request.headers.get('X-Internal-Token');
389
+ if (typeof expected !== 'string' || !provided) return false;
390
+ const encoder = new TextEncoder();
391
+ const [expectedHash, providedHash] = await Promise.all([
392
+ crypto.subtle.digest('SHA-256', encoder.encode(expected)),
393
+ crypto.subtle.digest('SHA-256', encoder.encode(provided)),
394
+ ]);
395
+ const left = new Uint8Array(expectedHash);
396
+ const right = new Uint8Array(providedHash);
397
+ let difference = 0;
398
+ for (let index = 0; index < left.length; index += 1) difference |= left[index]! ^ right[index]!;
399
+ return difference === 0;
400
+ }
401
+
311
402
  constructor(app: RoutableHono<HonoBindingsEnv>, config: AppConfig, workerName: string, basePath: string, options?: WorkerOptions) {
312
403
  this.app = app;
313
404
  this.config = config;
@@ -470,6 +561,10 @@ export class AppWorker {
470
561
  const module = await handlerModule;
471
562
  const handler = module.default;
472
563
 
564
+ if (handler.metrics && this.config.metrics?.enabled && !getWorkerMetricsConfig(this.config, this.workerName).enabled) {
565
+ throw new Error(`Handler '${handler.name}' declares metrics but worker '${this.workerName}' has metrics disabled`);
566
+ }
567
+
473
568
  // Initialize handler's logger with worker's configuration
474
569
  const loggingConfig = getWorkerLoggingConfig(this.config, this.workerName);
475
570
 
@@ -499,6 +594,22 @@ export class AppWorker {
499
594
  handlerPath = `/${handler.name}`;
500
595
  }
501
596
 
597
+ const metricsConfig = getWorkerMetricsConfig(this.config, this.workerName);
598
+ if (metricsConfig.enabled && handler.metrics) {
599
+ const endpointPath = metricsConfig.endpoint_path.startsWith('/') ? metricsConfig.endpoint_path : `/${metricsConfig.endpoint_path}`;
600
+ this.app.get(`${handlerPath}${endpointPath}`, async (c) => {
601
+ try {
602
+ const families = handler.name === 'observability'
603
+ ? await this.getObservabilityMetrics(handler, c.env as WorkerEnv, c.req.raw)
604
+ : await this.getDirectMetrics(handler, c.env as WorkerEnv, c.req.raw);
605
+ return new Response(serializePrometheus(families), { headers: { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8', 'Cache-Control': 'no-store' } });
606
+ } catch (error) {
607
+ getLogger().error(`Metrics collection failed for handler ${handler.name}`, error instanceof Error ? error : new Error(String(error)));
608
+ return new Response('metrics collection failed\n', { status: 503, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
609
+ }
610
+ });
611
+ }
612
+
502
613
  if (handler.name !== 'api-docs') {
503
614
  (() => {
504
615
  const specApp = new Hono<HonoBindingsEnv>() as RoutableHono<HonoBindingsEnv>;
@@ -619,6 +730,24 @@ export class AppWorker {
619
730
  }
620
731
  }
621
732
 
733
+ mountInternalMetricsCollector(): void {
734
+ const metrics = getWorkerMetricsConfig(this.config, this.workerName);
735
+ if (!metrics.enabled) return;
736
+ const internalPath = '/_bobra/metrics/collect';
737
+ this.app.post(internalPath, async (c) => {
738
+ try {
739
+ if (!await this.hasInternalMetricsAuth(c.req.raw, c.env as WorkerEnv)) return c.json({ error: 'forbidden' }, 403);
740
+ const requested: { handlers?: string[] } = await c.req.json<{ handlers?: string[] }>().catch(() => ({}));
741
+ const selected = this.handlers.filter((handler) => handler.metrics && (!requested.handlers || requested.handlers.includes(handler.name)));
742
+ const groups = await Promise.all(selected.map((handler) => this.collectHandlerMetrics(handler, c.env as WorkerEnv, c.req.raw)));
743
+ return c.json({ families: mergeMetricFamilies(groups) });
744
+ } catch (error) {
745
+ getLogger().error('Internal metrics collection failed', error instanceof Error ? error : new Error(String(error)));
746
+ return c.json({ error: 'metrics collection failed' }, 503);
747
+ }
748
+ });
749
+ }
750
+
622
751
  // Initialize all handlers
623
752
  async initialize(env: WorkerEnv): Promise<void> {
624
753
  if (this.initialized) {
@@ -626,6 +755,10 @@ export class AppWorker {
626
755
  }
627
756
 
628
757
  const workerLoggingConfig = getWorkerLoggingConfig(this.config, this.workerName);
758
+ const metricsConfig = getWorkerMetricsConfig(this.config, this.workerName);
759
+ if (metricsConfig.enabled && !this.handlers.some((handler) => handler.metrics)) {
760
+ throw new Error(`Metrics-enabled worker '${this.workerName}' has no metrics provider`);
761
+ }
629
762
  const verbosity = workerLoggingConfig.startupVerbosity || ['worker-registry', 'discovery-validation', 'handler-add', 'handler-init'];
630
763
 
631
764
  for (const handler of this.handlers) {
@@ -766,6 +899,8 @@ export function createCloudflareWorker(
766
899
  await worker.add(handler);
767
900
  }
768
901
 
902
+ worker.mountInternalMetricsCollector();
903
+
769
904
  const workerExport = worker.export();
770
905
  return await workerExport.fetch(request, workerEnv, ctx);
771
906