@mastra/factory 0.29.0-alpha.2 → 0.29.0-alpha.3
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/README.md +40 -1
- package/dist/factory.d.ts +8 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +26 -2
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +30 -1
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +17 -3
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +11 -2
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +11 -0
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/metrics/collectors/postgres.d.ts +29 -0
- package/dist/metrics/collectors/postgres.d.ts.map +1 -0
- package/dist/metrics/collectors/postgres.js +121 -0
- package/dist/metrics/collectors/postgres.js.map +1 -0
- package/dist/metrics/collectors/probe.d.ts +22 -0
- package/dist/metrics/collectors/probe.d.ts.map +1 -0
- package/dist/metrics/collectors/probe.js +69 -0
- package/dist/metrics/collectors/probe.js.map +1 -0
- package/dist/metrics/collectors/process.d.ts +13 -0
- package/dist/metrics/collectors/process.d.ts.map +1 -0
- package/dist/metrics/collectors/process.js +85 -0
- package/dist/metrics/collectors/process.js.map +1 -0
- package/dist/metrics/collectors/redis.d.ts +29 -0
- package/dist/metrics/collectors/redis.d.ts.map +1 -0
- package/dist/metrics/collectors/redis.js +97 -0
- package/dist/metrics/collectors/redis.js.map +1 -0
- package/dist/metrics/config.d.ts +33 -0
- package/dist/metrics/config.d.ts.map +1 -0
- package/dist/metrics/config.js +65 -0
- package/dist/metrics/config.js.map +1 -0
- package/dist/metrics/index.d.ts +20 -0
- package/dist/metrics/index.d.ts.map +1 -0
- package/dist/metrics/index.js +65 -0
- package/dist/metrics/index.js.map +1 -0
- package/dist/metrics/intake.d.ts +28 -0
- package/dist/metrics/intake.d.ts.map +1 -0
- package/dist/metrics/intake.js +76 -0
- package/dist/metrics/intake.js.map +1 -0
- package/dist/metrics/metrics.d.ts +60 -0
- package/dist/metrics/metrics.d.ts.map +1 -0
- package/dist/metrics/metrics.js +182 -0
- package/dist/metrics/metrics.js.map +1 -0
- package/dist/metrics/sandbox.d.ts +35 -0
- package/dist/metrics/sandbox.d.ts.map +1 -0
- package/dist/metrics/sandbox.js +156 -0
- package/dist/metrics/sandbox.js.map +1 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -0
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +1 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +26 -8
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts +1 -0
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +1 -0
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +22 -14
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/sandbox/session-sandbox.d.ts +2 -0
- package/dist/sandbox/session-sandbox.d.ts.map +1 -1
- package/dist/sandbox/session-sandbox.js +7 -1
- package/dist/sandbox/session-sandbox.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +5 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +18 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/timing.d.ts +4 -1
- package/dist/timing.d.ts.map +1 -1
- package/dist/timing.js +12 -4
- package/dist/timing.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +7 -1
- package/dist/workspace.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../../src/metrics/config.ts"],"sourcesContent":["/** Metric groups a deployment can turn on, one per component to investigate. */\nexport const METRIC_GROUPS = ['process', 'postgres', 'redis', 'sandbox', 'intake'] as const;\nexport type MetricGroup = (typeof METRIC_GROUPS)[number];\n\nexport interface FactoryMetricsOptions {\n /** Groups to collect, or `'all'`. An empty list turns metrics off. */\n groups: readonly MetricGroup[] | 'all';\n /** How often gauges are sampled and aggregated timings are sent. Default 60s, minimum 15s. */\n intervalMs?: number;\n /** Most records sent per minute per process; the rest are dropped and counted. Default 500. */\n maxRecordsPerMinute?: number;\n}\n\nexport interface ResolvedMetricsConfig {\n groups: ReadonlySet<MetricGroup>;\n intervalMs: number;\n maxPerMinute: number;\n /** Group names that were asked for but don't exist. */\n unknownGroups: string[];\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\nconst MIN_INTERVAL_MS = 15_000;\n// Longest delay setInterval accepts; Node turns anything above it into 1 ms.\nconst MAX_INTERVAL_MS = 2_147_483_647;\nconst DEFAULT_MAX_PER_MINUTE = 500;\n\nfunction parseGroups(value: readonly string[] | 'all'): { groups: Set<MetricGroup>; unknownGroups: string[] } {\n if (value === 'all') return { groups: new Set(METRIC_GROUPS), unknownGroups: [] };\n const groups = new Set<MetricGroup>();\n const unknownGroups: string[] = [];\n for (const name of value) {\n if ((METRIC_GROUPS as readonly string[]).includes(name)) groups.add(name as MetricGroup);\n else unknownGroups.push(name);\n }\n return { groups, unknownGroups };\n}\n\n/**\n * Resolves which metric groups are on. Every record counts towards the deployment's observability\n * usage, so nothing is collected unless a group is asked for. Env vars override the code option:\n * `FACTORY_METRICS` (`all`, `0`, or a list like `sandbox,intake`), `FACTORY_METRICS_INTERVAL_MS`\n * and `FACTORY_METRICS_MAX_PER_MIN`. Returns `undefined` when no group is on.\n */\nexport function resolveMetricsConfig(\n option: FactoryMetricsOptions | undefined,\n env: NodeJS.ProcessEnv = process.env,\n): ResolvedMetricsConfig | undefined {\n const envGroups = env.FACTORY_METRICS?.trim();\n let requested: readonly string[] | 'all' | undefined = option?.groups;\n if (envGroups) {\n if (/^(0|false|no|off)$/i.test(envGroups)) return undefined;\n requested = /^(all|1|true|yes)$/i.test(envGroups)\n ? 'all'\n : envGroups\n .split(',')\n .map(name => name.trim())\n .filter(Boolean);\n }\n if (!requested) return undefined;\n const { groups, unknownGroups } = parseGroups(requested);\n if (groups.size === 0 && unknownGroups.length === 0) return undefined;\n\n const interval = Number(env.FACTORY_METRICS_INTERVAL_MS || option?.intervalMs);\n const maxPerMinute = Number(env.FACTORY_METRICS_MAX_PER_MIN || option?.maxRecordsPerMinute);\n return {\n groups,\n intervalMs:\n Number.isFinite(interval) && interval > 0\n ? Math.min(Math.max(interval, MIN_INTERVAL_MS), MAX_INTERVAL_MS)\n : DEFAULT_INTERVAL_MS,\n maxPerMinute: Number.isInteger(maxPerMinute) && maxPerMinute > 0 ? maxPerMinute : DEFAULT_MAX_PER_MINUTE,\n unknownGroups,\n };\n}\n\nexport type MetricsService = 'api' | 'worker' | 'all';\n\n/**\n * Which part of a split deployment this process is. Platform deploys a separate worker service\n * when the app has storage and pubsub: the API container runs with `MASTRA_WORKERS=false`, the\n * worker container with it set (empty, or a list of worker names). Unset means one process does both.\n */\nexport function metricsService(env: NodeJS.ProcessEnv = process.env): MetricsService {\n const workers = env.MASTRA_WORKERS;\n if (workers === undefined) return 'all';\n return workers.trim() === 'false' ? 'api' : 'worker';\n}\n"],"mappings":";;AACA,MAAa,gBAAgB;CAAC;CAAW;CAAY;CAAS;CAAW;AAAQ;AAoBjF,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AAExB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;AAE/B,SAAS,YAAY,OAAyF;CAC5G,IAAI,UAAU,OAA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etrics, MetricsTargets } from './metrics.js';
|
|
2
|
+
export { METRIC_GROUPS, metricsService, resolveMetricsConfig } from './config.js';
|
|
3
|
+
export type { FactoryMetricsOptions, MetricGroup } from './config.js';
|
|
4
|
+
export { FactoryMetrics, factoryMetrics, installFactoryMetrics } from './metrics.js';
|
|
5
|
+
export interface MetricsSources {
|
|
6
|
+
/** The Mastra storage, read for its `pg` pool when it's Postgres. */
|
|
7
|
+
storage: unknown;
|
|
8
|
+
vector: unknown;
|
|
9
|
+
pubsub: unknown;
|
|
10
|
+
/** Ids of the configured integrations; GitHub and Linear intake counts are sent as 0 when quiet. */
|
|
11
|
+
integrationIds?: readonly string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Builds the collectors for the enabled groups and starts the interval timer. Server-wide stats
|
|
15
|
+
* (Postgres activity, Redis memory and stream backlog) only run on the worker service (or a
|
|
16
|
+
* single-process deployment), so a split deployment doesn't report them twice. Returns a stop
|
|
17
|
+
* function that also closes the Redis monitor connection.
|
|
18
|
+
*/
|
|
19
|
+
export declare function startFactoryMetrics(metrics: FactoryMetrics, targets: MetricsTargets, sources: MetricsSources): () => Promise<void>;
|
|
20
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/metrics/index.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAoB,cAAc,EAAE,MAAM,cAAc,CAAC;AAGrF,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAClF,YAAY,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAIrF,MAAM,WAAW,cAAc;IAC7B,qEAAqE;IACrE,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;IAChB,MAAM,EAAE,OAAO,CAAC;IAChB,oGAAoG;IACpG,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACpC;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,cAAc,GACtB,MAAM,OAAO,CAAC,IAAI,CAAC,CAyDrB"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { countRunningSessionSandboxes } from "../sandbox/session-sandbox.js";
|
|
2
|
+
import { asPool, postgresPoolCollector, postgresStatsCollector } from "./collectors/postgres.js";
|
|
3
|
+
import { processCollector } from "./collectors/process.js";
|
|
4
|
+
import { asMonitorablePubSub, connectMonitor, redisProbeCollector, redisStatsCollector } from "./collectors/redis.js";
|
|
5
|
+
import { intakeCollector, keepIntakeSource } from "./intake.js";
|
|
6
|
+
import { sessionStartsCollector } from "./sandbox.js";
|
|
7
|
+
import { METRIC_GROUPS, metricsService, resolveMetricsConfig } from "./config.js";
|
|
8
|
+
import { FactoryMetrics, factoryMetrics, installFactoryMetrics } from "./metrics.js";
|
|
9
|
+
// src/metrics/index.ts
|
|
10
|
+
const SLOW_STATEMENTS_EVERY_MS = 6e5;
|
|
11
|
+
/**
|
|
12
|
+
* Builds the collectors for the enabled groups and starts the interval timer. Server-wide stats
|
|
13
|
+
* (Postgres activity, Redis memory and stream backlog) only run on the worker service (or a
|
|
14
|
+
* single-process deployment), so a split deployment doesn't report them twice. Returns a stop
|
|
15
|
+
* function that also closes the Redis monitor connection.
|
|
16
|
+
*/
|
|
17
|
+
function startFactoryMetrics(metrics, targets, sources) {
|
|
18
|
+
const intervalMs = metrics.intervalMs;
|
|
19
|
+
if (intervalMs === 0) return async () => {};
|
|
20
|
+
const timeoutMs = Math.min(5e3, intervalMs / 2);
|
|
21
|
+
const serverWide = metrics.service !== "api";
|
|
22
|
+
const collectors = [];
|
|
23
|
+
let redisClient;
|
|
24
|
+
if (metrics.enabled("process")) collectors.push(processCollector((kind, ms) => metrics.observe("process", "mastra_factory_gc_ms", ms, { kind })));
|
|
25
|
+
if (metrics.enabled("postgres")) {
|
|
26
|
+
const pools = {};
|
|
27
|
+
const store = asPool(sources.storage?.pool);
|
|
28
|
+
const vector = asPool(sources.vector?.pool);
|
|
29
|
+
if (store) pools.store = store;
|
|
30
|
+
if (vector) pools.vector = vector;
|
|
31
|
+
if (Object.keys(pools).length > 0) collectors.push(postgresPoolCollector(pools, timeoutMs));
|
|
32
|
+
const statsPool = store ?? vector;
|
|
33
|
+
if (statsPool && serverWide) {
|
|
34
|
+
const statementsEveryTicks = Math.max(1, Math.round(SLOW_STATEMENTS_EVERY_MS / intervalMs));
|
|
35
|
+
collectors.push(postgresStatsCollector(statsPool, timeoutMs, statementsEveryTicks, targets.getLogger));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (metrics.enabled("redis")) {
|
|
39
|
+
const pubsub = asMonitorablePubSub(sources.pubsub);
|
|
40
|
+
if (pubsub) {
|
|
41
|
+
redisClient = connectMonitor(pubsub, targets.getLogger);
|
|
42
|
+
collectors.push(redisProbeCollector(redisClient, timeoutMs));
|
|
43
|
+
const cluster = "masters" in redisClient;
|
|
44
|
+
if (serverWide && !cluster) collectors.push(redisStatsCollector(pubsub, redisClient, timeoutMs));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (metrics.enabled("sandbox")) {
|
|
48
|
+
collectors.push({ collect(sink) {
|
|
49
|
+
sink.emit("mastra_factory_sandboxes_active", countRunningSessionSandboxes());
|
|
50
|
+
} });
|
|
51
|
+
collectors.push(sessionStartsCollector());
|
|
52
|
+
}
|
|
53
|
+
if (metrics.enabled("intake")) {
|
|
54
|
+
for (const id of sources.integrationIds ?? []) if (id === "github" || id === "linear") keepIntakeSource(id);
|
|
55
|
+
collectors.push(intakeCollector());
|
|
56
|
+
}
|
|
57
|
+
metrics.start(targets, collectors);
|
|
58
|
+
return async () => {
|
|
59
|
+
metrics.stop();
|
|
60
|
+
await redisClient?.destroy?.();
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export { FactoryMetrics, METRIC_GROUPS, factoryMetrics, installFactoryMetrics, metricsService, resolveMetricsConfig, startFactoryMetrics };
|
|
64
|
+
|
|
65
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/metrics/index.ts"],"sourcesContent":["import { countRunningSessionSandboxes } from '../sandbox/session-sandbox.js';\nimport { postgresPoolCollector, postgresStatsCollector, asPool } from './collectors/postgres.js';\nimport type { PoolLike } from './collectors/postgres.js';\nimport { processCollector } from './collectors/process.js';\nimport { asMonitorablePubSub, connectMonitor, redisProbeCollector, redisStatsCollector } from './collectors/redis.js';\nimport type { RedisMonitorClient } from './collectors/redis.js';\nimport { intakeCollector, keepIntakeSource } from './intake.js';\nimport type { FactoryMetrics, MetricsCollector, MetricsTargets } from './metrics.js';\nimport { sessionStartsCollector } from './sandbox.js';\n\nexport { METRIC_GROUPS, metricsService, resolveMetricsConfig } from './config.js';\nexport type { FactoryMetricsOptions, MetricGroup } from './config.js';\nexport { FactoryMetrics, factoryMetrics, installFactoryMetrics } from './metrics.js';\n\nconst SLOW_STATEMENTS_EVERY_MS = 10 * 60_000;\n\nexport interface MetricsSources {\n /** The Mastra storage, read for its `pg` pool when it's Postgres. */\n storage: unknown;\n vector: unknown;\n pubsub: unknown;\n /** Ids of the configured integrations; GitHub and Linear intake counts are sent as 0 when quiet. */\n integrationIds?: readonly string[];\n}\n\n/**\n * Builds the collectors for the enabled groups and starts the interval timer. Server-wide stats\n * (Postgres activity, Redis memory and stream backlog) only run on the worker service (or a\n * single-process deployment), so a split deployment doesn't report them twice. Returns a stop\n * function that also closes the Redis monitor connection.\n */\nexport function startFactoryMetrics(\n metrics: FactoryMetrics,\n targets: MetricsTargets,\n sources: MetricsSources,\n): () => Promise<void> {\n const intervalMs = metrics.intervalMs;\n if (intervalMs === 0) return async () => {};\n const timeoutMs = Math.min(5_000, intervalMs / 2);\n const serverWide = metrics.service !== 'api';\n const collectors: MetricsCollector[] = [];\n let redisClient: RedisMonitorClient | undefined;\n\n if (metrics.enabled('process'))\n collectors.push(processCollector((kind, ms) => metrics.observe('process', 'mastra_factory_gc_ms', ms, { kind })));\n\n if (metrics.enabled('postgres')) {\n const pools: Record<string, PoolLike> = {};\n const store = asPool((sources.storage as { pool?: unknown } | undefined)?.pool);\n const vector = asPool((sources.vector as { pool?: unknown } | undefined)?.pool);\n if (store) pools.store = store;\n if (vector) pools.vector = vector;\n if (Object.keys(pools).length > 0) collectors.push(postgresPoolCollector(pools, timeoutMs));\n const statsPool = store ?? vector;\n if (statsPool && serverWide) {\n const statementsEveryTicks = Math.max(1, Math.round(SLOW_STATEMENTS_EVERY_MS / intervalMs));\n collectors.push(postgresStatsCollector(statsPool, timeoutMs, statementsEveryTicks, targets.getLogger));\n }\n }\n\n if (metrics.enabled('redis')) {\n const pubsub = asMonitorablePubSub(sources.pubsub);\n if (pubsub) {\n redisClient = connectMonitor(pubsub, targets.getLogger);\n collectors.push(redisProbeCollector(redisClient, timeoutMs));\n // On a cluster, INFO reads one node, so server-wide stats would mix nodes. Only the probe runs.\n const cluster = 'masters' in (redisClient as object);\n if (serverWide && !cluster) collectors.push(redisStatsCollector(pubsub, redisClient, timeoutMs));\n }\n }\n\n if (metrics.enabled('sandbox')) {\n collectors.push({\n collect(sink) {\n sink.emit('mastra_factory_sandboxes_active', countRunningSessionSandboxes());\n },\n });\n collectors.push(sessionStartsCollector());\n }\n\n if (metrics.enabled('intake')) {\n for (const id of sources.integrationIds ?? []) {\n if (id === 'github' || id === 'linear') keepIntakeSource(id);\n }\n collectors.push(intakeCollector());\n }\n\n metrics.start(targets, collectors);\n return async () => {\n metrics.stop();\n await redisClient?.destroy?.();\n };\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,2BAA2B;;;;;;;AAiBjC,SAAgB,o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GACZ,KAAK,KAAK,mCAAmC,6BAA6B,CAAC;EAC7E,EACF,CAAC;EACD,WAAW,KAAK,uBAAuB,CAAC;CAC1C;CAEA,IAAI,QAAQ,QAAQ,QAAQ,GAAG;EAC7B,KAAK,MAAM,MAAM,QAAQ,kBAAkB,CAAC,GAC1C,IAAI,OAAO,YAAY,OAAO,UAAU,iBAAiB,EAAE;EAE7D,WAAW,KAAK,gBAAgB,CAAC;CACnC;CAEA,QAAQ,MAAM,SAAS,UAAU;CACjC,OAAO,YAAY;EACjB,QAAQ,KAAK;EACb,MAAM,aAAa,UAAU;CAC/B;AACF"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { MetricsCollector } from './metrics.js';
|
|
2
|
+
export type IntakeSource = 'github' | 'linear' | 'gitlab';
|
|
3
|
+
/** One inbound event handed to a source's rules, by how it ended (`committed`, `replayed`, `ignored`, `missing`, `error`). */
|
|
4
|
+
export declare function recordIntakeEvent(source: IntakeSource, outcome: string): void;
|
|
5
|
+
/**
|
|
6
|
+
* Sends intake event counts for `source` every interval, 0 when quiet, so an idle source reads
|
|
7
|
+
* as zero instead of looking unreported.
|
|
8
|
+
*/
|
|
9
|
+
export declare function keepIntakeSource(source: IntakeSource): void;
|
|
10
|
+
/**
|
|
11
|
+
* One reconcile sweep. `replayed` counts changes the sweep found that live events never
|
|
12
|
+
* delivered: each one is a missed webhook.
|
|
13
|
+
*/
|
|
14
|
+
export declare function recordReconcileSweep(source: IntakeSource, kind: string, result: {
|
|
15
|
+
replayed: number;
|
|
16
|
+
ok: boolean;
|
|
17
|
+
}): void;
|
|
18
|
+
/**
|
|
19
|
+
* The reconcile worker for `source` started sweeping `kind`. The age counts from here until the
|
|
20
|
+
* first clean sweep, so a sweep that fails or stalls from boot shows a growing age instead of no series.
|
|
21
|
+
*/
|
|
22
|
+
export declare function recordSweepWorkerStarted(source: IntakeSource, kind: string): void;
|
|
23
|
+
/**
|
|
24
|
+
* Age of each source's last clean reconcile sweep, per kind. Growing without bound means the sweep has
|
|
25
|
+
* stalled, and webhooks it would have caught stay missed.
|
|
26
|
+
*/
|
|
27
|
+
export declare function intakeCollector(): MetricsCollector;
|
|
28
|
+
//# sourceMappingURL=intake.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake.d.ts","sourceRoot":"","sources":["../../src/metrics/intake.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAGrD,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE1D,8HAA8H;AAC9H,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAE7E;AAKD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CAK3D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,YAAY,EACpB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,OAAO,CAAA;CAAE,GACxC,IAAI,CAON;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAMjF;AAED;;;GAGG;AACH,wBAAgB,eAAe,IAAI,gBAAgB,CASlD"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { factoryMetrics } from "./metrics.js";
|
|
2
|
+
// src/metrics/intake.ts
|
|
3
|
+
/** One inbound event handed to a source's rules, by how it ended (`committed`, `replayed`, `ignored`, `missing`, `error`). */
|
|
4
|
+
function recordIntakeEvent(source, outcome) {
|
|
5
|
+
factoryMetrics().count("intake", "mastra_factory_intake_events_total", {
|
|
6
|
+
source,
|
|
7
|
+
outcome
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
const lastSweepAt = /* @__PURE__ */ new Map();
|
|
11
|
+
/**
|
|
12
|
+
* Sends intake event counts for `source` every interval, 0 when quiet, so an idle source reads
|
|
13
|
+
* as zero instead of looking unreported.
|
|
14
|
+
*/
|
|
15
|
+
function keepIntakeSource(source) {
|
|
16
|
+
const metrics = factoryMetrics();
|
|
17
|
+
for (const outcome of ["committed", "error"]) metrics.keepCounter("intake", "mastra_factory_intake_events_total", {
|
|
18
|
+
source,
|
|
19
|
+
outcome
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* One reconcile sweep. `replayed` counts changes the sweep found that live events never
|
|
24
|
+
* delivered: each one is a missed webhook.
|
|
25
|
+
*/
|
|
26
|
+
function recordReconcileSweep(source, kind, result) {
|
|
27
|
+
const metrics = factoryMetrics();
|
|
28
|
+
if (!metrics.enabled("intake")) return;
|
|
29
|
+
if (result.replayed > 0) metrics.count("intake", "mastra_factory_intake_replayed_total", {
|
|
30
|
+
source,
|
|
31
|
+
kind
|
|
32
|
+
}, result.replayed);
|
|
33
|
+
if (result.ok) lastSweepAt.set(`${source}:${kind}`, {
|
|
34
|
+
source,
|
|
35
|
+
kind,
|
|
36
|
+
at: Date.now()
|
|
37
|
+
});
|
|
38
|
+
else metrics.count("intake", "mastra_factory_intake_sweep_failures_total", {
|
|
39
|
+
source,
|
|
40
|
+
kind
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The reconcile worker for `source` started sweeping `kind`. The age counts from here until the
|
|
45
|
+
* first clean sweep, so a sweep that fails or stalls from boot shows a growing age instead of no series.
|
|
46
|
+
*/
|
|
47
|
+
function recordSweepWorkerStarted(source, kind) {
|
|
48
|
+
const metrics = factoryMetrics();
|
|
49
|
+
if (!metrics.enabled("intake")) return;
|
|
50
|
+
metrics.keepCounter("intake", "mastra_factory_intake_sweep_failures_total", {
|
|
51
|
+
source,
|
|
52
|
+
kind
|
|
53
|
+
});
|
|
54
|
+
const key = `${source}:${kind}`;
|
|
55
|
+
if (!lastSweepAt.has(key)) lastSweepAt.set(key, {
|
|
56
|
+
source,
|
|
57
|
+
kind,
|
|
58
|
+
at: Date.now()
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Age of each source's last clean reconcile sweep, per kind. Growing without bound means the sweep has
|
|
63
|
+
* stalled, and webhooks it would have caught stay missed.
|
|
64
|
+
*/
|
|
65
|
+
function intakeCollector() {
|
|
66
|
+
return { collect(sink) {
|
|
67
|
+
const now = Date.now();
|
|
68
|
+
for (const { source, kind, at } of lastSweepAt.values()) sink.emit("mastra_factory_intake_last_sweep_age_ms", now - at, {
|
|
69
|
+
source,
|
|
70
|
+
kind
|
|
71
|
+
});
|
|
72
|
+
} };
|
|
73
|
+
}
|
|
74
|
+
export { intakeCollector, keepIntakeSource, recordIntakeEvent, recordReconcileSweep, recordSweepWorkerStarted };
|
|
75
|
+
|
|
76
|
+
//# sourceMappingURL=intake.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake.js","names":[],"sources":["../../src/metrics/intake.ts"],"sourcesContent":["import type { MetricsCollector } from './metrics.js';\nimport { factoryMetrics } from './metrics.js';\n\nexport type IntakeSource = 'github' | 'linear' | 'gitlab';\n\n/** One inbound event handed to a source's rules, by how it ended (`committed`, `replayed`, `ignored`, `missing`, `error`). */\nexport function recordIntakeEvent(source: IntakeSource, outcome: string): void {\n factoryMetrics().count('intake', 'mastra_factory_intake_events_total', { source, outcome });\n}\n\n// When each source's reconcile sweep of each kind last finished cleanly, in this process.\nconst lastSweepAt = new Map<string, { source: IntakeSource; kind: string; at: number }>();\n\n/**\n * Sends intake event counts for `source` every interval, 0 when quiet, so an idle source reads\n * as zero instead of looking unreported.\n */\nexport function keepIntakeSource(source: IntakeSource): void {\n const metrics = factoryMetrics();\n for (const outcome of ['committed', 'error']) {\n metrics.keepCounter('intake', 'mastra_factory_intake_events_total', { source, outcome });\n }\n}\n\n/**\n * One reconcile sweep. `replayed` counts changes the sweep found that live events never\n * delivered: each one is a missed webhook.\n */\nexport function recordReconcileSweep(\n source: IntakeSource,\n kind: string,\n result: { replayed: number; ok: boolean },\n): void {\n const metrics = factoryMetrics();\n if (!metrics.enabled('intake')) return;\n if (result.replayed > 0)\n metrics.count('intake', 'mastra_factory_intake_replayed_total', { source, kind }, result.replayed);\n if (result.ok) lastSweepAt.set(`${source}:${kind}`, { source, kind, at: Date.now() });\n else metrics.count('intake', 'mastra_factory_intake_sweep_failures_total', { source, kind });\n}\n\n/**\n * The reconcile worker for `source` started sweeping `kind`. The age counts from here until the\n * first clean sweep, so a sweep that fails or stalls from boot shows a growing age instead of no series.\n */\nexport function recordSweepWorkerStarted(source: IntakeSource, kind: string): void {\n const metrics = factoryMetrics();\n if (!metrics.enabled('intake')) return;\n metrics.keepCounter('intake', 'mastra_factory_intake_sweep_failures_total', { source, kind });\n const key = `${source}:${kind}`;\n if (!lastSweepAt.has(key)) lastSweepAt.set(key, { source, kind, at: Date.now() });\n}\n\n/**\n * Age of each source's last clean reconcile sweep, per kind. Growing without bound means the sweep has\n * stalled, and webhooks it would have caught stay missed.\n */\nexport function intakeCollector(): MetricsCollector {\n return {\n collect(sink) {\n const now = Date.now();\n for (const { source, kind, at } of lastSweepAt.values()) {\n sink.emit('mastra_factory_intake_last_sweep_age_ms', now - at, { source, kind });\n }\n },\n };\n}\n"],"mappings":";;;AAMA,SAAgB,kBAAkB,QAAsB,SAAuB;CAC7E,eAAe,CAAC,CAAC,MAAM,UAAU,sCAAsC;EAAE;EAAQ;CAAQ,CAAC;AAC5F;AAGA,MAAM,8BAAc,IAAI,IAAgE;;;;;AAMxF,SAAgB,iBAAiB,QAA4B;CAC3D,MAAM,UAAU,eAAe;CAC/B,KAAK,MAAM,WAAW,CAAC,aAAa,OAAO,GACzC,QAAQ,YAAY,UAAU,sCAAsC;EAAE;EAAQ;CAAQ,CAAC;AAE3F;;;;;AAMA,SAAgB,qBACd,QACA,MACA,QACM;CACN,MAAM,UAAU,eAAe;CAC/B,IAAI,CAAC,QAAQ,QAAQ,QAAQ,GAAG;CAChC,IAAI,OAAO,WAAW,GACpB,QAAQ,MAAM,UAAU,wCAAwC;EAAE;EAAQ;CAAK,GAAG,OAAO,QAAQ;CACnG,IAAI,OAAO,IAAI,YAAY,IAAI,GAAG,OAAO,GAAG,QAAQ;EAAE;EAAQ;EAAM,IAAI,KAAK,IAAI;CAAE,CAAC;MAC/E,QAAQ,MAAM,UAAU,8CAA8C;EAAE;EAAQ;CAAK,CAAC;AAC7F;;;;;AAMA,SAAgB,yBAAyB,QAAsB,MAAoB;CACjF,MAAM,UAAU,eAAe;CAC/B,IAAI,CAAC,QAAQ,QAAQ,QAAQ,GAAG;CAChC,QAAQ,YAAY,UAAU,8CAA8C;EAAE;EAAQ;CAAK,CAAC;CAC5F,MAAM,MAAM,GAAG,OAAO,GAAG;CACzB,IAAI,CAAC,YAAY,IAAI,GAAG,GAAG,YAAY,IAAI,KAAK;EAAE;EAAQ;EAAM,IAAI,KAAK,IAAI;CAAE,CAAC;AAClF;;;;;AAMA,SAAgB,kBAAoC;CAClD,OAAO,EACL,QAAQ,MAAM;EACZ,MAAM,MAAM,KAAK,IAAI;EACrB,KAAK,MAAM,EAAE,QAAQ,MAAM,QAAQ,YAAY,OAAO,GACpD,KAAK,KAAK,2CAA2C,MAAM,IAAI;GAAE;GAAQ;EAAK,CAAC;CAEnF,EACF;AACF"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { MetricsContext } from '@mastra/core/observability';
|
|
2
|
+
import type { MetricGroup, MetricsService, ResolvedMetricsConfig } from './config.js';
|
|
3
|
+
export type MetricLabels = Record<string, string>;
|
|
4
|
+
/** The subset of the Mastra logger metrics write to. */
|
|
5
|
+
export interface MetricsLogger {
|
|
6
|
+
info(message: string, ...args: unknown[]): void;
|
|
7
|
+
warn(message: string, ...args: unknown[]): void;
|
|
8
|
+
}
|
|
9
|
+
/** Where collectors send their samples; capped per tick. */
|
|
10
|
+
export interface MetricSink {
|
|
11
|
+
emit(name: string, value: number, labels?: MetricLabels): void;
|
|
12
|
+
}
|
|
13
|
+
/** Sampled once per interval. */
|
|
14
|
+
export interface MetricsCollector {
|
|
15
|
+
collect(sink: MetricSink): Promise<void> | void;
|
|
16
|
+
/** Releases anything the collector holds (observers, histograms). */
|
|
17
|
+
stop?(): void;
|
|
18
|
+
}
|
|
19
|
+
export interface MetricsTargets {
|
|
20
|
+
/**
|
|
21
|
+
* The metrics context to send to. Read on every flush: Platform registers its exporter on the
|
|
22
|
+
* Mastra instance after the app module has loaded, replacing the no-op context.
|
|
23
|
+
*/
|
|
24
|
+
getMetrics: () => Pick<MetricsContext, 'emit'> | undefined;
|
|
25
|
+
getLogger: () => MetricsLogger | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Factory's metrics. Call sites check `enabled(group)` (or just call `count`/`observe`, which do
|
|
29
|
+
* nothing for a group that's off). Counts and timings are aggregated in-process and sent once per
|
|
30
|
+
* interval, so a burst of events costs one record per series, not one per event.
|
|
31
|
+
*/
|
|
32
|
+
export declare class FactoryMetrics {
|
|
33
|
+
#private;
|
|
34
|
+
constructor(config: ResolvedMetricsConfig | undefined, service: MetricsService);
|
|
35
|
+
get service(): MetricsService;
|
|
36
|
+
get intervalMs(): number;
|
|
37
|
+
enabled(group: MetricGroup): boolean;
|
|
38
|
+
/** Adds `value` to a counter, sent as one record per series per interval. */
|
|
39
|
+
count(group: MetricGroup, name: string, labels?: MetricLabels, value?: number): void;
|
|
40
|
+
/**
|
|
41
|
+
* Sends this counter series every interval, as 0 when nothing happened, so a quiet interval
|
|
42
|
+
* reads as zero instead of looking like the group is off. Keep it to a few series.
|
|
43
|
+
*/
|
|
44
|
+
keepCounter(group: MetricGroup, name: string, labels?: MetricLabels): void;
|
|
45
|
+
/** Records a timing, sent per interval as `stat=avg|p95|max` plus a `<name>_count` series. */
|
|
46
|
+
observe(group: MetricGroup, name: string, value: number, labels?: MetricLabels): void;
|
|
47
|
+
/** Starts the interval timer. Does nothing when every group is off. */
|
|
48
|
+
start(targets: MetricsTargets, collectors: MetricsCollector[]): void;
|
|
49
|
+
stop(): void;
|
|
50
|
+
/**
|
|
51
|
+
* Sends aggregated counters and timings, then samples the collectors. Skipped while the previous
|
|
52
|
+
* tick is still running, so a hung dependency never piles up probes. Exposed for tests.
|
|
53
|
+
*/
|
|
54
|
+
tick(): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
/** The process's Factory metrics. A no-op until a `MastraFactory` with metrics is constructed. */
|
|
57
|
+
export declare function factoryMetrics(): FactoryMetrics;
|
|
58
|
+
/** Replaces the process's Factory metrics, stopping the previous one. One Factory per process. */
|
|
59
|
+
export declare function installFactoryMetrics(metrics: FactoryMetrics): void;
|
|
60
|
+
//# sourceMappingURL=metrics.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../../src/metrics/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEtF,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAElD,wDAAwD;AACxD,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAChD,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;CACjD;AAED,4DAA4D;AAC5D,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;CAChE;AAED,iCAAiC;A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AkG;AAClG,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI,CAGnE"}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// src/metrics/metrics.ts
|
|
2
|
+
const MAX_SAMPLES = 1e3;
|
|
3
|
+
function seriesKey(name, labels) {
|
|
4
|
+
return `${name}\u0000${Object.keys(labels).sort().map((key) => `${key}=${labels[key]}`).join(",")}`;
|
|
5
|
+
}
|
|
6
|
+
function percentile(sorted, p) {
|
|
7
|
+
if (sorted.length === 0) return 0;
|
|
8
|
+
return sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Factory's metrics. Call sites check `enabled(group)` (or just call `count`/`observe`, which do
|
|
12
|
+
* nothing for a group that's off). Counts and timings are aggregated in-process and sent once per
|
|
13
|
+
* interval, so a burst of events costs one record per series, not one per event.
|
|
14
|
+
*/
|
|
15
|
+
var FactoryMetrics = class {
|
|
16
|
+
#config;
|
|
17
|
+
#service;
|
|
18
|
+
#counters = /* @__PURE__ */ new Map();
|
|
19
|
+
#observations = /* @__PURE__ */ new Map();
|
|
20
|
+
#collectors = [];
|
|
21
|
+
#targets;
|
|
22
|
+
#timer;
|
|
23
|
+
#running = false;
|
|
24
|
+
#credit;
|
|
25
|
+
constructor(config, service) {
|
|
26
|
+
this.#config = config;
|
|
27
|
+
this.#service = service;
|
|
28
|
+
}
|
|
29
|
+
get service() {
|
|
30
|
+
return this.#service;
|
|
31
|
+
}
|
|
32
|
+
get intervalMs() {
|
|
33
|
+
return this.#config?.intervalMs ?? 0;
|
|
34
|
+
}
|
|
35
|
+
enabled(group) {
|
|
36
|
+
return this.#config?.groups.has(group) ?? false;
|
|
37
|
+
}
|
|
38
|
+
/** Adds `value` to a counter, sent as one record per series per interval. */
|
|
39
|
+
count(group, name, labels = {}, value = 1) {
|
|
40
|
+
if (!this.enabled(group) || !Number.isFinite(value)) return;
|
|
41
|
+
const key = seriesKey(name, labels);
|
|
42
|
+
const counter = this.#counters.get(key);
|
|
43
|
+
if (counter) counter.value += value;
|
|
44
|
+
else this.#counters.set(key, {
|
|
45
|
+
name,
|
|
46
|
+
labels,
|
|
47
|
+
value
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Sends this counter series every interval, as 0 when nothing happened, so a quiet interval
|
|
52
|
+
* reads as zero instead of looking like the group is off. Keep it to a few series.
|
|
53
|
+
*/
|
|
54
|
+
keepCounter(group, name, labels = {}) {
|
|
55
|
+
if (!this.enabled(group)) return;
|
|
56
|
+
const key = seriesKey(name, labels);
|
|
57
|
+
const counter = this.#counters.get(key);
|
|
58
|
+
if (counter) counter.keep = true;
|
|
59
|
+
else this.#counters.set(key, {
|
|
60
|
+
name,
|
|
61
|
+
labels,
|
|
62
|
+
value: 0,
|
|
63
|
+
keep: true
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Records a timing, sent per interval as `stat=avg|p95|max` plus a `<name>_count` series. */
|
|
67
|
+
observe(group, name, value, labels = {}) {
|
|
68
|
+
if (!this.enabled(group) || !Number.isFinite(value)) return;
|
|
69
|
+
const key = seriesKey(name, labels);
|
|
70
|
+
let observation = this.#observations.get(key);
|
|
71
|
+
if (!observation) {
|
|
72
|
+
observation = {
|
|
73
|
+
name,
|
|
74
|
+
labels,
|
|
75
|
+
count: 0,
|
|
76
|
+
sum: 0,
|
|
77
|
+
max: -Infinity,
|
|
78
|
+
samples: []
|
|
79
|
+
};
|
|
80
|
+
this.#observations.set(key, observation);
|
|
81
|
+
}
|
|
82
|
+
observation.count++;
|
|
83
|
+
observation.sum += value;
|
|
84
|
+
observation.max = Math.max(observation.max, value);
|
|
85
|
+
if (observation.samples.length < MAX_SAMPLES) observation.samples.push(value);
|
|
86
|
+
else {
|
|
87
|
+
const slot = Math.floor(Math.random() * observation.count);
|
|
88
|
+
if (slot < MAX_SAMPLES) observation.samples[slot] = value;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Starts the interval timer. Does nothing when every group is off. */
|
|
92
|
+
start(targets, collectors) {
|
|
93
|
+
if (!this.#config || this.#timer) return;
|
|
94
|
+
this.#targets = targets;
|
|
95
|
+
this.#collectors = collectors;
|
|
96
|
+
for (const name of this.#config.unknownGroups) targets.getLogger()?.warn(`[factory:metrics] Unknown metric group "${name}" ignored.`);
|
|
97
|
+
this.#timer = setInterval(() => {
|
|
98
|
+
this.tick().catch((error) => this.#targets?.getLogger()?.warn("[factory:metrics] Metrics tick failed.", { error: String(error) }));
|
|
99
|
+
}, this.#config.intervalMs);
|
|
100
|
+
this.#timer.unref?.();
|
|
101
|
+
}
|
|
102
|
+
stop() {
|
|
103
|
+
if (this.#timer) clearInterval(this.#timer);
|
|
104
|
+
this.#timer = void 0;
|
|
105
|
+
for (const collector of this.#collectors) collector.stop?.();
|
|
106
|
+
this.#collectors = [];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Sends aggregated counters and timings, then samples the collectors. Skipped while the previous
|
|
110
|
+
* tick is still running, so a hung dependency never piles up probes. Exposed for tests.
|
|
111
|
+
*/
|
|
112
|
+
async tick() {
|
|
113
|
+
if (!this.#config || this.#running) return;
|
|
114
|
+
this.#running = true;
|
|
115
|
+
try {
|
|
116
|
+
const metrics = this.#targets?.getMetrics();
|
|
117
|
+
const perTick = this.#config.maxPerMinute * this.#config.intervalMs / 6e4;
|
|
118
|
+
const available = Math.floor(this.#credit = Math.min((this.#credit ?? 0) + perTick, Math.max(perTick, 1)));
|
|
119
|
+
const budget = available > 1 ? available - 1 : available;
|
|
120
|
+
let used = 0;
|
|
121
|
+
let dropped = 0;
|
|
122
|
+
const service = this.#service;
|
|
123
|
+
const sink = { emit(name, value, labels) {
|
|
124
|
+
if (!Number.isFinite(value)) return;
|
|
125
|
+
if (used >= budget) {
|
|
126
|
+
dropped++;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
used++;
|
|
130
|
+
metrics?.emit(name, value, {
|
|
131
|
+
...labels,
|
|
132
|
+
service
|
|
133
|
+
});
|
|
134
|
+
} };
|
|
135
|
+
for (const [key, counter] of this.#counters) {
|
|
136
|
+
sink.emit(counter.name, counter.value, counter.labels);
|
|
137
|
+
if (counter.keep) counter.value = 0;
|
|
138
|
+
else this.#counters.delete(key);
|
|
139
|
+
}
|
|
140
|
+
for (const observation of this.#observations.values()) {
|
|
141
|
+
const { name, labels, count, sum, max } = observation;
|
|
142
|
+
const sorted = observation.samples.sort((a, b) => a - b);
|
|
143
|
+
sink.emit(`${name}_count`, count, labels);
|
|
144
|
+
sink.emit(name, sum / count, {
|
|
145
|
+
...labels,
|
|
146
|
+
stat: "avg"
|
|
147
|
+
});
|
|
148
|
+
sink.emit(name, percentile(sorted, .95), {
|
|
149
|
+
...labels,
|
|
150
|
+
stat: "p95"
|
|
151
|
+
});
|
|
152
|
+
sink.emit(name, max, {
|
|
153
|
+
...labels,
|
|
154
|
+
stat: "max"
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
this.#observations.clear();
|
|
158
|
+
const results = await Promise.allSettled(this.#collectors.map((collector) => Promise.resolve().then(() => collector.collect(sink))));
|
|
159
|
+
for (const result of results) if (result.status === "rejected") this.#targets?.getLogger()?.warn("[factory:metrics] Collector failed.", { error: String(result.reason) });
|
|
160
|
+
if (dropped > 0 && used < available) {
|
|
161
|
+
used++;
|
|
162
|
+
metrics?.emit("mastra_factory_metrics_dropped_total", dropped, { service });
|
|
163
|
+
}
|
|
164
|
+
this.#credit -= used;
|
|
165
|
+
} finally {
|
|
166
|
+
this.#running = false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
let current = new FactoryMetrics(void 0, "all");
|
|
171
|
+
/** The process's Factory metrics. A no-op until a `MastraFactory` with metrics is constructed. */
|
|
172
|
+
function factoryMetrics() {
|
|
173
|
+
return current;
|
|
174
|
+
}
|
|
175
|
+
/** Replaces the process's Factory metrics, stopping the previous one. One Factory per process. */
|
|
176
|
+
function installFactoryMetrics(metrics) {
|
|
177
|
+
current.stop();
|
|
178
|
+
current = metrics;
|
|
179
|
+
}
|
|
180
|
+
export { FactoryMetrics, factoryMetrics, installFactoryMetrics };
|
|
181
|
+
|
|
182
|
+
//# sourceMappingURL=metrics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metrics.js","names":[],"sources":["../../src/metrics/metrics.ts"],"sourcesContent":["import type { MetricsContext } from '@mastra/core/observability';\n\nimport type { MetricGroup, MetricsService, ResolvedMetricsConfig } from './config.js';\n\nexport type MetricLabels = Record<string, string>;\n\n/** The subset of the Mastra logger metrics write to. */\nexport interface MetricsLogger {\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n}\n\n/** Where collectors send their samples; capped per tick. */\nexport interface MetricSink {\n emit(name: string, value: number, labels?: MetricLabels): void;\n}\n\n/** Sampled once per interval. */\nexport interface MetricsCollector {\n collect(sink: MetricSink): Promise<void> | void;\n /** Releases anything the collector holds (observers, histograms). */\n stop?(): void;\n}\n\nexport interface MetricsTargets {\n /**\n * The metrics context to send to. Read on every flush: Platform registers its exporter on the\n * Mastra instance after the app module has loaded, replacing the no-op context.\n */\n getMetrics: () => Pick<MetricsContext, 'emit'> | undefined;\n getLogger: () => MetricsLogger | undefined;\n}\n\n// Observations kept per series per interval for the p95; count, sum and max stay exact past it.\nconst MAX_SAMPLES = 1_000;\n\ninterface Observation {\n name: string;\n labels: MetricLabels;\n count: number;\n sum: number;\n max: number;\n samples: number[];\n}\n\ninterface Counter {\n name: string;\n labels: MetricLabels;\n value: number;\n /** Sent as 0 on intervals with no events, instead of being left out. */\n keep?: boolean;\n}\n\nfunction seriesKey(name: string, labels: MetricLabels): string {\n return `${name}\\u0000${Object.keys(labels)\n .sort()\n .map(key => `${key}=${labels[key]}`)\n .join(',')}`;\n}\n\nfunction percentile(sorted: number[], p: number): number {\n if (sorted.length === 0) return 0;\n return sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)]!;\n}\n\n/**\n * Factory's metrics. Call sites check `enabled(group)` (or just call `count`/`observe`, which do\n * nothing for a group that's off). Counts and timings are aggregated in-process and sent once per\n * interval, so a burst of events costs one record per series, not one per event.\n */\nexport class FactoryMetrics {\n readonly #config: ResolvedMetricsConfig | undefined;\n readonly #service: MetricsService;\n readonly #counters = new Map<string, Counter>();\n readonly #observations = new Map<string, Observation>();\n #collectors: MetricsCollector[] = [];\n #targets: MetricsTargets | undefined;\n #timer: ReturnType<typeof setInterval> | undefined;\n #running = false;\n // Records this process may still send. Refilled each tick by the interval's share of the\n // per-minute cap, so a cap below one record per tick still holds over a minute.\n #credit: number | undefined;\n\n constructor(config: ResolvedMetricsConfig | undefined, service: MetricsService) {\n this.#config = config;\n this.#service = service;\n }\n\n get service(): MetricsService {\n return this.#service;\n }\n\n get intervalMs(): number {\n return this.#config?.intervalMs ?? 0;\n }\n\n enabled(group: MetricGroup): boolean {\n return this.#config?.groups.has(group) ?? false;\n }\n\n /** Adds `value` to a counter, sent as one record per series per interval. */\n count(group: MetricGroup, name: string, labels: MetricLabels = {}, value = 1): void {\n if (!this.enabled(group) || !Number.isFinite(value)) return;\n const key = seriesKey(name, labels);\n const counter = this.#counters.get(key);\n if (counter) counter.value += value;\n else this.#counters.set(key, { name, labels, value });\n }\n\n /**\n * Sends this counter series every interval, as 0 when nothing happened, so a quiet interval\n * reads as zero instead of looking like the group is off. Keep it to a few series.\n */\n keepCounter(group: MetricGroup, name: string, labels: MetricLabels = {}): void {\n if (!this.enabled(group)) return;\n const key = seriesKey(name, labels);\n const counter = this.#counters.get(key);\n if (counter) counter.keep = true;\n else this.#counters.set(key, { name, labels, value: 0, keep: true });\n }\n\n /** Records a timing, sent per interval as `stat=avg|p95|max` plus a `<name>_count` series. */\n observe(group: MetricGroup, name: string, value: number, labels: MetricLabels = {}): void {\n if (!this.enabled(group) || !Number.isFinite(value)) return;\n const key = seriesKey(name, labels);\n let observation = this.#observations.get(key);\n if (!observation) {\n observation = { name, labels, count: 0, sum: 0, max: -Infinity, samples: [] };\n this.#observations.set(key, observation);\n }\n observation.count++;\n observation.sum += value;\n observation.max = Math.max(observation.max, value);\n // Reservoir sampling: every observation in the interval has the same chance of being kept,\n // so a p95 over a busy interval still reflects its last minutes.\n if (observation.samples.length < MAX_SAMPLES) observation.samples.push(value);\n else {\n const slot = Math.floor(Math.random() * observation.count);\n if (slot < MAX_SAMPLES) observation.samples[slot] = value;\n }\n }\n\n /** Starts the interval timer. Does nothing when every group is off. */\n start(targets: MetricsTargets, collectors: MetricsCollector[]): void {\n if (!this.#config || this.#timer) return;\n this.#targets = targets;\n this.#collectors = collectors;\n for (const name of this.#config.unknownGroups) {\n targets.getLogger()?.warn(`[factory:metrics] Unknown metric group \"${name}\" ignored.`);\n }\n this.#timer = setInterval(() => {\n this.tick().catch(error =>\n this.#targets?.getLogger()?.warn('[factory:metrics] Metrics tick failed.', { error: String(error) }),\n );\n }, this.#config.intervalMs);\n this.#timer.unref?.();\n }\n\n stop(): void {\n if (this.#timer) clearInterval(this.#timer);\n this.#timer = undefined;\n for (const collector of this.#collectors) collector.stop?.();\n this.#collectors = [];\n }\n\n /**\n * Sends aggregated counters and timings, then samples the collectors. Skipped while the previous\n * tick is still running, so a hung dependency never piles up probes. Exposed for tests.\n */\n async tick(): Promise<void> {\n if (!this.#config || this.#running) return;\n this.#running = true;\n try {\n const metrics = this.#targets?.getMetrics();\n const perTick = (this.#config.maxPerMinute * this.#config.intervalMs) / 60_000;\n const available = Math.floor((this.#credit = Math.min((this.#credit ?? 0) + perTick, Math.max(perTick, 1))));\n // One record is held back for the dropped-records count, so the cap includes it.\n const budget = available > 1 ? available - 1 : available;\n let used = 0;\n let dropped = 0;\n const service = this.#service;\n const sink: MetricSink = {\n emit(name, value, labels) {\n if (!Number.isFinite(value)) return;\n if (used >= budget) {\n dropped++;\n return;\n }\n used++;\n metrics?.emit(name, value, { ...labels, service });\n },\n };\n\n // Event counts and timings go first: they are lost if dropped, while gauges are sampled again next tick.\n for (const [key, counter] of this.#counters) {\n sink.emit(counter.name, counter.value, counter.labels);\n if (counter.keep) counter.value = 0;\n else this.#counters.delete(key);\n }\n for (const observation of this.#observations.values()) {\n const { name, labels, count, sum, max } = observation;\n const sorted = observation.samples.sort((a, b) => a - b);\n sink.emit(`${name}_count`, count, labels);\n sink.emit(name, sum / count, { ...labels, stat: 'avg' });\n sink.emit(name, percentile(sorted, 0.95), { ...labels, stat: 'p95' });\n sink.emit(name, max, { ...labels, stat: 'max' });\n }\n this.#observations.clear();\n\n // A collector that throws synchronously becomes a rejection here, so it never orphans the others.\n const results = await Promise.allSettled(\n this.#collectors.map(collector => Promise.resolve().then(() => collector.collect(sink))),\n );\n for (const result of results) {\n if (result.status === 'rejected') {\n this.#targets?.getLogger()?.warn('[factory:metrics] Collector failed.', { error: String(result.reason) });\n }\n }\n\n // Sent from the held-back record, so a capped deployment can see it is capped.\n if (dropped > 0 && used < available) {\n used++;\n metrics?.emit('mastra_factory_metrics_dropped_total', dropped, { service });\n }\n this.#credit -= used;\n } finally {\n this.#running = false;\n }\n }\n}\n\nlet current = new FactoryMetrics(undefined, 'all');\n\n/** The process's Factory metrics. A no-op until a `MastraFactory` with metrics is constructed. */\nexport function factoryMetrics(): FactoryMetrics {\n return current;\n}\n\n/** Replaces the process's Factory metrics, stopping the previous one. One Factory per process. */\nexport function installFactoryMetrics(metrics: FactoryMetrics): void {\n current.stop();\n current = metrics;\n}\n"],"mappings":";AAkCA,MAAM,cAAc;AAmBpB,SAAS,UAAU,MAAc,QAA8B;CAC7D,OAAO,GAAG,KAAK,QAAQ,OAAO,KAAK,MAAM,CAAC,CACvC,KAAK,CAAC,CACN,KAAI,QAAO,GAAG,IAAI,GAAG,OAAO,MAAM,CAAC,CACnC,KAAK,GAAG;AACb;AAEA,SAAS,WAAW,QAAkB,GAAmB;CACvD,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,OAAO,OAAO,KAA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,IAAI,OAAO,WAAW,YACpB,KAAK,UAAU,UAAU,CAAC,EAAE,KAAK,uCAAuC,EAAE,OAAO,OAAO,OAAO,MAAM,EAAE,CAAC;GAK5G,IAAI,UAAU,KAAK,OAAO,WAAW;IACnC;IACA,SAAS,KAAK,wCAAwC,SAAS,EAAE,QAAQ,CAAC;GAC5E;GACA,KAAK,WAAW;EAClB,UAAU;GACR,KAAK,WAAW;EAClB;CACF;AACF;AAEA,IAAI,UAAU,IAAI,eAAe,KAAA,GAAW,KAAK;;AAGjD,SAAgB,iBAAiC;CAC/C,OAAO;AACT;;AAGA,SAAgB,sBAAsB,SAA+B;CACnE,QAAQ,KAAK;CACb,UAAU;AACZ"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { MetricsCollector } from './metrics.js';
|
|
2
|
+
/**
|
|
3
|
+
* Maps a `timedPhase` name to the `phase` label. Only session workspace phases count; boot
|
|
4
|
+
* phases (`prepare.*`, `background.*`) don't. The `(…)` argument names a repository or an outcome
|
|
5
|
+
* and is never sent: repository names are unbounded.
|
|
6
|
+
*/
|
|
7
|
+
export declare function workspacePhaseLabel(phase: string): string | undefined;
|
|
8
|
+
/** Maps a sandbox command `phase` (e.g. `repository clone`, `environment branch fetch`) to the `step` label. */
|
|
9
|
+
export declare function commandStepLabel(phase: string): string;
|
|
10
|
+
/** `timedPhase` hook: records a workspace phase duration. */
|
|
11
|
+
export declare function recordWorkspacePhase(phase: string, ms: number, ok: boolean): void;
|
|
12
|
+
/** Records one attempt of a sandbox command run during workspace setup. */
|
|
13
|
+
export declare function recordSandboxCommand(phase: string, ms: number, outcome: 'ok' | 'exit' | 'threw'): void;
|
|
14
|
+
/** Marks the next start of `sandbox` as the eager start fired when the workspace resolves. */
|
|
15
|
+
export declare function markEagerSandboxStart(sandbox: object): void;
|
|
16
|
+
/**
|
|
17
|
+
* Times every real start of `sandbox`:
|
|
18
|
+
* - the provider's part (lease and boot, up to the onStart hook), so a slow or failing provider is
|
|
19
|
+
* told apart from slow or failing repository setup;
|
|
20
|
+
* - the whole start, up to the end of the onStart hook (`mastra_factory_session_ready_ms`), with
|
|
21
|
+
* failures included. `kind` is `first` for a session's first sandbox and `resume` for later starts;
|
|
22
|
+
* - how long the first caller other than the eager start waited for it
|
|
23
|
+
* (`mastra_factory_session_sandbox_wait_ms`): the start-up time someone actually waits through.
|
|
24
|
+
* Patches `_start` in place: `start()`, `ensureRunning()` and the lazy start before the first command
|
|
25
|
+
* all go through it. `hadSandbox` says whether the session already had a sandbox before this instance.
|
|
26
|
+
*/
|
|
27
|
+
export declare function instrumentSandboxStart(sandbox: object, provider: string, hadSandbox: boolean): void;
|
|
28
|
+
/** Called as the sandbox's onStart hook begins: the provider has handed over a running VM. */
|
|
29
|
+
export declare function recordSandboxAcquired(sandbox: object, outcome: string | undefined): void;
|
|
30
|
+
/**
|
|
31
|
+
* Starts in flight and the age of the oldest, sent every interval (0 when none), so a start that hangs
|
|
32
|
+
* shows while it's happening instead of only when it ends. Also shows the group is on while idle.
|
|
33
|
+
*/
|
|
34
|
+
export declare function sessionStartsCollector(): MetricsCollector;
|
|
35
|
+
//# sourceMappingURL=sandbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../src/metrics/sandbox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAYrD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGrE;AAED,gHAAgH;AAChH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOtD;AAED,6DAA6D;AAC7D,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,OAAO,GAAG,IAAI,CAMjF;AAED,2EAA2E;AAC3E,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAKtG;AA6BD,8FAA8F;AAC9F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAE3D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,GAAG,IAAI,CAiEnG;AAED,8FAA8F;AAC9F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAQxF;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,gBAAgB,CAUzD"}
|