@osfactory/otel-hook 0.9.0 → 0.11.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 +124 -4
- package/dist/{adapter-BJiz6lqM.d.ts → adapter-DiLknaTF.d.ts} +14 -2
- package/dist/cli.js +2272 -730
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +13 -4
- package/dist/config.js +128 -23
- package/dist/config.js.map +1 -1
- package/dist/{destinations-C6Bm89W6.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
- package/dist/diagnostics.d.ts +1 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
- package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-QWKGGEjk.d.ts} +131 -6
- package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
- package/dist/{hook-zA1b4cWd.d.ts → hook-BOecWGSz.d.ts} +10 -5
- package/dist/index.d.ts +16 -16
- package/dist/index.js +1808 -251
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +4 -4
- package/dist/install.js +31 -2
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +37 -12
- package/dist/integration.js +3271 -1551
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +55 -4
- package/dist/lifecycle.js +277 -4
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-Bl9ANVff.d.ts → memory-Cs51jyRk.d.ts} +2 -2
- package/dist/{semconv-fPRb-dpU.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
- package/dist/model.d.ts +1 -1
- package/dist/model.js +7 -0
- package/dist/model.js.map +1 -1
- package/dist/{payload-Ci8_ERm6.d.ts → payload-ChtrEX6A.d.ts} +41 -2
- package/dist/{ports-n7KFOpKo.d.ts → ports-CeqLq31i.d.ts} +87 -2
- package/dist/providers.d.ts +146 -10
- package/dist/providers.js +397 -13
- package/dist/providers.js.map +1 -1
- package/dist/{registry-B8ZHc2bc.d.ts → registry-CcJNF3WY.d.ts} +2 -2
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +1404 -1219
- package/dist/runtime.js.map +1 -1
- package/dist/{schema-BxiVsU-d.d.ts → schema-DMnoU1V_.d.ts} +93 -1
- package/dist/state.d.ts +4 -4
- package/dist/state.js +630 -39
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +6 -6
- package/dist/telemetry.js +872 -19
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +11 -9
- package/dist/testing.js +264 -34
- 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 { g as StateStore, C as Clock } from './ports-CeqLq31i.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-CSD_YiJ2.js';
|
|
4
|
+
import { p as SpanFamily, s as SpanScopeRef, m as SpanCorrelation, j as MetricObservation, k as MetricPoint } from './metric-model-DDnWxL9d.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.11.0";
|
|
273
275
|
|
|
274
276
|
// src/telemetry/export-identity.ts
|
|
275
277
|
import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
|
|
@@ -907,6 +909,13 @@ var generationEndEventSchema = event({
|
|
|
907
909
|
stopReason: nonEmptyStringSchema.optional(),
|
|
908
910
|
durationMillis: durationMillisSchema.optional(),
|
|
909
911
|
usage: canonicalUsageSchema.optional(),
|
|
912
|
+
/**
|
|
913
|
+
* True when `usage` is known to cover only part of the generation (for
|
|
914
|
+
* example the last model request of a multi-request turn); false when the
|
|
915
|
+
* provider or harness said it is the whole. Absent: not stated. Meaningless
|
|
916
|
+
* without `usage`.
|
|
917
|
+
*/
|
|
918
|
+
usagePartial: z9.boolean().optional(),
|
|
910
919
|
cost: costFactsSchema.optional(),
|
|
911
920
|
outputContent: contentFactsSchema.optional()
|
|
912
921
|
});
|
|
@@ -1619,6 +1628,267 @@ var createUsageAccumulator = (deps) => {
|
|
|
1619
1628
|
return { accumulateDelta, recordReset, read, cleanup };
|
|
1620
1629
|
};
|
|
1621
1630
|
|
|
1631
|
+
// src/lifecycle/metric-series.ts
|
|
1632
|
+
import { createHash as createHash2 } from "crypto";
|
|
1633
|
+
|
|
1634
|
+
// src/telemetry/metric-model.ts
|
|
1635
|
+
var TOKEN_USAGE_BUCKETS = Object.freeze([
|
|
1636
|
+
1,
|
|
1637
|
+
4,
|
|
1638
|
+
16,
|
|
1639
|
+
64,
|
|
1640
|
+
256,
|
|
1641
|
+
1024,
|
|
1642
|
+
4096,
|
|
1643
|
+
16384,
|
|
1644
|
+
65536,
|
|
1645
|
+
262144,
|
|
1646
|
+
1048576,
|
|
1647
|
+
4194304,
|
|
1648
|
+
16777216,
|
|
1649
|
+
67108864
|
|
1650
|
+
]);
|
|
1651
|
+
var OPERATION_DURATION_BUCKETS = Object.freeze([
|
|
1652
|
+
0.01,
|
|
1653
|
+
0.02,
|
|
1654
|
+
0.04,
|
|
1655
|
+
0.08,
|
|
1656
|
+
0.16,
|
|
1657
|
+
0.32,
|
|
1658
|
+
0.64,
|
|
1659
|
+
1.28,
|
|
1660
|
+
2.56,
|
|
1661
|
+
5.12,
|
|
1662
|
+
10.24,
|
|
1663
|
+
20.48,
|
|
1664
|
+
40.96,
|
|
1665
|
+
81.92
|
|
1666
|
+
]);
|
|
1667
|
+
var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
|
|
1668
|
+
var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
|
|
1669
|
+
var METRIC_SESSIONS = "otelhook.sessions";
|
|
1670
|
+
var METRIC_TOOL_CALLS = "otelhook.tool.calls";
|
|
1671
|
+
var METRIC_COST_USAGE = "otelhook.cost.usage";
|
|
1672
|
+
var METRIC_INSTRUMENTS = Object.freeze({
|
|
1673
|
+
[METRIC_TOKEN_USAGE]: {
|
|
1674
|
+
name: METRIC_TOKEN_USAGE,
|
|
1675
|
+
kind: "histogram",
|
|
1676
|
+
unit: "{token}",
|
|
1677
|
+
description: "Tokens used per generation, by token type (hook-derived)",
|
|
1678
|
+
valueType: "int",
|
|
1679
|
+
boundaries: TOKEN_USAGE_BUCKETS
|
|
1680
|
+
},
|
|
1681
|
+
[METRIC_OPERATION_DURATION]: {
|
|
1682
|
+
name: METRIC_OPERATION_DURATION,
|
|
1683
|
+
kind: "histogram",
|
|
1684
|
+
unit: "s",
|
|
1685
|
+
description: "Generation duration, from its start hook to its end hook (hook-derived)",
|
|
1686
|
+
valueType: "double",
|
|
1687
|
+
boundaries: OPERATION_DURATION_BUCKETS
|
|
1688
|
+
},
|
|
1689
|
+
[METRIC_SESSIONS]: {
|
|
1690
|
+
name: METRIC_SESSIONS,
|
|
1691
|
+
kind: "counter",
|
|
1692
|
+
unit: "{session}",
|
|
1693
|
+
description: "Agent sessions started",
|
|
1694
|
+
valueType: "int"
|
|
1695
|
+
},
|
|
1696
|
+
[METRIC_TOOL_CALLS]: {
|
|
1697
|
+
name: METRIC_TOOL_CALLS,
|
|
1698
|
+
kind: "counter",
|
|
1699
|
+
unit: "{call}",
|
|
1700
|
+
description: "Completed tool calls, by tool name and outcome",
|
|
1701
|
+
valueType: "int"
|
|
1702
|
+
},
|
|
1703
|
+
[METRIC_COST_USAGE]: {
|
|
1704
|
+
name: METRIC_COST_USAGE,
|
|
1705
|
+
kind: "counter",
|
|
1706
|
+
unit: "USD",
|
|
1707
|
+
description: "Cost reported by the provider; never estimated",
|
|
1708
|
+
valueType: "double"
|
|
1709
|
+
}
|
|
1710
|
+
});
|
|
1711
|
+
var emptyHistogram = (boundaries) => ({
|
|
1712
|
+
count: 0,
|
|
1713
|
+
sum: 0,
|
|
1714
|
+
min: Number.POSITIVE_INFINITY,
|
|
1715
|
+
max: Number.NEGATIVE_INFINITY,
|
|
1716
|
+
bucketCounts: new Array(boundaries.length + 1).fill(0)
|
|
1717
|
+
});
|
|
1718
|
+
var bucketIndex = (boundaries, value) => {
|
|
1719
|
+
for (let index = 0; index < boundaries.length; index += 1) {
|
|
1720
|
+
const bound = boundaries[index];
|
|
1721
|
+
if (bound !== void 0 && value <= bound) {
|
|
1722
|
+
return index;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
return boundaries.length;
|
|
1726
|
+
};
|
|
1727
|
+
var recordIntoHistogram = (state, boundaries, value) => {
|
|
1728
|
+
const bucketCounts = [...state.bucketCounts];
|
|
1729
|
+
const index = bucketIndex(boundaries, value);
|
|
1730
|
+
bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
|
|
1731
|
+
return {
|
|
1732
|
+
count: state.count + 1,
|
|
1733
|
+
sum: state.sum + value,
|
|
1734
|
+
min: Math.min(state.min, value),
|
|
1735
|
+
max: Math.max(state.max, value),
|
|
1736
|
+
bucketCounts
|
|
1737
|
+
};
|
|
1738
|
+
};
|
|
1739
|
+
var seriesIdentity = (instrument, attributes) => JSON.stringify([
|
|
1740
|
+
instrument,
|
|
1741
|
+
Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
|
|
1742
|
+
]);
|
|
1743
|
+
var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
|
|
1744
|
+
"user.",
|
|
1745
|
+
"enduser.",
|
|
1746
|
+
"organization."
|
|
1747
|
+
]);
|
|
1748
|
+
|
|
1749
|
+
// src/lifecycle/metric-series.ts
|
|
1750
|
+
var TURN_START_SEGMENT = "turn-start";
|
|
1751
|
+
var SHARED_SCOPE = "all";
|
|
1752
|
+
var SHARED_LOCK = "otelhook.metrics.shared";
|
|
1753
|
+
var sessionScope = (sessionId) => `s=${sessionId}`;
|
|
1754
|
+
var digest = (identity) => createHash2("sha256").update(identity).digest("base64url").slice(0, 43);
|
|
1755
|
+
var toStoredHistogram = (histogram) => ({
|
|
1756
|
+
count: histogram.count,
|
|
1757
|
+
sum: histogram.sum,
|
|
1758
|
+
// An empty histogram has infinite min/max, which JSON cannot hold. A stored
|
|
1759
|
+
// histogram always has at least one value, so these are finite in practice.
|
|
1760
|
+
min: Number.isFinite(histogram.min) ? histogram.min : 0,
|
|
1761
|
+
max: Number.isFinite(histogram.max) ? histogram.max : 0,
|
|
1762
|
+
bucketCounts: [...histogram.bucketCounts]
|
|
1763
|
+
});
|
|
1764
|
+
var createMetricSeriesStore = (deps) => {
|
|
1765
|
+
const { stateStore, clock } = deps;
|
|
1766
|
+
const readSeries = async (key) => {
|
|
1767
|
+
const record = await stateStore.read(key);
|
|
1768
|
+
if (record?.value.kind !== "metric-series") {
|
|
1769
|
+
return void 0;
|
|
1770
|
+
}
|
|
1771
|
+
return record.value;
|
|
1772
|
+
};
|
|
1773
|
+
const recordGroup = async (scope, observations, deliveryToken) => {
|
|
1774
|
+
const bySeries = /* @__PURE__ */ new Map();
|
|
1775
|
+
for (const observation of observations) {
|
|
1776
|
+
const identity = seriesIdentity(observation.instrument, observation.attributes);
|
|
1777
|
+
const group = bySeries.get(identity) ?? [];
|
|
1778
|
+
group.push(observation);
|
|
1779
|
+
bySeries.set(identity, group);
|
|
1780
|
+
}
|
|
1781
|
+
const now = clock.now();
|
|
1782
|
+
const points = [];
|
|
1783
|
+
for (const [identity, group] of bySeries) {
|
|
1784
|
+
const first = group[0];
|
|
1785
|
+
if (first === void 0) {
|
|
1786
|
+
continue;
|
|
1787
|
+
}
|
|
1788
|
+
const instrument = METRIC_INSTRUMENTS[first.instrument];
|
|
1789
|
+
const key = metricSeriesKey(scope, digest(identity));
|
|
1790
|
+
const existing = await readSeries(key);
|
|
1791
|
+
const boundaries = instrument.boundaries;
|
|
1792
|
+
const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
|
|
1793
|
+
const base = compatible ? existing : void 0;
|
|
1794
|
+
const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
|
|
1795
|
+
const earliest = Math.min(...group.map((observation) => observation.timeMillis));
|
|
1796
|
+
const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
|
|
1797
|
+
let value = base?.value ?? 0;
|
|
1798
|
+
let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
|
|
1799
|
+
if (!replay) {
|
|
1800
|
+
for (const observation of group) {
|
|
1801
|
+
if (histogram !== void 0 && boundaries !== void 0) {
|
|
1802
|
+
histogram = recordIntoHistogram(histogram, boundaries, observation.value);
|
|
1803
|
+
} else {
|
|
1804
|
+
value += observation.value;
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
await stateStore.write(key, {
|
|
1808
|
+
kind: "metric-series",
|
|
1809
|
+
startTimeMillis,
|
|
1810
|
+
...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
|
|
1811
|
+
...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
points.push({
|
|
1815
|
+
instrument: first.instrument,
|
|
1816
|
+
temporality: "cumulative",
|
|
1817
|
+
attributes: first.attributes,
|
|
1818
|
+
startTimeMillis,
|
|
1819
|
+
timeMillis: Math.max(now, startTimeMillis),
|
|
1820
|
+
...histogram === void 0 ? { value } : { histogram }
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
return points;
|
|
1824
|
+
};
|
|
1825
|
+
const recordCumulative = async (observations, options) => {
|
|
1826
|
+
if (observations.length === 0) {
|
|
1827
|
+
return [];
|
|
1828
|
+
}
|
|
1829
|
+
if (options?.perSession === false) {
|
|
1830
|
+
return withOptionalSessionLock(
|
|
1831
|
+
stateStore,
|
|
1832
|
+
SHARED_LOCK,
|
|
1833
|
+
() => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
1837
|
+
for (const observation of observations) {
|
|
1838
|
+
const group = bySession.get(observation.sessionId) ?? [];
|
|
1839
|
+
group.push(observation);
|
|
1840
|
+
bySession.set(observation.sessionId, group);
|
|
1841
|
+
}
|
|
1842
|
+
const points = [];
|
|
1843
|
+
for (const [sessionId, group] of bySession) {
|
|
1844
|
+
points.push(
|
|
1845
|
+
...await withOptionalSessionLock(
|
|
1846
|
+
stateStore,
|
|
1847
|
+
sessionId,
|
|
1848
|
+
() => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
|
|
1849
|
+
)
|
|
1850
|
+
);
|
|
1851
|
+
}
|
|
1852
|
+
return points;
|
|
1853
|
+
};
|
|
1854
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
1855
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
1856
|
+
const now = clock.now();
|
|
1857
|
+
let removed = 0;
|
|
1858
|
+
let scanned = 0;
|
|
1859
|
+
const prefix = metricSeriesScanPrefix(
|
|
1860
|
+
options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
|
|
1861
|
+
);
|
|
1862
|
+
for (const key of await stateStore.keys(prefix)) {
|
|
1863
|
+
if (scanned >= cap) {
|
|
1864
|
+
break;
|
|
1865
|
+
}
|
|
1866
|
+
scanned += 1;
|
|
1867
|
+
const record = await stateStore.read(key);
|
|
1868
|
+
if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
|
|
1869
|
+
await stateStore.delete(key);
|
|
1870
|
+
removed += 1;
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
return { removed, scanned };
|
|
1874
|
+
};
|
|
1875
|
+
const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
|
|
1876
|
+
const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
|
|
1877
|
+
const existing = await stateStore.read(turnKey(sessionId));
|
|
1878
|
+
const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
|
|
1879
|
+
if (previous !== void 0 && previous >= startMillis) {
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
|
|
1883
|
+
});
|
|
1884
|
+
const readTurnStart = async (sessionId) => {
|
|
1885
|
+
const record = await stateStore.read(turnKey(sessionId));
|
|
1886
|
+
const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
|
|
1887
|
+
return typeof value === "number" ? value : void 0;
|
|
1888
|
+
};
|
|
1889
|
+
return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
|
|
1890
|
+
};
|
|
1891
|
+
|
|
1622
1892
|
// src/lifecycle/janitor.ts
|
|
1623
1893
|
var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
|
|
1624
1894
|
var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
|
|
@@ -1629,7 +1899,7 @@ var createLifecycleJanitor = (options) => {
|
|
|
1629
1899
|
const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
1630
1900
|
const runOnce = async (sessionId) => {
|
|
1631
1901
|
const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
|
|
1632
|
-
const [span, dedup, usage] = await Promise.all([
|
|
1902
|
+
const [span, dedup, usage, metrics] = await Promise.all([
|
|
1633
1903
|
options.spanCorrelator?.cleanup(spanMaxAge, scope),
|
|
1634
1904
|
// Deduplication is deliberately swept across every scope rather than the
|
|
1635
1905
|
// ending session's: a delivery scope is a host-chosen namespace or a
|
|
@@ -1640,12 +1910,14 @@ var createLifecycleJanitor = (options) => {
|
|
|
1640
1910
|
maxEntries,
|
|
1641
1911
|
...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
|
|
1642
1912
|
}),
|
|
1643
|
-
options.usageAccumulator?.cleanup(usageMaxAge, scope)
|
|
1913
|
+
options.usageAccumulator?.cleanup(usageMaxAge, scope),
|
|
1914
|
+
options.metricSeries?.cleanup(usageMaxAge, scope)
|
|
1644
1915
|
]);
|
|
1645
1916
|
return {
|
|
1646
1917
|
...span === void 0 ? {} : { span },
|
|
1647
1918
|
...dedup === void 0 ? {} : { dedup },
|
|
1648
|
-
...usage === void 0 ? {} : { usage }
|
|
1919
|
+
...usage === void 0 ? {} : { usage },
|
|
1920
|
+
...metrics === void 0 ? {} : { metrics }
|
|
1649
1921
|
};
|
|
1650
1922
|
};
|
|
1651
1923
|
return { runOnce };
|
|
@@ -1654,6 +1926,7 @@ export {
|
|
|
1654
1926
|
SPAN_RECORD_VERSION,
|
|
1655
1927
|
createCallbackDeduplicator,
|
|
1656
1928
|
createLifecycleJanitor,
|
|
1929
|
+
createMetricSeriesStore,
|
|
1657
1930
|
createSpanCorrelator,
|
|
1658
1931
|
createUsageAccumulator
|
|
1659
1932
|
};
|