@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.
- package/batteries/metrics/index.test.ts +53 -0
- package/batteries/metrics/index.ts +209 -0
- package/core/config.ts +81 -0
- package/core/discovery.ts +3 -0
- package/core/factory-import.test.ts +19 -0
- package/core/factory.ts +135 -0
- package/core/metrics-config.test.ts +62 -0
- package/dist/batteries/metrics/index.d.ts +140 -0
- package/dist/batteries/metrics/index.js +202 -0
- package/dist/batteries/metrics/index.js.map +1 -0
- package/dist/core/config.d.ts +47 -0
- package/dist/core/config.js +52 -0
- package/dist/core/config.js.map +1 -1
- package/dist/core/discovery.d.ts +3 -0
- package/dist/core/discovery.js.map +1 -1
- package/dist/core/factory.d.ts +7 -0
- package/dist/core/factory.js +140 -1
- package/dist/core/factory.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/network/service-fetch.js +2 -0
- package/dist/network/service-fetch.js.map +1 -1
- package/dist/node/generate-wrangler-config.d.ts +1 -0
- package/dist/node/generate-wrangler-config.js +30 -3
- package/dist/node/generate-wrangler-config.js.map +1 -1
- package/index.ts +1 -0
- package/network/service-fetch.ts +1 -0
- package/node/generate-wrangler-config.ts +27 -2
- package/package.json +6 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { getWorkerMetricsConfig, parseConfig, validateConfig } from './config';
|
|
3
|
+
import { generateWranglerConfig } from '../node/generate-wrangler-config';
|
|
4
|
+
|
|
5
|
+
const yaml = `
|
|
6
|
+
server: { name: neutral-app, version: 1.0.0, description: test }
|
|
7
|
+
cors: { origin: ['*'], allowMethods: ['GET'], allowHeaders: ['Content-Type'] }
|
|
8
|
+
metrics:
|
|
9
|
+
enabled: true
|
|
10
|
+
internal_token_binding: APP_INIT_TOKEN
|
|
11
|
+
workers:
|
|
12
|
+
source-worker:
|
|
13
|
+
name: source-worker
|
|
14
|
+
handlers: [source]
|
|
15
|
+
metrics: { enabled: true }
|
|
16
|
+
metrics-worker:
|
|
17
|
+
name: metrics-worker
|
|
18
|
+
handlers: [observability]
|
|
19
|
+
metrics: { enabled: true }
|
|
20
|
+
router: { name: router, routes: [] }
|
|
21
|
+
`;
|
|
22
|
+
|
|
23
|
+
describe('metrics configuration', () => {
|
|
24
|
+
it('inherits global policy and generates SQLite cache bindings', () => {
|
|
25
|
+
const config = parseConfig(yaml);
|
|
26
|
+
validateConfig(config);
|
|
27
|
+
const generated = generateWranglerConfig(config, 'worker', 'metrics-worker');
|
|
28
|
+
expect(generated.durable_objects?.bindings).toContainEqual({ name: 'BOBRA_METRICS_COORDINATOR', class_name: 'BobraMetricsCoordinator' });
|
|
29
|
+
expect(generated.migrations?.some((migration) => migration.new_sqlite_classes?.includes('BobraMetricsCoordinator'))).toBe(true);
|
|
30
|
+
expect(generated.services).toContainEqual({ binding: 'SOURCE_WORKER', service: 'source-worker' });
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('keeps worker participation explicit and honors direct cache opt-out', () => {
|
|
34
|
+
const config = parseConfig(yaml);
|
|
35
|
+
config.workers['source-worker']!.metrics = { enabled: true, cache: { enabled: false } };
|
|
36
|
+
expect(getWorkerMetricsConfig(config, 'source-worker').cache.enabled).toBe(false);
|
|
37
|
+
expect(getWorkerMetricsConfig(config, 'unlisted-worker').enabled).toBe(false);
|
|
38
|
+
const generated = generateWranglerConfig(config, 'worker', 'source-worker');
|
|
39
|
+
expect(generated.durable_objects).toBeUndefined();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('rejects enabled metrics without internal collection authentication', () => {
|
|
43
|
+
const config = parseConfig(yaml.replace(' internal_token_binding: APP_INIT_TOKEN\n', ''));
|
|
44
|
+
expect(() => validateConfig(config)).toThrow('metrics.internal_token_binding');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('requires collection authentication globally even if a worker declares its own binding', () => {
|
|
48
|
+
const config = parseConfig(yaml
|
|
49
|
+
.replace(' internal_token_binding: APP_INIT_TOKEN\n', '')
|
|
50
|
+
.replace(' metrics: { enabled: true }\n metrics-worker:', ' metrics: { enabled: true, internal_token_binding: SOURCE_ONLY_TOKEN }\n metrics-worker:'));
|
|
51
|
+
expect(getWorkerMetricsConfig(config, 'source-worker').internal_token_binding).toBeUndefined();
|
|
52
|
+
expect(() => validateConfig(config)).toThrow('metrics.internal_token_binding');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('adds a dedicated metrics migration without changing an existing SQLite migration', () => {
|
|
56
|
+
const config = parseConfig(yaml);
|
|
57
|
+
config.workers['metrics-worker']!.durable_objects = [{ binding: 'APP_STATE', class_name: 'AppState' }];
|
|
58
|
+
const generated = generateWranglerConfig(config, 'worker', 'metrics-worker');
|
|
59
|
+
expect(generated.migrations).toContainEqual({ tag: 'durable-objects-v1', new_classes: ['AppState'] });
|
|
60
|
+
expect(generated.migrations).toContainEqual({ tag: 'bobra-metrics-v1', new_sqlite_classes: ['BobraMetricsCoordinator'] });
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import * as v from 'valibot';
|
|
2
|
+
export declare const METRICS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
|
|
3
|
+
export type MetricType = 'counter' | 'gauge';
|
|
4
|
+
export interface MetricSample {
|
|
5
|
+
labels?: Record<string, string>;
|
|
6
|
+
value: number;
|
|
7
|
+
}
|
|
8
|
+
export interface MetricFamily {
|
|
9
|
+
name: string;
|
|
10
|
+
help: string;
|
|
11
|
+
type: MetricType;
|
|
12
|
+
samples: MetricSample[];
|
|
13
|
+
}
|
|
14
|
+
export interface MetricsCollectionContext {
|
|
15
|
+
env: Record<string, unknown>;
|
|
16
|
+
workerName: string;
|
|
17
|
+
handlerName: string;
|
|
18
|
+
request?: Request;
|
|
19
|
+
}
|
|
20
|
+
export interface MetricsProvider {
|
|
21
|
+
collect(context: MetricsCollectionContext): Promise<MetricFamily[]>;
|
|
22
|
+
}
|
|
23
|
+
export declare const metricSampleSchema: v.ObjectSchema<{
|
|
24
|
+
readonly labels: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
25
|
+
readonly value: v.NumberSchema<undefined>;
|
|
26
|
+
}, undefined>;
|
|
27
|
+
export declare const metricFamilySchema: v.ObjectSchema<{
|
|
28
|
+
readonly name: v.StringSchema<undefined>;
|
|
29
|
+
readonly help: v.StringSchema<undefined>;
|
|
30
|
+
readonly type: v.PicklistSchema<["counter", "gauge"], undefined>;
|
|
31
|
+
readonly samples: v.ArraySchema<v.ObjectSchema<{
|
|
32
|
+
readonly labels: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
33
|
+
readonly value: v.NumberSchema<undefined>;
|
|
34
|
+
}, undefined>, undefined>;
|
|
35
|
+
}, undefined>;
|
|
36
|
+
export declare function parseMetricsDuration(value: string): number;
|
|
37
|
+
export declare function validateMetricFamilies(families: MetricFamily[]): MetricFamily[];
|
|
38
|
+
export declare function addMetricLabels(families: MetricFamily[], labels: Record<string, string>): MetricFamily[];
|
|
39
|
+
export declare function mergeMetricFamilies(input: MetricFamily[][]): MetricFamily[];
|
|
40
|
+
export declare function serializePrometheus(families: MetricFamily[]): string;
|
|
41
|
+
export interface MetricsSnapshot {
|
|
42
|
+
collectedAt: number;
|
|
43
|
+
families: MetricFamily[];
|
|
44
|
+
}
|
|
45
|
+
export interface MetricsLease {
|
|
46
|
+
holder: string;
|
|
47
|
+
expiresAt: number;
|
|
48
|
+
}
|
|
49
|
+
export interface MetricsDurableEnv {
|
|
50
|
+
[key: string]: unknown;
|
|
51
|
+
}
|
|
52
|
+
type MetricsDurableStorage = {
|
|
53
|
+
get<T>(key: string): Promise<T | undefined>;
|
|
54
|
+
put<T>(key: string, value: T): Promise<void>;
|
|
55
|
+
delete(key: string): Promise<boolean>;
|
|
56
|
+
setAlarm(scheduledTime: number | Date): Promise<void>;
|
|
57
|
+
};
|
|
58
|
+
declare class MetricsDurableObjectBase {
|
|
59
|
+
readonly ctx: {
|
|
60
|
+
storage: MetricsDurableStorage;
|
|
61
|
+
};
|
|
62
|
+
readonly env: MetricsDurableEnv;
|
|
63
|
+
constructor(...args: [ctx: {
|
|
64
|
+
storage: MetricsDurableStorage;
|
|
65
|
+
}, env: MetricsDurableEnv]);
|
|
66
|
+
}
|
|
67
|
+
export type MetricsDurableObjectConstructor = new (...args: any[]) => MetricsDurableObjectBase;
|
|
68
|
+
/** Creates a cache class using the runtime DurableObject base supplied by the Worker entrypoint. */
|
|
69
|
+
export declare function createBobraMetricsCacheClass<TBase extends MetricsDurableObjectConstructor>(DurableObjectBase: TBase): {
|
|
70
|
+
new (...args: any[]): {
|
|
71
|
+
readSnapshot(key: string): Promise<MetricsSnapshot | undefined>;
|
|
72
|
+
writeSnapshot(key: string, snapshot: MetricsSnapshot): Promise<void>;
|
|
73
|
+
deleteSnapshot(key: string): Promise<void>;
|
|
74
|
+
acquireLease(key: string, holder: string, ttlMs: number): Promise<boolean>;
|
|
75
|
+
releaseLease(key: string, holder: string): Promise<void>;
|
|
76
|
+
readonly ctx: {
|
|
77
|
+
storage: MetricsDurableStorage;
|
|
78
|
+
};
|
|
79
|
+
readonly env: MetricsDurableEnv;
|
|
80
|
+
};
|
|
81
|
+
} & TBase;
|
|
82
|
+
/** Coordinator owns the next alarm timestamp; application code performs collection through Service Bindings. */
|
|
83
|
+
export declare function createBobraMetricsCoordinatorClass<TBase extends MetricsDurableObjectConstructor>(DurableObjectBase: TBase): {
|
|
84
|
+
new (...args: any[]): {
|
|
85
|
+
scheduleNext(at: number): Promise<void>;
|
|
86
|
+
readMergedSnapshot(): Promise<MetricsSnapshot | undefined>;
|
|
87
|
+
refresh(): Promise<MetricsSnapshot>;
|
|
88
|
+
alarm(): Promise<void>;
|
|
89
|
+
readSnapshot(key: string): Promise<MetricsSnapshot | undefined>;
|
|
90
|
+
writeSnapshot(key: string, snapshot: MetricsSnapshot): Promise<void>;
|
|
91
|
+
deleteSnapshot(key: string): Promise<void>;
|
|
92
|
+
acquireLease(key: string, holder: string, ttlMs: number): Promise<boolean>;
|
|
93
|
+
releaseLease(key: string, holder: string): Promise<void>;
|
|
94
|
+
readonly ctx: {
|
|
95
|
+
storage: MetricsDurableStorage;
|
|
96
|
+
};
|
|
97
|
+
readonly env: MetricsDurableEnv;
|
|
98
|
+
};
|
|
99
|
+
} & TBase;
|
|
100
|
+
declare const BobraMetricsCache_base: {
|
|
101
|
+
new (...args: any[]): {
|
|
102
|
+
readSnapshot(key: string): Promise<MetricsSnapshot | undefined>;
|
|
103
|
+
writeSnapshot(key: string, snapshot: MetricsSnapshot): Promise<void>;
|
|
104
|
+
deleteSnapshot(key: string): Promise<void>;
|
|
105
|
+
acquireLease(key: string, holder: string, ttlMs: number): Promise<boolean>;
|
|
106
|
+
releaseLease(key: string, holder: string): Promise<void>;
|
|
107
|
+
readonly ctx: {
|
|
108
|
+
storage: MetricsDurableStorage;
|
|
109
|
+
};
|
|
110
|
+
readonly env: MetricsDurableEnv;
|
|
111
|
+
};
|
|
112
|
+
} & typeof MetricsDurableObjectBase;
|
|
113
|
+
export declare class BobraMetricsCache extends BobraMetricsCache_base {
|
|
114
|
+
}
|
|
115
|
+
declare const BobraMetricsCoordinator_base: {
|
|
116
|
+
new (...args: any[]): {
|
|
117
|
+
scheduleNext(at: number): Promise<void>;
|
|
118
|
+
readMergedSnapshot(): Promise<MetricsSnapshot | undefined>;
|
|
119
|
+
refresh(): Promise<MetricsSnapshot>;
|
|
120
|
+
alarm(): Promise<void>;
|
|
121
|
+
readSnapshot(key: string): Promise<MetricsSnapshot | undefined>;
|
|
122
|
+
writeSnapshot(key: string, snapshot: MetricsSnapshot): Promise<void>;
|
|
123
|
+
deleteSnapshot(key: string): Promise<void>;
|
|
124
|
+
acquireLease(key: string, holder: string, ttlMs: number): Promise<boolean>;
|
|
125
|
+
releaseLease(key: string, holder: string): Promise<void>;
|
|
126
|
+
readonly ctx: {
|
|
127
|
+
storage: MetricsDurableStorage;
|
|
128
|
+
};
|
|
129
|
+
readonly env: MetricsDurableEnv;
|
|
130
|
+
};
|
|
131
|
+
} & typeof MetricsDurableObjectBase;
|
|
132
|
+
export declare class BobraMetricsCoordinator extends BobraMetricsCoordinator_base {
|
|
133
|
+
}
|
|
134
|
+
/** Provider for a normal `observability` handler. It performs one Service Binding call per participating Worker. */
|
|
135
|
+
export declare function createObservabilityMetricsProvider(): MetricsProvider;
|
|
136
|
+
export declare function collectObservabilityMetricGroups(context: MetricsCollectionContext): Promise<{
|
|
137
|
+
families: MetricFamily[];
|
|
138
|
+
successfulProviders: number;
|
|
139
|
+
}>;
|
|
140
|
+
export {};
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import * as v from 'valibot';
|
|
2
|
+
import { getWorkerMetricsConfig, loadConfig, serviceToBindingName } from '../../core/config';
|
|
3
|
+
export const METRICS_CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
|
|
4
|
+
const metricName = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
|
|
5
|
+
const labelName = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
6
|
+
export const metricSampleSchema = v.object({ labels: v.optional(v.record(v.string(), v.string())), value: v.number() });
|
|
7
|
+
export const metricFamilySchema = v.object({ name: v.string(), help: v.string(), type: v.picklist(['counter', 'gauge']), samples: v.array(metricSampleSchema) });
|
|
8
|
+
export function parseMetricsDuration(value) {
|
|
9
|
+
const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(value);
|
|
10
|
+
if (!match)
|
|
11
|
+
throw new Error(`Invalid metrics duration '${value}'`);
|
|
12
|
+
const multipliers = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 };
|
|
13
|
+
return Number(match[1]) * multipliers[match[2]];
|
|
14
|
+
}
|
|
15
|
+
function escapeHelp(value) { return value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); }
|
|
16
|
+
function escapeLabel(value) { return value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"'); }
|
|
17
|
+
function sampleKey(labels) { return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}=${value}`).join(','); }
|
|
18
|
+
export function validateMetricFamilies(families) {
|
|
19
|
+
for (const family of families) {
|
|
20
|
+
v.parse(metricFamilySchema, family);
|
|
21
|
+
if (!metricName.test(family.name))
|
|
22
|
+
throw new Error(`Invalid Prometheus metric name '${family.name}'`);
|
|
23
|
+
for (const sample of family.samples) {
|
|
24
|
+
if (!Number.isFinite(sample.value))
|
|
25
|
+
throw new Error(`Metric '${family.name}' has a non-finite value`);
|
|
26
|
+
for (const label of Object.keys(sample.labels || {}))
|
|
27
|
+
if (!labelName.test(label))
|
|
28
|
+
throw new Error(`Invalid Prometheus label name '${label}'`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return families;
|
|
32
|
+
}
|
|
33
|
+
export function addMetricLabels(families, labels) {
|
|
34
|
+
return families.map((family) => ({ ...family, samples: family.samples.map((sample) => {
|
|
35
|
+
const sampleLabels = sample.labels || {};
|
|
36
|
+
for (const [key, value] of Object.entries(labels))
|
|
37
|
+
if (sampleLabels[key] !== undefined && sampleLabels[key] !== value)
|
|
38
|
+
throw new Error(`Metric '${family.name}' label '${key}' conflicts with configured source label`);
|
|
39
|
+
return { ...sample, labels: { ...labels, ...sampleLabels } };
|
|
40
|
+
}) }));
|
|
41
|
+
}
|
|
42
|
+
export function mergeMetricFamilies(input) {
|
|
43
|
+
const merged = new Map();
|
|
44
|
+
const invalidFamilies = new Set();
|
|
45
|
+
const values = new Map();
|
|
46
|
+
const conflictedSamples = new Set();
|
|
47
|
+
for (const group of input)
|
|
48
|
+
for (const family of validateMetricFamilies(group)) {
|
|
49
|
+
const current = merged.get(family.name);
|
|
50
|
+
if (!current)
|
|
51
|
+
merged.set(family.name, { ...family, samples: [] });
|
|
52
|
+
else if (current.help !== family.help || current.type !== family.type) {
|
|
53
|
+
invalidFamilies.add(family.name);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const destination = merged.get(family.name);
|
|
57
|
+
for (const sample of family.samples) {
|
|
58
|
+
const key = `${family.name}|${sampleKey(sample.labels || {})}`;
|
|
59
|
+
if (conflictedSamples.has(key))
|
|
60
|
+
continue;
|
|
61
|
+
const existing = values.get(key);
|
|
62
|
+
if (existing === undefined) {
|
|
63
|
+
values.set(key, sample.value);
|
|
64
|
+
destination.samples.push({ ...sample, labels: { ...(sample.labels || {}) } });
|
|
65
|
+
}
|
|
66
|
+
else if (existing !== sample.value) {
|
|
67
|
+
conflictedSamples.add(key);
|
|
68
|
+
values.delete(key);
|
|
69
|
+
destination.samples = destination.samples.filter((entry) => sampleKey(entry.labels || {}) !== sampleKey(sample.labels || {}));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
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 || {}))) }));
|
|
74
|
+
}
|
|
75
|
+
export function serializePrometheus(families) {
|
|
76
|
+
const lines = [];
|
|
77
|
+
for (const family of mergeMetricFamilies([families])) {
|
|
78
|
+
lines.push(`# HELP ${family.name} ${escapeHelp(family.help)}`, `# TYPE ${family.name} ${family.type}`);
|
|
79
|
+
for (const sample of family.samples) {
|
|
80
|
+
const labels = sample.labels || {};
|
|
81
|
+
const rendered = Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}="${escapeLabel(value)}"`).join(',');
|
|
82
|
+
lines.push(`${family.name}${rendered ? `{${rendered}}` : ''} ${sample.value}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return lines.length ? `${lines.join('\n')}\n` : '';
|
|
86
|
+
}
|
|
87
|
+
class MetricsDurableObjectBase {
|
|
88
|
+
ctx;
|
|
89
|
+
env;
|
|
90
|
+
constructor(...args) {
|
|
91
|
+
[this.ctx, this.env] = args;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Creates a cache class using the runtime DurableObject base supplied by the Worker entrypoint. */
|
|
95
|
+
export function createBobraMetricsCacheClass(DurableObjectBase) {
|
|
96
|
+
return class BobraMetricsCache extends DurableObjectBase {
|
|
97
|
+
async readSnapshot(key) { return this.ctx.storage.get(`snapshot:${key}`); }
|
|
98
|
+
async writeSnapshot(key, snapshot) { await this.ctx.storage.put(`snapshot:${key}`, snapshot); }
|
|
99
|
+
async deleteSnapshot(key) { await this.ctx.storage.delete(`snapshot:${key}`); }
|
|
100
|
+
async acquireLease(key, holder, ttlMs) {
|
|
101
|
+
const leaseKey = `lease:${key}`;
|
|
102
|
+
const current = await this.ctx.storage.get(leaseKey);
|
|
103
|
+
const now = Date.now();
|
|
104
|
+
if (current && current.expiresAt > now && current.holder !== holder)
|
|
105
|
+
return false;
|
|
106
|
+
await this.ctx.storage.put(leaseKey, { holder, expiresAt: now + ttlMs });
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
async releaseLease(key, holder) {
|
|
110
|
+
const leaseKey = `lease:${key}`;
|
|
111
|
+
const current = await this.ctx.storage.get(leaseKey);
|
|
112
|
+
if (current?.holder === holder)
|
|
113
|
+
await this.ctx.storage.delete(leaseKey);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** Coordinator owns the next alarm timestamp; application code performs collection through Service Bindings. */
|
|
118
|
+
export function createBobraMetricsCoordinatorClass(DurableObjectBase) {
|
|
119
|
+
const BobraMetricsCache = createBobraMetricsCacheClass(DurableObjectBase);
|
|
120
|
+
return class BobraMetricsCoordinator extends BobraMetricsCache {
|
|
121
|
+
async scheduleNext(at) { await this.ctx.storage.put('next_alarm_at', at); await this.ctx.storage.setAlarm(at); }
|
|
122
|
+
async readMergedSnapshot() { return this.readSnapshot('merged'); }
|
|
123
|
+
async refresh() {
|
|
124
|
+
const config = await loadConfig(this.env);
|
|
125
|
+
const workerName = Object.entries(config.workers).find(([, worker]) => worker.handlers.includes('observability'))?.[0] || String(this.env.WORKER_NAME || 'observability');
|
|
126
|
+
const policy = config.workers[workerName] ? getWorkerMetricsConfig(config, workerName).cache : undefined;
|
|
127
|
+
const holder = crypto.randomUUID();
|
|
128
|
+
const leaseTtl = policy?.provider_timeout ? parseMetricsDuration(policy.provider_timeout) : 15_000;
|
|
129
|
+
if (!await this.acquireLease('merged', holder, leaseTtl)) {
|
|
130
|
+
const existing = await this.readMergedSnapshot();
|
|
131
|
+
const maxStaleness = policy?.max_staleness ? parseMetricsDuration(policy.max_staleness) : 120_000;
|
|
132
|
+
if (existing && Date.now() - existing.collectedAt <= maxStaleness)
|
|
133
|
+
return existing;
|
|
134
|
+
throw new Error('Metrics aggregation refresh already in progress');
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
const result = await collectObservabilityMetricGroups({ env: this.env, workerName, handlerName: 'observability' });
|
|
138
|
+
if (result.successfulProviders === 0)
|
|
139
|
+
throw new Error('No metrics provider returned a successful response');
|
|
140
|
+
const snapshot = { collectedAt: Date.now(), families: result.families };
|
|
141
|
+
await this.writeSnapshot('merged', snapshot);
|
|
142
|
+
return snapshot;
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
await this.releaseLease('merged', holder);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async alarm() {
|
|
149
|
+
const config = await loadConfig(this.env);
|
|
150
|
+
const workerName = Object.entries(config.workers).find(([, worker]) => worker.handlers.includes('observability'))?.[0] || String(this.env.WORKER_NAME || 'observability');
|
|
151
|
+
const policy = config.workers[workerName] ? getWorkerMetricsConfig(config, workerName).cache : undefined;
|
|
152
|
+
try {
|
|
153
|
+
await this.refresh();
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
const delay = policy?.freshness ? parseMetricsDuration(policy.freshness) : 60_000;
|
|
157
|
+
await this.scheduleNext(Date.now() + delay);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
// Node-safe classes for configuration/tests. Worker entrypoints must create
|
|
163
|
+
// their exports with cloudflare:workers DurableObject to enable RPC.
|
|
164
|
+
export class BobraMetricsCache extends createBobraMetricsCacheClass(MetricsDurableObjectBase) {
|
|
165
|
+
}
|
|
166
|
+
export class BobraMetricsCoordinator extends createBobraMetricsCoordinatorClass(MetricsDurableObjectBase) {
|
|
167
|
+
}
|
|
168
|
+
/** Provider for a normal `observability` handler. It performs one Service Binding call per participating Worker. */
|
|
169
|
+
export function createObservabilityMetricsProvider() {
|
|
170
|
+
return {
|
|
171
|
+
async collect(context) {
|
|
172
|
+
const result = await collectObservabilityMetricGroups(context);
|
|
173
|
+
if (result.successfulProviders === 0)
|
|
174
|
+
throw new Error('No metrics provider returned a successful response');
|
|
175
|
+
return result.families;
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
export async function collectObservabilityMetricGroups(context) {
|
|
180
|
+
const config = await loadConfig(context.env);
|
|
181
|
+
const groups = [];
|
|
182
|
+
let successfulProviders = 0;
|
|
183
|
+
await Promise.all(Object.entries(config.workers).filter(([workerName, worker]) => workerName !== context.workerName && worker.metrics?.enabled).map(async ([workerName]) => {
|
|
184
|
+
const binding = context.env[serviceToBindingName(workerName)];
|
|
185
|
+
if (!binding)
|
|
186
|
+
return;
|
|
187
|
+
const token = config.metrics?.internal_token_binding ? context.env[config.metrics.internal_token_binding] : undefined;
|
|
188
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
189
|
+
if (typeof token === 'string')
|
|
190
|
+
headers['X-Internal-Token'] = token;
|
|
191
|
+
const response = await binding.fetch('http://internal/_bobra/metrics/collect', { method: 'POST', headers, body: '{}' });
|
|
192
|
+
if (!response.ok)
|
|
193
|
+
return;
|
|
194
|
+
const payload = await response.json();
|
|
195
|
+
if (!payload.families)
|
|
196
|
+
return;
|
|
197
|
+
successfulProviders += 1;
|
|
198
|
+
groups.push(payload.families);
|
|
199
|
+
}));
|
|
200
|
+
return { families: mergeMetricFamilies(groups), successfulProviders };
|
|
201
|
+
}
|
|
202
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../batteries/metrics/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE7F,MAAM,CAAC,MAAM,oBAAoB,GAAG,0CAA0C,CAAC;AAC/E,MAAM,UAAU,GAAG,4BAA4B,CAAC;AAChD,MAAM,SAAS,GAAG,0BAA0B,CAAC;AAQ7C,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AACxH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAC;AAEjK,MAAM,UAAU,oBAAoB,CAAC,KAAa;IAChD,MAAM,KA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C;QAC/E,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,KAAK,CAAC;QACnE,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,wCAAwC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACxH,IAAI,CAAC,QAAQ,CAAC,EAAE;YAAE,OAAO;QACzB,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAmC,CAAC;QACvE,IAAI,CAAC,OAAO,CAAC,QAAQ;YAAE,OAAO;QAC9B,mBAAmB,IAAI,CAAC,CAAC;QACzB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC,CAAC;IACJ,OAAO,EAAE,QAAQ,EAAE,mBAAmB,CAAC,MAAM,CAAC,EAAE,mBAAmB,EAAE,CAAC;AAC5E,CAAC"}
|
package/dist/core/config.d.ts
CHANGED
|
@@ -120,6 +120,7 @@ export interface WorkerConfig {
|
|
|
120
120
|
cf_routes?: CloudflareRoute[];
|
|
121
121
|
assets?: AssetsConfig;
|
|
122
122
|
placement?: WorkerPlacementConfig;
|
|
123
|
+
metrics?: WorkerMetricsConfig;
|
|
123
124
|
observability?: {
|
|
124
125
|
logs?: {
|
|
125
126
|
enabled?: boolean;
|
|
@@ -169,11 +170,57 @@ export interface AppConfig {
|
|
|
169
170
|
pgEdge: PgEdgeConfig;
|
|
170
171
|
vars?: Record<string, string | number | boolean | JSONValue>;
|
|
171
172
|
placement?: WorkerPlacementConfig;
|
|
173
|
+
metrics?: MetricsConfig;
|
|
172
174
|
workers: Record<string, WorkerConfig>;
|
|
173
175
|
router: RouterConfig;
|
|
174
176
|
}
|
|
177
|
+
export interface MetricsCacheConfig {
|
|
178
|
+
enabled: boolean;
|
|
179
|
+
backend: 'durable-object';
|
|
180
|
+
freshness: string;
|
|
181
|
+
max_staleness: string;
|
|
182
|
+
provider_timeout: string;
|
|
183
|
+
force_refresh_cooldown: string;
|
|
184
|
+
adaptive: {
|
|
185
|
+
enabled: boolean;
|
|
186
|
+
recurring_request_count: number;
|
|
187
|
+
recurring_window: string;
|
|
188
|
+
};
|
|
189
|
+
alarm: {
|
|
190
|
+
enabled: boolean;
|
|
191
|
+
retry_initial: string;
|
|
192
|
+
retry_max: string;
|
|
193
|
+
retry_multiplier: number;
|
|
194
|
+
jitter_percent: number;
|
|
195
|
+
};
|
|
196
|
+
discovery: {
|
|
197
|
+
refresh_interval: string;
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
export interface MetricsLabelsConfig {
|
|
201
|
+
source: {
|
|
202
|
+
enabled: boolean;
|
|
203
|
+
app: string;
|
|
204
|
+
worker: string;
|
|
205
|
+
handler: string;
|
|
206
|
+
};
|
|
207
|
+
static: Record<string, string | null>;
|
|
208
|
+
}
|
|
209
|
+
export interface MetricsConfig {
|
|
210
|
+
enabled: boolean;
|
|
211
|
+
endpoint_path: string;
|
|
212
|
+
/** Existing app init-token binding used only for stateless Worker-to-Worker collection. */
|
|
213
|
+
internal_token_binding?: string;
|
|
214
|
+
cache: MetricsCacheConfig;
|
|
215
|
+
labels: MetricsLabelsConfig;
|
|
216
|
+
}
|
|
217
|
+
/** Worker policy can override collection behavior, but collection authentication is application-global. */
|
|
218
|
+
export type WorkerMetricsConfig = Omit<Partial<MetricsConfig>, 'internal_token_binding'>;
|
|
219
|
+
export declare const defaultMetricsConfig: MetricsConfig;
|
|
175
220
|
export declare const defaultConfig: AppConfig;
|
|
176
221
|
export declare function parseConfig(yamlContent: string, env?: Record<string, unknown>): AppConfig;
|
|
222
|
+
/** Effective metrics policy follows the same global -> worker hierarchy as logging. */
|
|
223
|
+
export declare function getWorkerMetricsConfig(config: AppConfig, workerName: string): MetricsConfig;
|
|
177
224
|
export declare function loadConfig(env?: {
|
|
178
225
|
CONFIG_CONTENT?: string;
|
|
179
226
|
[key: string]: unknown;
|
package/dist/core/config.js
CHANGED
|
@@ -41,6 +41,17 @@ export function flattenHyperdriveConfigs(postgresConfig) {
|
|
|
41
41
|
}
|
|
42
42
|
return result;
|
|
43
43
|
}
|
|
44
|
+
export const defaultMetricsConfig = {
|
|
45
|
+
enabled: false,
|
|
46
|
+
endpoint_path: '/metrics',
|
|
47
|
+
cache: {
|
|
48
|
+
enabled: true, backend: 'durable-object', freshness: '60s', max_staleness: '120s', provider_timeout: '15s', force_refresh_cooldown: '10s',
|
|
49
|
+
adaptive: { enabled: true, recurring_request_count: 2, recurring_window: '120s' },
|
|
50
|
+
alarm: { enabled: true, retry_initial: '5s', retry_max: '5m', retry_multiplier: 2, jitter_percent: 10 },
|
|
51
|
+
discovery: { refresh_interval: '5m' },
|
|
52
|
+
},
|
|
53
|
+
labels: { source: { enabled: true, app: 'bobra_app', worker: 'bobra_worker', handler: 'bobra_handler' }, static: {} },
|
|
54
|
+
};
|
|
44
55
|
// Default configuration — apps should override these via their config.yml
|
|
45
56
|
export const defaultConfig = {
|
|
46
57
|
cors: {
|
|
@@ -60,6 +71,7 @@ export const defaultConfig = {
|
|
|
60
71
|
},
|
|
61
72
|
db_engine: 'postgres',
|
|
62
73
|
vars: {},
|
|
74
|
+
metrics: defaultMetricsConfig,
|
|
63
75
|
workers: {},
|
|
64
76
|
router: {
|
|
65
77
|
name: 'example-app-router-worker',
|
|
@@ -94,6 +106,7 @@ export function parseConfig(yamlContent, env) {
|
|
|
94
106
|
...parsed.pgEdge,
|
|
95
107
|
},
|
|
96
108
|
logging: parsed.logging,
|
|
109
|
+
metrics: mergeMetricsConfig(defaultMetricsConfig, parsed.metrics),
|
|
97
110
|
vars: parsed.vars || {},
|
|
98
111
|
workers: parsed.workers || {},
|
|
99
112
|
router: {
|
|
@@ -113,6 +126,24 @@ export function parseConfig(yamlContent, env) {
|
|
|
113
126
|
throw new Error(`Invalid YAML configuration: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
114
127
|
}
|
|
115
128
|
}
|
|
129
|
+
function mergeMetricsConfig(base, override) {
|
|
130
|
+
return {
|
|
131
|
+
...base, ...override,
|
|
132
|
+
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 } },
|
|
133
|
+
labels: { ...base.labels, ...override?.labels, source: { ...base.labels.source, ...override?.labels?.source }, static: { ...base.labels.static, ...override?.labels?.static } },
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** Effective metrics policy follows the same global -> worker hierarchy as logging. */
|
|
137
|
+
export function getWorkerMetricsConfig(config, workerName) {
|
|
138
|
+
// Generator callers receive raw YAML while Worker runtime receives parsed
|
|
139
|
+
// config. Start from defaults in both cases so partial global policy is safe.
|
|
140
|
+
const globalMetrics = mergeMetricsConfig(defaultMetricsConfig, config.metrics);
|
|
141
|
+
const effective = mergeMetricsConfig(globalMetrics, config.workers?.[workerName]?.metrics);
|
|
142
|
+
effective.internal_token_binding = globalMetrics.internal_token_binding;
|
|
143
|
+
// Global enable is a master switch; a Worker opts in explicitly, matching logging's worker ownership.
|
|
144
|
+
effective.enabled = Boolean(globalMetrics.enabled && config.workers?.[workerName]?.metrics?.enabled);
|
|
145
|
+
return effective;
|
|
146
|
+
}
|
|
116
147
|
// Cache for parsed configuration to avoid repeated decompression/parsing
|
|
117
148
|
let configCache = null;
|
|
118
149
|
// Load configuration from environment or use default
|
|
@@ -287,6 +318,10 @@ export function validateConfig(config) {
|
|
|
287
318
|
const routerWorkerName = getRouterWorkerName(config);
|
|
288
319
|
const allHandlerIds = new Set();
|
|
289
320
|
const allServiceIds = new Set();
|
|
321
|
+
const metricsWorkers = Object.entries(config.workers || {}).filter(([workerName]) => getWorkerMetricsConfig(config, workerName).enabled);
|
|
322
|
+
if (metricsWorkers.length > 0 && !config.metrics?.internal_token_binding) {
|
|
323
|
+
throw new Error('Metrics-enabled workers require metrics.internal_token_binding for internal collection');
|
|
324
|
+
}
|
|
290
325
|
for (const [workerName, worker] of Object.entries(config.workers || {})) {
|
|
291
326
|
for (const handlerId of worker.handlers || []) {
|
|
292
327
|
if (allHandlerIds.has(handlerId)) {
|
|
@@ -305,6 +340,23 @@ export function validateConfig(config) {
|
|
|
305
340
|
allServiceIds.add(service.service);
|
|
306
341
|
}
|
|
307
342
|
}
|
|
343
|
+
for (const [workerName, worker] of Object.entries(config.workers || {})) {
|
|
344
|
+
const metrics = getWorkerMetricsConfig(config, workerName);
|
|
345
|
+
if (!metrics.enabled)
|
|
346
|
+
continue;
|
|
347
|
+
if (!worker.handlers?.length)
|
|
348
|
+
throw new Error(`Metrics-enabled worker '${workerName}' must declare handlers`);
|
|
349
|
+
if (!metrics.endpoint_path.startsWith('/'))
|
|
350
|
+
throw new Error(`Metrics endpoint_path for worker '${workerName}' must start with '/'`);
|
|
351
|
+
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];
|
|
352
|
+
for (const value of durationKeys)
|
|
353
|
+
if (!/^\d+(?:\.\d+)?(?:ms|s|m|h)$/.test(value))
|
|
354
|
+
throw new Error(`Invalid metrics duration '${value}' for worker '${workerName}'`);
|
|
355
|
+
if (metrics.cache.adaptive.recurring_request_count < 1 || metrics.cache.alarm.retry_multiplier < 1 || metrics.cache.alarm.jitter_percent < 0)
|
|
356
|
+
throw new Error(`Invalid metrics retry/adaptive policy for worker '${workerName}'`);
|
|
357
|
+
if (!metrics.labels.source.app || !metrics.labels.source.worker || !metrics.labels.source.handler)
|
|
358
|
+
throw new Error(`Metrics source labels for worker '${workerName}' must be non-empty`);
|
|
359
|
+
}
|
|
308
360
|
}
|
|
309
361
|
// Helper function to get service binding with direct call fallback
|
|
310
362
|
export function getServiceBindingWithFallback(env, bindingName, config, workerName) {
|