@osfactory/otel-hook 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +108 -4
- package/dist/{adapter-B9RwW6TO.d.ts → adapter-DQiPu8xF.d.ts} +2 -2
- package/dist/cli.js +1495 -135
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +11 -4
- package/dist/config.js +116 -21
- package/dist/config.js.map +1 -1
- package/dist/{destinations-DWOkVxV1.d.ts → destinations-DvqsPulb.d.ts} +12 -2
- package/dist/diagnostics.d.ts +1 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/{events-CSD_YiJ2.d.ts → events-fcomX6d5.d.ts} +22 -0
- package/dist/{export-destinations-lORbe25J.d.ts → export-destinations-CI7z4n3i.d.ts} +136 -6
- package/dist/{filesystem-store-DX3dGIgu.d.ts → filesystem-store-CmnUlj1O.d.ts} +1 -1
- package/dist/{hook-BAxXoKsp.d.ts → hook-vM_cgqS2.d.ts} +11 -5
- package/dist/index.d.ts +16 -16
- package/dist/index.js +1496 -183
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +4 -4
- package/dist/install.js +9 -1
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +36 -12
- package/dist/integration.js +1464 -231
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +55 -4
- package/dist/lifecycle.js +279 -5
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-aJilVG4R.d.ts → memory-DdU1U91y.d.ts} +2 -2
- package/dist/{semconv-Dw7gcQcg.d.ts → metric-model-C9lLqqpI.d.ts} +157 -2
- package/dist/model.d.ts +1 -1
- package/dist/model.js +9 -1
- package/dist/model.js.map +1 -1
- package/dist/{payload-D7gc0-WQ.d.ts → payload-BT19hiVZ.d.ts} +1 -1
- package/dist/{ports-plO5MKrY.d.ts → ports-C3k_5eOQ.d.ts} +57 -2
- package/dist/providers.d.ts +10 -10
- package/dist/providers.js +10 -1
- package/dist/providers.js.map +1 -1
- package/dist/{registry-C7XO4DzD.d.ts → registry-gyJqaWmp.d.ts} +2 -2
- package/dist/runtime.d.ts +97 -9
- package/dist/runtime.js +312 -33
- package/dist/runtime.js.map +1 -1
- package/dist/{schema-CHb3GU1r.d.ts → schema-SpFM6YQY.d.ts} +87 -1
- package/dist/state.d.ts +4 -4
- package/dist/state.js +32 -1
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +6 -6
- package/dist/telemetry.js +929 -31
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +11 -9
- package/dist/testing.js +164 -33
- package/dist/testing.js.map +1 -1
- package/package.json +3 -1
package/dist/lifecycle.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { j as StateStore, C as Clock } from './ports-C3k_5eOQ.js';
|
|
2
2
|
import { Attributes } from '@opentelemetry/api';
|
|
3
|
-
import { b as CanonicalEvent, f as CanonicalUsage } from './events-
|
|
4
|
-
import {
|
|
3
|
+
import { b as CanonicalEvent, f as CanonicalUsage } from './events-fcomX6d5.js';
|
|
4
|
+
import { p as SpanFamily, s as SpanScopeRef, m as SpanCorrelation, j as MetricObservation, k as MetricPoint } from './metric-model-C9lLqqpI.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import './errors.js';
|
|
7
7
|
import './primitives-CJ8-rn-f.js';
|
|
@@ -372,10 +372,60 @@ type UsageAccumulatorDependencies = {
|
|
|
372
372
|
};
|
|
373
373
|
declare const createUsageAccumulator: (deps: UsageAccumulatorDependencies) => UsageAccumulator;
|
|
374
374
|
|
|
375
|
+
/**
|
|
376
|
+
* Cumulative metric series kept across hook processes (issue #69).
|
|
377
|
+
*
|
|
378
|
+
* A hook process lives for one callback, so an in-process `MeterProvider` would
|
|
379
|
+
* only ever see one observation and restart every series at zero. Cumulative
|
|
380
|
+
* temporality — what receivers that merge counters by keeping the largest value
|
|
381
|
+
* need — therefore requires the running total to outlive the process. Each series
|
|
382
|
+
* is one state record: read, fold the batch's observations in, write back, and
|
|
383
|
+
* export the new total as a point whose interval starts at the series' first
|
|
384
|
+
* observation.
|
|
385
|
+
*
|
|
386
|
+
* Folding is idempotent per delivery: the record names the last delivery folded
|
|
387
|
+
* into it, so a callback replayed after a crash between "recorded" and "committed"
|
|
388
|
+
* restates the total instead of adding to it.
|
|
389
|
+
*
|
|
390
|
+
* Concurrency: the read-fold-write runs under the session lock of the series'
|
|
391
|
+
* scope (the provider session, or one shared lock for series that span sessions),
|
|
392
|
+
* the same lock usage accounting uses, so two concurrent processes cannot both add
|
|
393
|
+
* to the same stale total.
|
|
394
|
+
*/
|
|
395
|
+
type MetricSeriesStoreDependencies = {
|
|
396
|
+
readonly stateStore: StateStore;
|
|
397
|
+
readonly clock: Clock;
|
|
398
|
+
};
|
|
399
|
+
type RecordCumulativeOptions = {
|
|
400
|
+
/** Opaque digest of the delivery these observations came from. */
|
|
401
|
+
readonly deliveryToken?: string;
|
|
402
|
+
/** Whether series are per session (`session.id` on the points). Default true. */
|
|
403
|
+
readonly perSession?: boolean;
|
|
404
|
+
};
|
|
405
|
+
type MetricSeriesCleanupResult = {
|
|
406
|
+
readonly removed: number;
|
|
407
|
+
readonly scanned: number;
|
|
408
|
+
};
|
|
409
|
+
interface MetricSeriesStore {
|
|
410
|
+
/** Fold observations into their series; returns one cumulative point per touched series. */
|
|
411
|
+
recordCumulative(observations: readonly MetricObservation[], options?: RecordCumulativeOptions): Promise<readonly MetricPoint[]>;
|
|
412
|
+
/** Remember when the session's current turn began (its last prompt). */
|
|
413
|
+
recordTurnStart(sessionId: string, startMillis: number): Promise<void>;
|
|
414
|
+
/** When the session's current turn began, if a prompt was recorded. */
|
|
415
|
+
readTurnStart(sessionId: string): Promise<number | undefined>;
|
|
416
|
+
cleanup(maxAgeMillis: number, options?: {
|
|
417
|
+
readonly maxEntries?: number;
|
|
418
|
+
readonly sessionId?: string;
|
|
419
|
+
}): Promise<MetricSeriesCleanupResult>;
|
|
420
|
+
}
|
|
421
|
+
declare const createMetricSeriesStore: (deps: MetricSeriesStoreDependencies) => MetricSeriesStore;
|
|
422
|
+
|
|
375
423
|
type LifecycleJanitorOptions = {
|
|
376
424
|
readonly spanCorrelator?: SpanCorrelator;
|
|
377
425
|
readonly deduplicator?: CallbackDeduplicator;
|
|
378
426
|
readonly usageAccumulator?: UsageAccumulator;
|
|
427
|
+
/** Cumulative metric series state; swept by age, like usage rollups. */
|
|
428
|
+
readonly metricSeries?: MetricSeriesStore;
|
|
379
429
|
readonly spanMaxAgeMillis?: number;
|
|
380
430
|
readonly dedupMaxAgeMillis?: number;
|
|
381
431
|
/**
|
|
@@ -410,6 +460,7 @@ type LifecycleCleanupReport = {
|
|
|
410
460
|
readonly span?: LifecycleSweepStats;
|
|
411
461
|
readonly dedup?: LifecycleSweepStats;
|
|
412
462
|
readonly usage?: LifecycleSweepStats;
|
|
463
|
+
readonly metrics?: LifecycleSweepStats;
|
|
413
464
|
};
|
|
414
465
|
/**
|
|
415
466
|
* Fans a single bounded cleanup pass out across whichever lifecycle
|
|
@@ -425,4 +476,4 @@ interface LifecycleJanitor {
|
|
|
425
476
|
}
|
|
426
477
|
declare const createLifecycleJanitor: (options: LifecycleJanitorOptions) => LifecycleJanitor;
|
|
427
478
|
|
|
428
|
-
export { type CallbackDeduplicator, type CallbackDeduplicatorDependencies, type DedupCheckResult, type DedupCleanupResult, type DeliveryClaimOptions, type DeliveryClaimOutcome, type DeliveryClaimResult, type LifecycleCleanupReport, type LifecycleJanitor, type LifecycleJanitorOptions, type LifecycleScope, type LifecycleSweepStats, type RollupCleanupResult, SPAN_RECORD_VERSION, type SpanCleanupResult, type SpanCorrelationFacts, type SpanCorrelator, type SpanCorrelatorDependencies, type SpanEndInput, type SpanEndOrphanReason, type SpanEndResult, type SpanStartInput, type SpanStartResult, type UsageAccumulator, type UsageAccumulatorDependencies, type UsageAccumulatorKey, type UsageAccumulatorSnapshot, createCallbackDeduplicator, createLifecycleJanitor, createSpanCorrelator, createUsageAccumulator };
|
|
479
|
+
export { type CallbackDeduplicator, type CallbackDeduplicatorDependencies, type DedupCheckResult, type DedupCleanupResult, type DeliveryClaimOptions, type DeliveryClaimOutcome, type DeliveryClaimResult, type LifecycleCleanupReport, type LifecycleJanitor, type LifecycleJanitorOptions, type LifecycleScope, type LifecycleSweepStats, type MetricSeriesCleanupResult, type MetricSeriesStore, type MetricSeriesStoreDependencies, type RecordCumulativeOptions, type RollupCleanupResult, SPAN_RECORD_VERSION, type SpanCleanupResult, type SpanCorrelationFacts, type SpanCorrelator, type SpanCorrelatorDependencies, type SpanEndInput, type SpanEndOrphanReason, type SpanEndResult, type SpanStartInput, type SpanStartResult, type UsageAccumulator, type UsageAccumulatorDependencies, type UsageAccumulatorKey, type UsageAccumulatorSnapshot, createCallbackDeduplicator, createLifecycleJanitor, createMetricSeriesStore, createSpanCorrelator, createUsageAccumulator };
|
package/dist/lifecycle.js
CHANGED
|
@@ -33,6 +33,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
|
|
|
33
33
|
var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
|
|
34
34
|
var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
|
|
35
35
|
var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
|
|
36
|
+
var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
|
|
37
|
+
var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
|
|
36
38
|
|
|
37
39
|
// src/lifecycle/dedup.ts
|
|
38
40
|
var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
|
|
@@ -269,7 +271,7 @@ import {
|
|
|
269
271
|
} from "@opentelemetry/semantic-conventions/incubating";
|
|
270
272
|
|
|
271
273
|
// src/version.ts
|
|
272
|
-
var VERSION = "0.
|
|
274
|
+
var VERSION = "0.12.0";
|
|
273
275
|
|
|
274
276
|
// src/telemetry/export-identity.ts
|
|
275
277
|
import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
|
|
@@ -864,7 +866,15 @@ var baseEventFields = {
|
|
|
864
866
|
* factory, never by hand.
|
|
865
867
|
*/
|
|
866
868
|
subagentId: subagentIdSchema.optional(),
|
|
867
|
-
extensions: extensionsSchema.default(emptyExtensions)
|
|
869
|
+
extensions: extensionsSchema.default(emptyExtensions),
|
|
870
|
+
/**
|
|
871
|
+
* Attributes of the session context segment in force when the event
|
|
872
|
+
* occurred (`docs/session-context.md`), stamped by the core from a file a
|
|
873
|
+
* harness wrote. Exported on every record of the event, over the same keys
|
|
874
|
+
* from the Resource. Absent when no context applies. Set by the core only,
|
|
875
|
+
* never by an adapter.
|
|
876
|
+
*/
|
|
877
|
+
contextAttributes: z9.record(z9.string().min(1).max(255), z9.union([z9.string(), z9.number(), z9.boolean()])).optional()
|
|
868
878
|
};
|
|
869
879
|
var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
|
|
870
880
|
var sessionStartEventSchema = event({
|
|
@@ -1626,6 +1636,267 @@ var createUsageAccumulator = (deps) => {
|
|
|
1626
1636
|
return { accumulateDelta, recordReset, read, cleanup };
|
|
1627
1637
|
};
|
|
1628
1638
|
|
|
1639
|
+
// src/lifecycle/metric-series.ts
|
|
1640
|
+
import { createHash as createHash2 } from "crypto";
|
|
1641
|
+
|
|
1642
|
+
// src/telemetry/metric-model.ts
|
|
1643
|
+
var TOKEN_USAGE_BUCKETS = Object.freeze([
|
|
1644
|
+
1,
|
|
1645
|
+
4,
|
|
1646
|
+
16,
|
|
1647
|
+
64,
|
|
1648
|
+
256,
|
|
1649
|
+
1024,
|
|
1650
|
+
4096,
|
|
1651
|
+
16384,
|
|
1652
|
+
65536,
|
|
1653
|
+
262144,
|
|
1654
|
+
1048576,
|
|
1655
|
+
4194304,
|
|
1656
|
+
16777216,
|
|
1657
|
+
67108864
|
|
1658
|
+
]);
|
|
1659
|
+
var OPERATION_DURATION_BUCKETS = Object.freeze([
|
|
1660
|
+
0.01,
|
|
1661
|
+
0.02,
|
|
1662
|
+
0.04,
|
|
1663
|
+
0.08,
|
|
1664
|
+
0.16,
|
|
1665
|
+
0.32,
|
|
1666
|
+
0.64,
|
|
1667
|
+
1.28,
|
|
1668
|
+
2.56,
|
|
1669
|
+
5.12,
|
|
1670
|
+
10.24,
|
|
1671
|
+
20.48,
|
|
1672
|
+
40.96,
|
|
1673
|
+
81.92
|
|
1674
|
+
]);
|
|
1675
|
+
var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
|
|
1676
|
+
var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
|
|
1677
|
+
var METRIC_SESSIONS = "otelhook.sessions";
|
|
1678
|
+
var METRIC_TOOL_CALLS = "otelhook.tool.calls";
|
|
1679
|
+
var METRIC_COST_USAGE = "otelhook.cost.usage";
|
|
1680
|
+
var METRIC_INSTRUMENTS = Object.freeze({
|
|
1681
|
+
[METRIC_TOKEN_USAGE]: {
|
|
1682
|
+
name: METRIC_TOKEN_USAGE,
|
|
1683
|
+
kind: "histogram",
|
|
1684
|
+
unit: "{token}",
|
|
1685
|
+
description: "Tokens used per generation, by token type (hook-derived)",
|
|
1686
|
+
valueType: "int",
|
|
1687
|
+
boundaries: TOKEN_USAGE_BUCKETS
|
|
1688
|
+
},
|
|
1689
|
+
[METRIC_OPERATION_DURATION]: {
|
|
1690
|
+
name: METRIC_OPERATION_DURATION,
|
|
1691
|
+
kind: "histogram",
|
|
1692
|
+
unit: "s",
|
|
1693
|
+
description: "Generation duration, from its start hook to its end hook (hook-derived)",
|
|
1694
|
+
valueType: "double",
|
|
1695
|
+
boundaries: OPERATION_DURATION_BUCKETS
|
|
1696
|
+
},
|
|
1697
|
+
[METRIC_SESSIONS]: {
|
|
1698
|
+
name: METRIC_SESSIONS,
|
|
1699
|
+
kind: "counter",
|
|
1700
|
+
unit: "{session}",
|
|
1701
|
+
description: "Agent sessions started",
|
|
1702
|
+
valueType: "int"
|
|
1703
|
+
},
|
|
1704
|
+
[METRIC_TOOL_CALLS]: {
|
|
1705
|
+
name: METRIC_TOOL_CALLS,
|
|
1706
|
+
kind: "counter",
|
|
1707
|
+
unit: "{call}",
|
|
1708
|
+
description: "Completed tool calls, by tool name and outcome",
|
|
1709
|
+
valueType: "int"
|
|
1710
|
+
},
|
|
1711
|
+
[METRIC_COST_USAGE]: {
|
|
1712
|
+
name: METRIC_COST_USAGE,
|
|
1713
|
+
kind: "counter",
|
|
1714
|
+
unit: "USD",
|
|
1715
|
+
description: "Cost reported by the provider; never estimated",
|
|
1716
|
+
valueType: "double"
|
|
1717
|
+
}
|
|
1718
|
+
});
|
|
1719
|
+
var emptyHistogram = (boundaries) => ({
|
|
1720
|
+
count: 0,
|
|
1721
|
+
sum: 0,
|
|
1722
|
+
min: Number.POSITIVE_INFINITY,
|
|
1723
|
+
max: Number.NEGATIVE_INFINITY,
|
|
1724
|
+
bucketCounts: new Array(boundaries.length + 1).fill(0)
|
|
1725
|
+
});
|
|
1726
|
+
var bucketIndex = (boundaries, value) => {
|
|
1727
|
+
for (let index = 0; index < boundaries.length; index += 1) {
|
|
1728
|
+
const bound = boundaries[index];
|
|
1729
|
+
if (bound !== void 0 && value <= bound) {
|
|
1730
|
+
return index;
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
return boundaries.length;
|
|
1734
|
+
};
|
|
1735
|
+
var recordIntoHistogram = (state, boundaries, value) => {
|
|
1736
|
+
const bucketCounts = [...state.bucketCounts];
|
|
1737
|
+
const index = bucketIndex(boundaries, value);
|
|
1738
|
+
bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
|
|
1739
|
+
return {
|
|
1740
|
+
count: state.count + 1,
|
|
1741
|
+
sum: state.sum + value,
|
|
1742
|
+
min: Math.min(state.min, value),
|
|
1743
|
+
max: Math.max(state.max, value),
|
|
1744
|
+
bucketCounts
|
|
1745
|
+
};
|
|
1746
|
+
};
|
|
1747
|
+
var seriesIdentity = (instrument, attributes) => JSON.stringify([
|
|
1748
|
+
instrument,
|
|
1749
|
+
Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
|
|
1750
|
+
]);
|
|
1751
|
+
var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
|
|
1752
|
+
"user.",
|
|
1753
|
+
"enduser.",
|
|
1754
|
+
"organization."
|
|
1755
|
+
]);
|
|
1756
|
+
|
|
1757
|
+
// src/lifecycle/metric-series.ts
|
|
1758
|
+
var TURN_START_SEGMENT = "turn-start";
|
|
1759
|
+
var SHARED_SCOPE = "all";
|
|
1760
|
+
var SHARED_LOCK = "otelhook.metrics.shared";
|
|
1761
|
+
var sessionScope = (sessionId) => `s=${sessionId}`;
|
|
1762
|
+
var digest = (identity) => createHash2("sha256").update(identity).digest("base64url").slice(0, 43);
|
|
1763
|
+
var toStoredHistogram = (histogram) => ({
|
|
1764
|
+
count: histogram.count,
|
|
1765
|
+
sum: histogram.sum,
|
|
1766
|
+
// An empty histogram has infinite min/max, which JSON cannot hold. A stored
|
|
1767
|
+
// histogram always has at least one value, so these are finite in practice.
|
|
1768
|
+
min: Number.isFinite(histogram.min) ? histogram.min : 0,
|
|
1769
|
+
max: Number.isFinite(histogram.max) ? histogram.max : 0,
|
|
1770
|
+
bucketCounts: [...histogram.bucketCounts]
|
|
1771
|
+
});
|
|
1772
|
+
var createMetricSeriesStore = (deps) => {
|
|
1773
|
+
const { stateStore, clock } = deps;
|
|
1774
|
+
const readSeries = async (key) => {
|
|
1775
|
+
const record = await stateStore.read(key);
|
|
1776
|
+
if (record?.value.kind !== "metric-series") {
|
|
1777
|
+
return void 0;
|
|
1778
|
+
}
|
|
1779
|
+
return record.value;
|
|
1780
|
+
};
|
|
1781
|
+
const recordGroup = async (scope, observations, deliveryToken) => {
|
|
1782
|
+
const bySeries = /* @__PURE__ */ new Map();
|
|
1783
|
+
for (const observation of observations) {
|
|
1784
|
+
const identity = seriesIdentity(observation.instrument, observation.attributes);
|
|
1785
|
+
const group = bySeries.get(identity) ?? [];
|
|
1786
|
+
group.push(observation);
|
|
1787
|
+
bySeries.set(identity, group);
|
|
1788
|
+
}
|
|
1789
|
+
const now = clock.now();
|
|
1790
|
+
const points = [];
|
|
1791
|
+
for (const [identity, group] of bySeries) {
|
|
1792
|
+
const first = group[0];
|
|
1793
|
+
if (first === void 0) {
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
const instrument = METRIC_INSTRUMENTS[first.instrument];
|
|
1797
|
+
const key = metricSeriesKey(scope, digest(identity));
|
|
1798
|
+
const existing = await readSeries(key);
|
|
1799
|
+
const boundaries = instrument.boundaries;
|
|
1800
|
+
const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
|
|
1801
|
+
const base = compatible ? existing : void 0;
|
|
1802
|
+
const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
|
|
1803
|
+
const earliest = Math.min(...group.map((observation) => observation.timeMillis));
|
|
1804
|
+
const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
|
|
1805
|
+
let value = base?.value ?? 0;
|
|
1806
|
+
let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
|
|
1807
|
+
if (!replay) {
|
|
1808
|
+
for (const observation of group) {
|
|
1809
|
+
if (histogram !== void 0 && boundaries !== void 0) {
|
|
1810
|
+
histogram = recordIntoHistogram(histogram, boundaries, observation.value);
|
|
1811
|
+
} else {
|
|
1812
|
+
value += observation.value;
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
await stateStore.write(key, {
|
|
1816
|
+
kind: "metric-series",
|
|
1817
|
+
startTimeMillis,
|
|
1818
|
+
...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
|
|
1819
|
+
...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
|
|
1820
|
+
});
|
|
1821
|
+
}
|
|
1822
|
+
points.push({
|
|
1823
|
+
instrument: first.instrument,
|
|
1824
|
+
temporality: "cumulative",
|
|
1825
|
+
attributes: first.attributes,
|
|
1826
|
+
startTimeMillis,
|
|
1827
|
+
timeMillis: Math.max(now, startTimeMillis),
|
|
1828
|
+
...histogram === void 0 ? { value } : { histogram }
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
return points;
|
|
1832
|
+
};
|
|
1833
|
+
const recordCumulative = async (observations, options) => {
|
|
1834
|
+
if (observations.length === 0) {
|
|
1835
|
+
return [];
|
|
1836
|
+
}
|
|
1837
|
+
if (options?.perSession === false) {
|
|
1838
|
+
return withOptionalSessionLock(
|
|
1839
|
+
stateStore,
|
|
1840
|
+
SHARED_LOCK,
|
|
1841
|
+
() => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
|
|
1842
|
+
);
|
|
1843
|
+
}
|
|
1844
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
1845
|
+
for (const observation of observations) {
|
|
1846
|
+
const group = bySession.get(observation.sessionId) ?? [];
|
|
1847
|
+
group.push(observation);
|
|
1848
|
+
bySession.set(observation.sessionId, group);
|
|
1849
|
+
}
|
|
1850
|
+
const points = [];
|
|
1851
|
+
for (const [sessionId, group] of bySession) {
|
|
1852
|
+
points.push(
|
|
1853
|
+
...await withOptionalSessionLock(
|
|
1854
|
+
stateStore,
|
|
1855
|
+
sessionId,
|
|
1856
|
+
() => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
|
|
1857
|
+
)
|
|
1858
|
+
);
|
|
1859
|
+
}
|
|
1860
|
+
return points;
|
|
1861
|
+
};
|
|
1862
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
1863
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
1864
|
+
const now = clock.now();
|
|
1865
|
+
let removed = 0;
|
|
1866
|
+
let scanned = 0;
|
|
1867
|
+
const prefix = metricSeriesScanPrefix(
|
|
1868
|
+
options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
|
|
1869
|
+
);
|
|
1870
|
+
for (const key of await stateStore.keys(prefix)) {
|
|
1871
|
+
if (scanned >= cap) {
|
|
1872
|
+
break;
|
|
1873
|
+
}
|
|
1874
|
+
scanned += 1;
|
|
1875
|
+
const record = await stateStore.read(key);
|
|
1876
|
+
if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
|
|
1877
|
+
await stateStore.delete(key);
|
|
1878
|
+
removed += 1;
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
return { removed, scanned };
|
|
1882
|
+
};
|
|
1883
|
+
const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
|
|
1884
|
+
const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
|
|
1885
|
+
const existing = await stateStore.read(turnKey(sessionId));
|
|
1886
|
+
const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
|
|
1887
|
+
if (previous !== void 0 && previous >= startMillis) {
|
|
1888
|
+
return;
|
|
1889
|
+
}
|
|
1890
|
+
await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
|
|
1891
|
+
});
|
|
1892
|
+
const readTurnStart = async (sessionId) => {
|
|
1893
|
+
const record = await stateStore.read(turnKey(sessionId));
|
|
1894
|
+
const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
|
|
1895
|
+
return typeof value === "number" ? value : void 0;
|
|
1896
|
+
};
|
|
1897
|
+
return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
|
|
1898
|
+
};
|
|
1899
|
+
|
|
1629
1900
|
// src/lifecycle/janitor.ts
|
|
1630
1901
|
var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
|
|
1631
1902
|
var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
|
|
@@ -1636,7 +1907,7 @@ var createLifecycleJanitor = (options) => {
|
|
|
1636
1907
|
const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
1637
1908
|
const runOnce = async (sessionId) => {
|
|
1638
1909
|
const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
|
|
1639
|
-
const [span, dedup, usage] = await Promise.all([
|
|
1910
|
+
const [span, dedup, usage, metrics] = await Promise.all([
|
|
1640
1911
|
options.spanCorrelator?.cleanup(spanMaxAge, scope),
|
|
1641
1912
|
// Deduplication is deliberately swept across every scope rather than the
|
|
1642
1913
|
// ending session's: a delivery scope is a host-chosen namespace or a
|
|
@@ -1647,12 +1918,14 @@ var createLifecycleJanitor = (options) => {
|
|
|
1647
1918
|
maxEntries,
|
|
1648
1919
|
...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
|
|
1649
1920
|
}),
|
|
1650
|
-
options.usageAccumulator?.cleanup(usageMaxAge, scope)
|
|
1921
|
+
options.usageAccumulator?.cleanup(usageMaxAge, scope),
|
|
1922
|
+
options.metricSeries?.cleanup(usageMaxAge, scope)
|
|
1651
1923
|
]);
|
|
1652
1924
|
return {
|
|
1653
1925
|
...span === void 0 ? {} : { span },
|
|
1654
1926
|
...dedup === void 0 ? {} : { dedup },
|
|
1655
|
-
...usage === void 0 ? {} : { usage }
|
|
1927
|
+
...usage === void 0 ? {} : { usage },
|
|
1928
|
+
...metrics === void 0 ? {} : { metrics }
|
|
1656
1929
|
};
|
|
1657
1930
|
};
|
|
1658
1931
|
return { runOnce };
|
|
@@ -1661,6 +1934,7 @@ export {
|
|
|
1661
1934
|
SPAN_RECORD_VERSION,
|
|
1662
1935
|
createCallbackDeduplicator,
|
|
1663
1936
|
createLifecycleJanitor,
|
|
1937
|
+
createMetricSeriesStore,
|
|
1664
1938
|
createSpanCorrelator,
|
|
1665
1939
|
createUsageAccumulator
|
|
1666
1940
|
};
|