@rasputin-ai/node 0.12.1 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-instrumentation/bun-plugin.d.ts.map +1 -1
- package/dist/auto-instrumentation/instrument-compiled-esm.d.ts.map +1 -1
- package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts +2 -1
- package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts.map +1 -1
- package/dist/auto-instrumentation/node-hooks.d.ts.map +1 -1
- package/dist/auto-instrumentation/transform-disk-cache.d.ts.map +1 -1
- package/dist/execution-recorder/bind-adaptive-recorder.d.ts +4 -2
- package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
- package/dist/execution-recorder/execution-recorder-hooks.d.ts +3 -0
- package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -1
- package/dist/execution-recorder/execution-recorder-types.d.ts +1 -2
- package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
- package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
- package/dist/execution-recorder/execution-recording-sync.d.ts +2 -2
- package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
- package/dist/execution-recorder/function-plan.d.ts +3 -1
- package/dist/execution-recorder/function-plan.d.ts.map +1 -1
- package/dist/function-metrics/bind-function-metrics.d.ts +19 -0
- package/dist/function-metrics/bind-function-metrics.d.ts.map +1 -0
- package/dist/function-metrics/create-metrics-only-runtime.d.ts +4 -0
- package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -0
- package/dist/function-metrics/encode-function-metrics-upload.d.ts +14 -0
- package/dist/function-metrics/encode-function-metrics-upload.d.ts.map +1 -0
- package/dist/function-metrics/function-metric-declaration-registry.d.ts +9 -0
- package/dist/function-metrics/function-metric-declaration-registry.d.ts.map +1 -0
- package/dist/function-metrics/function-metrics-batches.d.ts +35 -0
- package/dist/function-metrics/function-metrics-batches.d.ts.map +1 -0
- package/dist/function-metrics/function-metrics-collector.d.ts +45 -0
- package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -0
- package/dist/function-metrics/function-metrics-exporter.d.ts +23 -0
- package/dist/function-metrics/function-metrics-exporter.d.ts.map +1 -0
- package/dist/function-metrics/install-function-metric-declaration-sink.d.ts +2 -0
- package/dist/function-metrics/install-function-metric-declaration-sink.d.ts.map +1 -0
- package/dist/function-metrics/intern-prepared-metrics.d.ts +4 -0
- package/dist/function-metrics/intern-prepared-metrics.d.ts.map +1 -0
- package/dist/function-metrics/send-function-metrics-batch.d.ts +25 -0
- package/dist/function-metrics/send-function-metrics-batch.d.ts.map +1 -0
- package/dist/function-metrics/settle-function-metrics.d.ts +5 -0
- package/dist/function-metrics/settle-function-metrics.d.ts.map +1 -0
- package/dist/index.js +1624 -147
- package/dist/instrument/build.js +458 -162
- package/dist/instrument/bun.js +454 -132
- package/dist/instrument/node.js +452 -132
- package/dist/internal.d.ts +2 -0
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +1600 -139
- package/dist/rasputin-init.d.ts +17 -4
- package/dist/rasputin-init.d.ts.map +1 -1
- package/dist/sdk-meta.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -3,7 +3,8 @@ import { join } from "node:path";
|
|
|
3
3
|
import {
|
|
4
4
|
copyRedactKeys as copyRedactKeys2,
|
|
5
5
|
createClient,
|
|
6
|
-
isClientEnabled
|
|
6
|
+
isClientEnabled,
|
|
7
|
+
resolveClientActivation as resolveClientActivation2
|
|
7
8
|
} from "@rasputin-ai/core";
|
|
8
9
|
|
|
9
10
|
// src/auto-instrumentation/instrumentation-manifest-registry.ts
|
|
@@ -220,9 +221,12 @@ var snapshotInstrumentationManifest = (options = {}) => {
|
|
|
220
221
|
if (registry.snapshotCache && registry.snapshotCache.generation === registry.generation && registry.snapshotCache.optionsKey === optionsKey) {
|
|
221
222
|
return registry.snapshotCache.manifest;
|
|
222
223
|
}
|
|
223
|
-
const functions =
|
|
224
|
-
|
|
225
|
-
|
|
224
|
+
const functions = new Map(
|
|
225
|
+
registry.prebuilt?.functions.map((fn) => [fn.functionId, fn])
|
|
226
|
+
);
|
|
227
|
+
const callSites = new Map(
|
|
228
|
+
registry.prebuilt?.callSites.map((site) => [site.id, site])
|
|
229
|
+
);
|
|
226
230
|
const remember = (manifest) => {
|
|
227
231
|
registry.snapshotCache = {
|
|
228
232
|
generation: registry.generation,
|
|
@@ -235,83 +239,95 @@ var snapshotInstrumentationManifest = (options = {}) => {
|
|
|
235
239
|
for (const fn of delta.functions) {
|
|
236
240
|
const definition = definitionFromEncodedPlan(fn.plan);
|
|
237
241
|
if (!definition.source) continue;
|
|
238
|
-
|
|
242
|
+
if (!fn.metricsDeclaration) {
|
|
243
|
+
throw new Error(`Missing function metrics declaration: ${fn.functionId}`);
|
|
244
|
+
}
|
|
245
|
+
functions.set(definition.functionId, {
|
|
246
|
+
...functions.get(definition.functionId),
|
|
239
247
|
functionId: definition.functionId,
|
|
240
|
-
source:
|
|
248
|
+
source: {
|
|
249
|
+
packageRelativePath: definition.source.packageRelativePath,
|
|
250
|
+
...definition.source.packageName ? { packageName: definition.source.packageName } : {},
|
|
251
|
+
...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
|
|
252
|
+
},
|
|
241
253
|
name: fn.name,
|
|
242
254
|
startLine: fn.startLine,
|
|
243
255
|
startColumn: fn.startColumn,
|
|
244
256
|
endLine: fn.endLine,
|
|
245
257
|
endColumn: fn.endColumn,
|
|
246
|
-
|
|
258
|
+
metricsDeclaration: fn.metricsDeclaration,
|
|
247
259
|
...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
|
|
248
260
|
});
|
|
249
261
|
}
|
|
250
262
|
for (const site of delta.callSites) {
|
|
251
263
|
const source = sourceAt(site.filePath, site.line, site.column);
|
|
252
264
|
if (!source) continue;
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
265
|
+
const id = stableId(
|
|
266
|
+
"cs",
|
|
267
|
+
site.callerFunctionId,
|
|
268
|
+
source.packageName ?? "",
|
|
269
|
+
source.packageRelativePath,
|
|
270
|
+
site.line,
|
|
271
|
+
site.column
|
|
272
|
+
);
|
|
273
|
+
callSites.set(id, {
|
|
274
|
+
id,
|
|
262
275
|
callerFunctionId: site.callerFunctionId,
|
|
263
276
|
calleeName: site.calleeName,
|
|
264
277
|
calleeText: site.calleeText,
|
|
265
|
-
source,
|
|
266
278
|
line: site.line,
|
|
267
279
|
column: site.column,
|
|
268
280
|
endLine: site.endLine,
|
|
269
281
|
endColumn: site.endColumn,
|
|
270
|
-
resultBinding: site.resultBinding
|
|
271
|
-
argIdentifiers: site.argIdentifiers
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
|
-
for (const destructure of delta.destructures) {
|
|
275
|
-
const source = sourceAt(destructure.filePath, destructure.line, destructure.column);
|
|
276
|
-
if (!source) continue;
|
|
277
|
-
destructures.push({
|
|
278
|
-
callerFunctionId: destructure.callerFunctionId,
|
|
279
|
-
sourceParam: destructure.sourceParam,
|
|
280
|
-
source,
|
|
281
|
-
line: destructure.line,
|
|
282
|
-
column: destructure.column,
|
|
283
|
-
binding: destructure.binding
|
|
282
|
+
resultBinding: site.resultBinding
|
|
284
283
|
});
|
|
285
284
|
}
|
|
286
285
|
}
|
|
287
286
|
if (registry.prebuilt && registry.files.size === 0) {
|
|
288
|
-
|
|
289
|
-
if (!options.sourceRoot && !options.sourceRoots) return remember(prebuilt);
|
|
287
|
+
if (!options.sourceRoot && !options.sourceRoots) return remember(registry.prebuilt);
|
|
290
288
|
return remember({
|
|
291
|
-
...prebuilt,
|
|
289
|
+
...registry.prebuilt,
|
|
292
290
|
sourceRoots: {
|
|
293
291
|
...options.sourceRoot ? { default: options.sourceRoot } : {},
|
|
294
292
|
packages: { ...options.sourceRoots ?? {} }
|
|
295
293
|
}
|
|
296
294
|
});
|
|
297
295
|
}
|
|
298
|
-
if (functions.
|
|
296
|
+
if (functions.size === 0 && callSites.size === 0) {
|
|
299
297
|
return remember(void 0);
|
|
300
298
|
}
|
|
301
|
-
const packages = { ...options.sourceRoots
|
|
299
|
+
const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
|
|
300
|
+
const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
|
|
302
301
|
return remember({
|
|
303
302
|
schema_version: INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
|
|
304
|
-
...
|
|
303
|
+
...sourceRoot || Object.keys(packages).length > 0 ? {
|
|
305
304
|
sourceRoots: {
|
|
306
|
-
...
|
|
305
|
+
...sourceRoot ? { default: sourceRoot } : {},
|
|
307
306
|
packages
|
|
308
307
|
}
|
|
309
308
|
} : {},
|
|
310
|
-
functions,
|
|
311
|
-
callSites
|
|
312
|
-
destructures
|
|
309
|
+
functions: [...functions.values()],
|
|
310
|
+
callSites: [...callSites.values()]
|
|
313
311
|
});
|
|
314
312
|
};
|
|
313
|
+
var collectParamsByFunctionId = () => {
|
|
314
|
+
const registry = getRegistry();
|
|
315
|
+
if (registry.paramsCache?.generation === registry.generation) return registry.paramsCache.params;
|
|
316
|
+
const params = /* @__PURE__ */ new Map();
|
|
317
|
+
for (const delta of registry.files.values()) {
|
|
318
|
+
for (const fn of delta.functions) {
|
|
319
|
+
if (!fn.params || fn.params.length === 0) continue;
|
|
320
|
+
const definition = definitionFromEncodedPlan(fn.plan);
|
|
321
|
+
params.set(definition.functionId, fn.params);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
registry.paramsCache = { generation: registry.generation, params };
|
|
325
|
+
return params;
|
|
326
|
+
};
|
|
327
|
+
var paramsForRuntimeFunction = (functionId) => {
|
|
328
|
+
const params = collectParamsByFunctionId().get(functionId);
|
|
329
|
+
return params && params.length > 0 ? params : void 0;
|
|
330
|
+
};
|
|
315
331
|
var markInstrumentationManifestUploaded = (generation) => {
|
|
316
332
|
const registry = getRegistry();
|
|
317
333
|
if (registry.generation === generation) registry.uploadedGeneration = generation;
|
|
@@ -663,13 +679,318 @@ var scheduleInstrumentationManifestUpload = (options) => {
|
|
|
663
679
|
};
|
|
664
680
|
|
|
665
681
|
// src/execution-recorder/execution-recorder.ts
|
|
666
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
682
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
667
683
|
import {
|
|
684
|
+
functionMetricsTraceDeclaration as functionMetricsTraceDeclaration3,
|
|
668
685
|
rasputinOmitted,
|
|
669
686
|
rasputinTagKind,
|
|
687
|
+
runtimeFunctionId as runtimeFunctionId3
|
|
688
|
+
} from "@rasputin-ai/core";
|
|
689
|
+
|
|
690
|
+
// src/function-metrics/create-metrics-only-runtime.ts
|
|
691
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
692
|
+
import {
|
|
693
|
+
functionMetricsTraceDeclaration as functionMetricsTraceDeclaration2,
|
|
670
694
|
runtimeFunctionId as runtimeFunctionId2
|
|
671
695
|
} from "@rasputin-ai/core";
|
|
672
696
|
|
|
697
|
+
// src/execution-recorder/error-observation.ts
|
|
698
|
+
var bindings = /* @__PURE__ */ new WeakMap();
|
|
699
|
+
var mintErrorObservation = (binding) => {
|
|
700
|
+
const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
701
|
+
bindings.set(observation, binding);
|
|
702
|
+
return observation;
|
|
703
|
+
};
|
|
704
|
+
var bindingForObservation = (value) => {
|
|
705
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
706
|
+
return bindings.get(value);
|
|
707
|
+
};
|
|
708
|
+
var inertErrorObservation = () => {
|
|
709
|
+
return Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
// src/execution-recorder/execution-identity.ts
|
|
713
|
+
var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
|
|
714
|
+
var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
|
|
715
|
+
var trimmed = (value) => typeof value === "string" ? value.trim() : "";
|
|
716
|
+
var boundedKey = (key) => {
|
|
717
|
+
return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
|
|
718
|
+
};
|
|
719
|
+
var executionTypeKey = (metadata) => {
|
|
720
|
+
if (metadata.kind === "http") {
|
|
721
|
+
const method = trimmed(metadata.request?.method).toUpperCase();
|
|
722
|
+
const route = trimmed(metadata.request?.route);
|
|
723
|
+
if (!method || !route) return void 0;
|
|
724
|
+
if (route.includes("?") || route.includes("://")) return void 0;
|
|
725
|
+
return boundedKey(`http:${method}:${route}`);
|
|
726
|
+
}
|
|
727
|
+
if (!NAMED_KINDS.has(metadata.kind)) return void 0;
|
|
728
|
+
const name = trimmed(metadata.name);
|
|
729
|
+
if (!name) return void 0;
|
|
730
|
+
return boundedKey(`${metadata.kind}:${name}`);
|
|
731
|
+
};
|
|
732
|
+
var isHttpClientErrorStatus = (status) => {
|
|
733
|
+
return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
// src/execution-recorder/function-plan.ts
|
|
737
|
+
var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
|
|
738
|
+
var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
|
|
739
|
+
|
|
740
|
+
// src/function-metrics/function-metric-declaration-registry.ts
|
|
741
|
+
var REGISTRY_SYMBOL = Symbol.for("rasputin.functionMetrics.declarations.v1");
|
|
742
|
+
var getRegistry2 = () => {
|
|
743
|
+
const existing = Reflect.get(globalThis, REGISTRY_SYMBOL);
|
|
744
|
+
if (typeof existing === "object" && existing !== null) {
|
|
745
|
+
const byRuntimeId = Reflect.get(existing, "byRuntimeId");
|
|
746
|
+
if (byRuntimeId instanceof Map) return { byRuntimeId };
|
|
747
|
+
}
|
|
748
|
+
const registry = {
|
|
749
|
+
byRuntimeId: /* @__PURE__ */ new Map()
|
|
750
|
+
};
|
|
751
|
+
Reflect.set(globalThis, REGISTRY_SYMBOL, registry);
|
|
752
|
+
return registry;
|
|
753
|
+
};
|
|
754
|
+
var registerFunctionMetricDeclarations = (declarations) => {
|
|
755
|
+
const { byRuntimeId } = getRegistry2();
|
|
756
|
+
for (const declaration of declarations) {
|
|
757
|
+
if (byRuntimeId.has(declaration.runtime_id)) continue;
|
|
758
|
+
byRuntimeId.set(declaration.runtime_id, declaration);
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
var functionMetricDeclarationFor = (runtimeId) => getRegistry2().byRuntimeId.get(runtimeId);
|
|
762
|
+
|
|
763
|
+
// src/function-metrics/intern-prepared-metrics.ts
|
|
764
|
+
import { functionMetricsTraceDeclaration } from "@rasputin-ai/core";
|
|
765
|
+
var internPreparedMetrics = (collector, plan) => {
|
|
766
|
+
if (plan.excluded) return void 0;
|
|
767
|
+
if (plan.metricsHandle !== void 0) return plan.metricsHandle;
|
|
768
|
+
const declaration = plan.metricsDeclaration ?? functionMetricDeclarationFor(plan.functionId) ?? functionMetricsTraceDeclaration({
|
|
769
|
+
runtimeId: plan.functionId
|
|
770
|
+
});
|
|
771
|
+
plan.metricsDeclaration = declaration;
|
|
772
|
+
const handle = collector.internDeclaration(declaration);
|
|
773
|
+
if (handle !== void 0) plan.metricsHandle = handle;
|
|
774
|
+
return handle;
|
|
775
|
+
};
|
|
776
|
+
|
|
777
|
+
// src/function-metrics/settle-function-metrics.ts
|
|
778
|
+
var finishMetricsCall = (collector, functionHandle, executionHandle, startedNs, failed, endedNs) => {
|
|
779
|
+
try {
|
|
780
|
+
collector.finishCall(functionHandle, executionHandle, startedNs, failed, endedNs);
|
|
781
|
+
} catch {
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
var thenOf = (value) => {
|
|
785
|
+
if (typeof value !== "object" && typeof value !== "function" || value === null) {
|
|
786
|
+
return void 0;
|
|
787
|
+
}
|
|
788
|
+
if (!("then" in value)) return void 0;
|
|
789
|
+
const then = value.then;
|
|
790
|
+
if (typeof then !== "function") return void 0;
|
|
791
|
+
return (onFulfilled, onRejected) => {
|
|
792
|
+
Reflect.apply(then, value, [onFulfilled, onRejected]);
|
|
793
|
+
};
|
|
794
|
+
};
|
|
795
|
+
var startMetricsCall = (collector, functionHandle, executionHandle, startedNs) => {
|
|
796
|
+
if (!collector || functionHandle === void 0) return void 0;
|
|
797
|
+
try {
|
|
798
|
+
return collector.startCall(functionHandle, executionHandle, startedNs);
|
|
799
|
+
} catch {
|
|
800
|
+
return void 0;
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
var completeMetricsResult = (collector, functionHandle, executionHandle, startedNs, value) => {
|
|
804
|
+
const then = thenOf(value);
|
|
805
|
+
if (!then) {
|
|
806
|
+
finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false);
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
try {
|
|
810
|
+
then(
|
|
811
|
+
() => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, false),
|
|
812
|
+
() => finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true)
|
|
813
|
+
);
|
|
814
|
+
} catch {
|
|
815
|
+
finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
|
|
819
|
+
// src/function-metrics/create-metrics-only-runtime.ts
|
|
820
|
+
var emptyStats = () => ({
|
|
821
|
+
functionCallsObserved: 0,
|
|
822
|
+
functionCallsCaptured: 0,
|
|
823
|
+
functionCallsExcluded: 0,
|
|
824
|
+
serializedValues: 0,
|
|
825
|
+
serializedValueNodes: 0,
|
|
826
|
+
serializedValueBytes: 0,
|
|
827
|
+
errorSnapshots: 0,
|
|
828
|
+
successfulExecutionsDiscarded: 0,
|
|
829
|
+
truncatedEvents: 0,
|
|
830
|
+
repeatedCallsSuppressed: 0,
|
|
831
|
+
activeExecutions: 0,
|
|
832
|
+
peakActiveExecutions: 0,
|
|
833
|
+
activeEstimatedBytes: 0,
|
|
834
|
+
peakActiveEstimatedBytes: 0,
|
|
835
|
+
memoryPressureExecutions: 0,
|
|
836
|
+
memoryPressureDegradations: 0,
|
|
837
|
+
valuesDroppedByMemoryBudget: 0,
|
|
838
|
+
eventsDroppedByMemoryBudget: 0,
|
|
839
|
+
partialErrorSnapshots: 0,
|
|
840
|
+
measuredExecutions: 0,
|
|
841
|
+
totalInlineWallTimeMs: 0,
|
|
842
|
+
maxInlineWallTimeMs: 0,
|
|
843
|
+
journalPoolHits: 0,
|
|
844
|
+
journalPoolMisses: 0,
|
|
845
|
+
journalPoolSize: 0,
|
|
846
|
+
journalAllocatedCapacity: 0,
|
|
847
|
+
attributionDegradations: 0,
|
|
848
|
+
adaptiveLightExecutions: 0,
|
|
849
|
+
adaptiveFullExecutions: 0,
|
|
850
|
+
adaptiveActivations: 0,
|
|
851
|
+
adaptiveNotifyFailures: 0,
|
|
852
|
+
adaptiveRefreshFailures: 0,
|
|
853
|
+
lastAdaptiveFailureKind: null
|
|
854
|
+
});
|
|
855
|
+
var mergeMetadata = (store, metadata) => {
|
|
856
|
+
if (metadata.kind) store.execution.kind = metadata.kind;
|
|
857
|
+
if (metadata.name !== void 0) store.execution.name = metadata.name;
|
|
858
|
+
if (metadata.request) {
|
|
859
|
+
store.execution.request = { ...store.execution.request, ...metadata.request };
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
var definitionOf = (input) => {
|
|
863
|
+
if (typeof input === "string")
|
|
864
|
+
return { name: input, functionId: runtimeFunctionId2({ name: input }) };
|
|
865
|
+
return input;
|
|
866
|
+
};
|
|
867
|
+
var bindExecutionHandle = (collector, store) => {
|
|
868
|
+
store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
|
|
869
|
+
};
|
|
870
|
+
var runWithMetrics = (collector, plan, executionHandle, callback) => {
|
|
871
|
+
const functionHandle = internPreparedMetrics(collector, plan);
|
|
872
|
+
const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
|
|
873
|
+
try {
|
|
874
|
+
const result = callback();
|
|
875
|
+
if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
|
|
876
|
+
completeMetricsResult(collector, functionHandle, executionHandle, startedNs, result);
|
|
877
|
+
}
|
|
878
|
+
return result;
|
|
879
|
+
} catch (error) {
|
|
880
|
+
if (startedNs !== void 0 && functionHandle !== void 0 && executionHandle !== void 0) {
|
|
881
|
+
finishMetricsCall(collector, functionHandle, executionHandle, startedNs, true);
|
|
882
|
+
}
|
|
883
|
+
throw error;
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
var metricsHandle = (collector, plan, executionHandle) => {
|
|
887
|
+
const functionHandle = internPreparedMetrics(collector, plan);
|
|
888
|
+
const startedNs = startMetricsCall(collector, functionHandle, executionHandle);
|
|
889
|
+
if (startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
|
|
890
|
+
return passthroughHandle();
|
|
891
|
+
}
|
|
892
|
+
let failed = false;
|
|
893
|
+
let settled = false;
|
|
894
|
+
return {
|
|
895
|
+
leave: (value) => value,
|
|
896
|
+
fail: () => {
|
|
897
|
+
failed = true;
|
|
898
|
+
},
|
|
899
|
+
end: () => {
|
|
900
|
+
if (settled) return;
|
|
901
|
+
settled = true;
|
|
902
|
+
finishMetricsCall(collector, functionHandle, executionHandle, startedNs, failed);
|
|
903
|
+
},
|
|
904
|
+
run: function __rasputinHandleRun__4(callback) {
|
|
905
|
+
return runExactlyOnce((invoke) => invoke(), callback);
|
|
906
|
+
},
|
|
907
|
+
suspend: (value) => value,
|
|
908
|
+
resume: (value) => value
|
|
909
|
+
};
|
|
910
|
+
};
|
|
911
|
+
var createMetricsOnlyRuntime = (collector) => {
|
|
912
|
+
const storage = new AsyncLocalStorage();
|
|
913
|
+
const preparedModules = /* @__PURE__ */ new WeakMap();
|
|
914
|
+
let nextRuntimePlanId = 1;
|
|
915
|
+
const currentHandle = () => storage.getStore()?.executionHandle;
|
|
916
|
+
const planFor = (definition) => ({
|
|
917
|
+
runtimePlanId: nextRuntimePlanId++,
|
|
918
|
+
definition,
|
|
919
|
+
functionId: definition.functionId,
|
|
920
|
+
excluded: false,
|
|
921
|
+
estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
|
|
922
|
+
omitCallValues: false,
|
|
923
|
+
metricsDeclaration: functionMetricDeclarationFor(definition.functionId) ?? functionMetricsTraceDeclaration2({
|
|
924
|
+
runtimeId: definition.functionId
|
|
925
|
+
})
|
|
926
|
+
});
|
|
927
|
+
const prepareEncoded = (plans) => {
|
|
928
|
+
const cached = preparedModules.get(plans);
|
|
929
|
+
if (cached) return cached;
|
|
930
|
+
const prepared = plans.map((encoded) => {
|
|
931
|
+
const definition = definitionFromEncodedPlan(encoded);
|
|
932
|
+
return {
|
|
933
|
+
...planFor(definition),
|
|
934
|
+
omitCallValues: encodedPlanOmitsCallValues(encoded),
|
|
935
|
+
metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
|
|
936
|
+
};
|
|
937
|
+
});
|
|
938
|
+
preparedModules.set(plans, prepared);
|
|
939
|
+
return prepared;
|
|
940
|
+
};
|
|
941
|
+
const runPrepared = (plan, _args, callback) => runWithMetrics(collector, plan, currentHandle(), callback);
|
|
942
|
+
function trace(input, fn) {
|
|
943
|
+
const definition = typeof input === "string" ? definitionOf(input) : { ...input, functionId: runtimeFunctionId2(input) };
|
|
944
|
+
const plan = planFor(definition);
|
|
945
|
+
return function __rasputinHandleRun__4(...args) {
|
|
946
|
+
if (new.target) {
|
|
947
|
+
throw new TypeError("execution.trace() wraps function calls, not constructors");
|
|
948
|
+
}
|
|
949
|
+
return runPrepared(plan, args, () => fn.apply(this, args));
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
return {
|
|
953
|
+
createScope: (metadata) => {
|
|
954
|
+
const store = {
|
|
955
|
+
execution: {
|
|
956
|
+
...metadata,
|
|
957
|
+
...metadata.request ? { request: { ...metadata.request } } : {}
|
|
958
|
+
},
|
|
959
|
+
executionHandle: void 0
|
|
960
|
+
};
|
|
961
|
+
bindExecutionHandle(collector, store);
|
|
962
|
+
return {
|
|
963
|
+
run: (callback) => storage.run(store, callback),
|
|
964
|
+
getErrorState: () => void 0,
|
|
965
|
+
observeError: () => inertErrorObservation(),
|
|
966
|
+
finish: (next) => {
|
|
967
|
+
if (next) {
|
|
968
|
+
mergeMetadata(store, next);
|
|
969
|
+
bindExecutionHandle(collector, store);
|
|
970
|
+
}
|
|
971
|
+
},
|
|
972
|
+
mergeMetadata: (next) => {
|
|
973
|
+
mergeMetadata(store, next);
|
|
974
|
+
bindExecutionHandle(collector, store);
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
},
|
|
978
|
+
getErrorState: () => void 0,
|
|
979
|
+
runFunction: (definition, args, callback) => runPrepared(planFor(definitionOf(definition)), args, callback),
|
|
980
|
+
runFunctionPlans: (plans, planIndex, args, callback) => {
|
|
981
|
+
const plan = prepareEncoded(plans)[planIndex];
|
|
982
|
+
return plan ? runPrepared(plan, args, callback) : callback();
|
|
983
|
+
},
|
|
984
|
+
prepareFunctionPlans: (plans) => prepareEncoded(plans),
|
|
985
|
+
runPreparedFunction: runPrepared,
|
|
986
|
+
enterPreparedFunction: (plan) => metricsHandle(collector, plan, currentHandle()),
|
|
987
|
+
trace,
|
|
988
|
+
getStats: () => emptyStats(),
|
|
989
|
+
close: () => {
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
};
|
|
993
|
+
|
|
673
994
|
// src/execution-recorder/adaptive-recording-options.ts
|
|
674
995
|
var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
|
|
675
996
|
var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
|
|
@@ -746,45 +1067,6 @@ var createDynamicDurationSampleBuckets = (options) => {
|
|
|
746
1067
|
};
|
|
747
1068
|
};
|
|
748
1069
|
|
|
749
|
-
// src/execution-recorder/error-observation.ts
|
|
750
|
-
var bindings = /* @__PURE__ */ new WeakMap();
|
|
751
|
-
var mintErrorObservation = (binding) => {
|
|
752
|
-
const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
753
|
-
bindings.set(observation, binding);
|
|
754
|
-
return observation;
|
|
755
|
-
};
|
|
756
|
-
var bindingForObservation = (value) => {
|
|
757
|
-
if (typeof value !== "object" || value === null) return void 0;
|
|
758
|
-
return bindings.get(value);
|
|
759
|
-
};
|
|
760
|
-
var inertErrorObservation = () => {
|
|
761
|
-
return Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
762
|
-
};
|
|
763
|
-
|
|
764
|
-
// src/execution-recorder/execution-identity.ts
|
|
765
|
-
var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
|
|
766
|
-
var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
|
|
767
|
-
var trimmed = (value) => typeof value === "string" ? value.trim() : "";
|
|
768
|
-
var boundedKey = (key) => {
|
|
769
|
-
return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
|
|
770
|
-
};
|
|
771
|
-
var executionTypeKey = (metadata) => {
|
|
772
|
-
if (metadata.kind === "http") {
|
|
773
|
-
const method = trimmed(metadata.request?.method).toUpperCase();
|
|
774
|
-
const route = trimmed(metadata.request?.route);
|
|
775
|
-
if (!method || !route) return void 0;
|
|
776
|
-
if (route.includes("?") || route.includes("://")) return void 0;
|
|
777
|
-
return boundedKey(`http:${method}:${route}`);
|
|
778
|
-
}
|
|
779
|
-
if (!NAMED_KINDS.has(metadata.kind)) return void 0;
|
|
780
|
-
const name = trimmed(metadata.name);
|
|
781
|
-
if (!name) return void 0;
|
|
782
|
-
return boundedKey(`${metadata.kind}:${name}`);
|
|
783
|
-
};
|
|
784
|
-
var isHttpClientErrorStatus = (status) => {
|
|
785
|
-
return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
|
|
786
|
-
};
|
|
787
|
-
|
|
788
1070
|
// src/execution-recorder/execution-journal.ts
|
|
789
1071
|
var KIND_ENTER = 1;
|
|
790
1072
|
var KIND_EXIT = 2;
|
|
@@ -1184,10 +1466,6 @@ var ExecutionJournalPool = class {
|
|
|
1184
1466
|
}
|
|
1185
1467
|
};
|
|
1186
1468
|
|
|
1187
|
-
// src/execution-recorder/function-plan.ts
|
|
1188
|
-
var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
|
|
1189
|
-
var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
|
|
1190
|
-
|
|
1191
1469
|
// src/execution-recorder/publish-runtime-state.ts
|
|
1192
1470
|
var measured = (value) => typeof value === "number";
|
|
1193
1471
|
var eventsAreFullyTimed = (events) => {
|
|
@@ -2686,7 +2964,7 @@ var manualFunctionDefinition = (value) => {
|
|
|
2686
2964
|
...located?.[4] ? { column: Number(located[4]) } : {}
|
|
2687
2965
|
} : void 0;
|
|
2688
2966
|
const definition = { name, ...source ? { source } : {} };
|
|
2689
|
-
return { ...definition, functionId:
|
|
2967
|
+
return { ...definition, functionId: runtimeFunctionId3(definition) };
|
|
2690
2968
|
};
|
|
2691
2969
|
var normalizeFunctionDefinition = (value) => typeof value === "string" ? manualFunctionDefinition(value) : value;
|
|
2692
2970
|
var elapsedMs2 = (startedAtNs, endedAtNs = process.hrtime.bigint()) => Number(endedAtNs - startedAtNs) / 1e6;
|
|
@@ -2727,7 +3005,7 @@ var observeRecordedCallback = function __rasputinHandleRun__3(recording, recorde
|
|
|
2727
3005
|
recordExitWork(phaseTimingEnabled ? process.hrtime.bigint() : recorderStartedAtNs);
|
|
2728
3006
|
return result;
|
|
2729
3007
|
};
|
|
2730
|
-
var
|
|
3008
|
+
var emptyStats2 = {
|
|
2731
3009
|
functionCallsObserved: 0,
|
|
2732
3010
|
functionCallsCaptured: 0,
|
|
2733
3011
|
functionCallsExcluded: 0,
|
|
@@ -2788,7 +3066,7 @@ var noOpExecution = {
|
|
|
2788
3066
|
resume: (value) => value
|
|
2789
3067
|
}),
|
|
2790
3068
|
trace: (_functionId, fn) => fn,
|
|
2791
|
-
getStats: () => ({ ...
|
|
3069
|
+
getStats: () => ({ ...emptyStats2 }),
|
|
2792
3070
|
close: () => {
|
|
2793
3071
|
}
|
|
2794
3072
|
};
|
|
@@ -2822,7 +3100,16 @@ var newSuppression = (group, parentCallId, startedAtNs, endedAtNs, timed) => {
|
|
|
2822
3100
|
var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
|
|
2823
3101
|
var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
|
|
2824
3102
|
var createExecutionRecorder = (options, hooks = {}) => {
|
|
2825
|
-
if (!options?.enabled)
|
|
3103
|
+
if (!options?.enabled) {
|
|
3104
|
+
return hooks.functionMetrics ? createMetricsOnlyRuntime(hooks.functionMetrics) : noOpExecution;
|
|
3105
|
+
}
|
|
3106
|
+
const functionMetrics = hooks.functionMetrics;
|
|
3107
|
+
const bindMetricsExecution = (recording) => {
|
|
3108
|
+
if (!functionMetrics) return;
|
|
3109
|
+
recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
|
|
3110
|
+
executionTypeKey(recording.execution)
|
|
3111
|
+
);
|
|
3112
|
+
};
|
|
2826
3113
|
warnIfMissingAsyncContextFrame();
|
|
2827
3114
|
const adaptiveEnabled = options.adaptive?.enabled === true;
|
|
2828
3115
|
const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
|
|
@@ -2844,7 +3131,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
2844
3131
|
if (!key) return false;
|
|
2845
3132
|
return keyIsActive(snapshot, key, atMs);
|
|
2846
3133
|
};
|
|
2847
|
-
const storage = new
|
|
3134
|
+
const storage = new AsyncLocalStorage2();
|
|
2848
3135
|
const currentStore = () => {
|
|
2849
3136
|
try {
|
|
2850
3137
|
return storage.getStore();
|
|
@@ -3095,7 +3382,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3095
3382
|
functionId: definition.functionId,
|
|
3096
3383
|
excluded: excludesSource(definition),
|
|
3097
3384
|
estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
|
|
3098
|
-
omitCallValues: false
|
|
3385
|
+
omitCallValues: false,
|
|
3386
|
+
metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
|
|
3099
3387
|
});
|
|
3100
3388
|
internedPlans.set(definition.functionId, plan);
|
|
3101
3389
|
return plan;
|
|
@@ -3105,13 +3393,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3105
3393
|
if (cached) return cached;
|
|
3106
3394
|
const prepared = plans.map((encoded) => {
|
|
3107
3395
|
const definition = definitionFromEncodedPlan(encoded);
|
|
3396
|
+
const params = paramsForRuntimeFunction(definition.functionId);
|
|
3397
|
+
const withParams = params && params.length > 0 ? { ...definition, params } : definition;
|
|
3108
3398
|
return storePlan({
|
|
3109
3399
|
runtimePlanId: nextRuntimePlanId++,
|
|
3110
|
-
definition,
|
|
3111
|
-
functionId:
|
|
3112
|
-
excluded: excludesSource(
|
|
3113
|
-
estimatedCallBytes: estimatedCallBytesFor(
|
|
3114
|
-
omitCallValues: encodedPlanOmitsCallValues(encoded)
|
|
3400
|
+
definition: withParams,
|
|
3401
|
+
functionId: withParams.functionId,
|
|
3402
|
+
excluded: excludesSource(withParams),
|
|
3403
|
+
estimatedCallBytes: estimatedCallBytesFor(withParams.functionId),
|
|
3404
|
+
omitCallValues: encodedPlanOmitsCallValues(encoded),
|
|
3405
|
+
metricsDeclaration: functionMetricDeclarationFor(withParams.functionId)
|
|
3115
3406
|
});
|
|
3116
3407
|
});
|
|
3117
3408
|
preparedModules.set(plans, prepared);
|
|
@@ -3630,7 +3921,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3630
3921
|
}
|
|
3631
3922
|
const recorderStartedAtNs = process.hrtime.bigint();
|
|
3632
3923
|
recording.finished = true;
|
|
3633
|
-
if (metadata)
|
|
3924
|
+
if (metadata) {
|
|
3925
|
+
mergeExecutionMetadata(recording.execution, metadata);
|
|
3926
|
+
bindMetricsExecution(recording);
|
|
3927
|
+
}
|
|
3634
3928
|
stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
|
|
3635
3929
|
if (recording.runFailed && !recording.hasError) {
|
|
3636
3930
|
retainFailure(recording);
|
|
@@ -3699,6 +3993,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3699
3993
|
sessionCaptureSnapshot
|
|
3700
3994
|
};
|
|
3701
3995
|
if (identityComplete) tryAdmitLiveSession(recording);
|
|
3996
|
+
bindMetricsExecution(recording);
|
|
3702
3997
|
stats.activeExecutions++;
|
|
3703
3998
|
stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
|
|
3704
3999
|
liveRecordings.push(recording);
|
|
@@ -3750,6 +4045,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3750
4045
|
try {
|
|
3751
4046
|
mergeExecutionMetadata(recording.execution, nextMetadata);
|
|
3752
4047
|
completeIdentityFromSnapshot(recording);
|
|
4048
|
+
bindMetricsExecution(recording);
|
|
3753
4049
|
} catch {
|
|
3754
4050
|
}
|
|
3755
4051
|
}
|
|
@@ -3766,9 +4062,22 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3766
4062
|
}
|
|
3767
4063
|
};
|
|
3768
4064
|
const runPreparedFunctionFromStore = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
|
|
4065
|
+
const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
|
|
4066
|
+
const executionHandle = store?.recording.metricsExecutionHandle;
|
|
4067
|
+
const startedNs = startMetricsCall(functionMetrics, functionHandle, executionHandle);
|
|
4068
|
+
const settle = (value, failed) => {
|
|
4069
|
+
if (!functionMetrics || startedNs === void 0 || functionHandle === void 0 || executionHandle === void 0) {
|
|
4070
|
+
return;
|
|
4071
|
+
}
|
|
4072
|
+
if (failed) {
|
|
4073
|
+
finishMetricsCall(functionMetrics, functionHandle, executionHandle, startedNs, true);
|
|
4074
|
+
return;
|
|
4075
|
+
}
|
|
4076
|
+
completeMetricsResult(functionMetrics, functionHandle, executionHandle, startedNs, value);
|
|
4077
|
+
};
|
|
3769
4078
|
let startedCallback = false;
|
|
3770
4079
|
try {
|
|
3771
|
-
|
|
4080
|
+
const result = runPreparedFunctionFromStoreInner(
|
|
3772
4081
|
store,
|
|
3773
4082
|
plan,
|
|
3774
4083
|
args,
|
|
@@ -3778,9 +4087,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3778
4087
|
},
|
|
3779
4088
|
omitValues
|
|
3780
4089
|
);
|
|
4090
|
+
settle(result, false);
|
|
4091
|
+
return result;
|
|
3781
4092
|
} catch (error) {
|
|
3782
|
-
if (startedCallback)
|
|
3783
|
-
|
|
4093
|
+
if (startedCallback) {
|
|
4094
|
+
settle(error, true);
|
|
4095
|
+
throw error;
|
|
4096
|
+
}
|
|
4097
|
+
const result = callback();
|
|
4098
|
+
settle(result, false);
|
|
4099
|
+
return result;
|
|
3784
4100
|
}
|
|
3785
4101
|
};
|
|
3786
4102
|
const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
|
|
@@ -3985,6 +4301,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
3985
4301
|
this.group = group;
|
|
3986
4302
|
this.captureDroppedThrow = captureDroppedThrow;
|
|
3987
4303
|
this.callerClaimed = false;
|
|
4304
|
+
this.metricsOpen = false;
|
|
4305
|
+
this.metricsFailed = false;
|
|
4306
|
+
this.metricsFunctionHandle = 0;
|
|
4307
|
+
this.metricsExecutionHandle = 0;
|
|
4308
|
+
this.metricsStartedNs = 0n;
|
|
3988
4309
|
}
|
|
3989
4310
|
claimCaller() {
|
|
3990
4311
|
if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
|
|
@@ -4019,6 +4340,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4019
4340
|
try {
|
|
4020
4341
|
if (this.status === "failed") return;
|
|
4021
4342
|
this.status = "failed";
|
|
4343
|
+
this.metricsFailed = true;
|
|
4022
4344
|
if (this.mode === "captured") writeCapturedThrow(this, error);
|
|
4023
4345
|
else if (this.mode === "suppressed" && this.plan) {
|
|
4024
4346
|
captureCompletedThrow(
|
|
@@ -4047,18 +4369,38 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4047
4369
|
}
|
|
4048
4370
|
}
|
|
4049
4371
|
end() {
|
|
4372
|
+
let endedAtNs;
|
|
4373
|
+
if (this.metricsOpen && functionMetrics) {
|
|
4374
|
+
this.metricsOpen = false;
|
|
4375
|
+
try {
|
|
4376
|
+
endedAtNs = readCallClock();
|
|
4377
|
+
finishMetricsCall(
|
|
4378
|
+
functionMetrics,
|
|
4379
|
+
this.metricsFunctionHandle,
|
|
4380
|
+
this.metricsExecutionHandle,
|
|
4381
|
+
this.metricsStartedNs,
|
|
4382
|
+
this.metricsFailed,
|
|
4383
|
+
endedAtNs
|
|
4384
|
+
);
|
|
4385
|
+
} catch {
|
|
4386
|
+
}
|
|
4387
|
+
}
|
|
4050
4388
|
if (this.mode === "expired") return;
|
|
4051
4389
|
try {
|
|
4052
4390
|
if (this.status !== "failed") {
|
|
4053
4391
|
if (this.mode === "captured") {
|
|
4054
|
-
writeCapturedExit(
|
|
4392
|
+
writeCapturedExit(
|
|
4393
|
+
this,
|
|
4394
|
+
this.status === "left" ? this.pendingReturn : void 0,
|
|
4395
|
+
endedAtNs
|
|
4396
|
+
);
|
|
4055
4397
|
} else if (this.mode === "suppressed" && this.group) {
|
|
4056
4398
|
recordSuppressedCall(
|
|
4057
4399
|
this.recording,
|
|
4058
4400
|
this.group,
|
|
4059
4401
|
this.parentCallId,
|
|
4060
4402
|
this.startedAtNs,
|
|
4061
|
-
this.timed ? readCallClock() : 0n,
|
|
4403
|
+
this.timed ? endedAtNs ?? readCallClock() : 0n,
|
|
4062
4404
|
this.timed
|
|
4063
4405
|
);
|
|
4064
4406
|
} else if (this.mode === "dropped") {
|
|
@@ -4131,9 +4473,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4131
4473
|
const expectStore = (frame, expected) => {
|
|
4132
4474
|
if (currentStore() !== expected && frame.plan) degradeAttribution(frame.recording, frame.plan);
|
|
4133
4475
|
};
|
|
4134
|
-
const writeCapturedExit = (frame, value) => {
|
|
4476
|
+
const writeCapturedExit = (frame, value, completedAtNs) => {
|
|
4135
4477
|
if (!frame.recording.journal) return;
|
|
4136
|
-
const endedAtNs = frame.timed ? readCallClock() : void 0;
|
|
4478
|
+
const endedAtNs = frame.timed ? completedAtNs ?? readCallClock() : void 0;
|
|
4137
4479
|
const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
|
|
4138
4480
|
if (endedAtNs !== void 0) {
|
|
4139
4481
|
frame.recording.journal.finishCall(
|
|
@@ -4168,6 +4510,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4168
4510
|
stats.functionCallsCaptured++;
|
|
4169
4511
|
capturedError.commit();
|
|
4170
4512
|
};
|
|
4513
|
+
const armCallFrameMetrics = (frame, plan) => {
|
|
4514
|
+
if (!functionMetrics || plan.excluded) return;
|
|
4515
|
+
const functionHandle = internPreparedMetrics(functionMetrics, plan);
|
|
4516
|
+
const reuseStart = frame.timed && frame.startedAtNs !== 0n ? frame.startedAtNs : void 0;
|
|
4517
|
+
const startedNs = startMetricsCall(
|
|
4518
|
+
functionMetrics,
|
|
4519
|
+
functionHandle,
|
|
4520
|
+
frame.recording.metricsExecutionHandle,
|
|
4521
|
+
reuseStart
|
|
4522
|
+
);
|
|
4523
|
+
if (startedNs === void 0 || functionHandle === void 0) return;
|
|
4524
|
+
const executionHandle = frame.recording.metricsExecutionHandle;
|
|
4525
|
+
if (executionHandle === void 0) return;
|
|
4526
|
+
frame.metricsOpen = true;
|
|
4527
|
+
frame.metricsFunctionHandle = functionHandle;
|
|
4528
|
+
frame.metricsExecutionHandle = executionHandle;
|
|
4529
|
+
frame.metricsStartedNs = startedNs;
|
|
4530
|
+
};
|
|
4171
4531
|
const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
|
|
4172
4532
|
const frame = new CallFrame(
|
|
4173
4533
|
mode,
|
|
@@ -4186,6 +4546,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4186
4546
|
);
|
|
4187
4547
|
frame.claimCaller();
|
|
4188
4548
|
enterStore(frame, parentStore);
|
|
4549
|
+
armCallFrameMetrics(frame, plan);
|
|
4189
4550
|
return frame;
|
|
4190
4551
|
};
|
|
4191
4552
|
const enterPreparedFunctionFromStore = (store, plan, args, omitValues) => {
|
|
@@ -4197,7 +4558,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4197
4558
|
if (store.recording.finished) {
|
|
4198
4559
|
if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
|
|
4199
4560
|
const expiredStore = { recording: store.recording };
|
|
4200
|
-
|
|
4561
|
+
const expired = new CallFrame(
|
|
4201
4562
|
"expired",
|
|
4202
4563
|
store.recording,
|
|
4203
4564
|
expiredStore,
|
|
@@ -4212,6 +4573,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4212
4573
|
void 0,
|
|
4213
4574
|
false
|
|
4214
4575
|
);
|
|
4576
|
+
armCallFrameMetrics(expired, plan);
|
|
4577
|
+
return expired;
|
|
4215
4578
|
}
|
|
4216
4579
|
stats.functionCallsObserved++;
|
|
4217
4580
|
const recording = store.recording;
|
|
@@ -4236,6 +4599,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4236
4599
|
false
|
|
4237
4600
|
);
|
|
4238
4601
|
enterStore(frame, excludedStore);
|
|
4602
|
+
armCallFrameMetrics(frame, plan);
|
|
4239
4603
|
return frame;
|
|
4240
4604
|
}
|
|
4241
4605
|
recording.inFlightCalls++;
|
|
@@ -4349,6 +4713,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4349
4713
|
false
|
|
4350
4714
|
);
|
|
4351
4715
|
enterStore(captured, callStore);
|
|
4716
|
+
armCallFrameMetrics(captured, plan);
|
|
4352
4717
|
return captured;
|
|
4353
4718
|
};
|
|
4354
4719
|
const runPreparedFunction = (plan, args, callback, omitValues) => {
|
|
@@ -4389,8 +4754,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
|
|
|
4389
4754
|
};
|
|
4390
4755
|
const prepareFunctionPlans = (plans) => preparedPlansFor(plans);
|
|
4391
4756
|
function trace(input, fn) {
|
|
4392
|
-
const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId:
|
|
4757
|
+
const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId3(input) };
|
|
4393
4758
|
const plan = preparePlan(definition);
|
|
4759
|
+
plan.metricsDeclaration ??= functionMetricsTraceDeclaration3({
|
|
4760
|
+
runtimeId: definition.functionId
|
|
4761
|
+
});
|
|
4394
4762
|
return function __rasputinHandleRun__4(...args) {
|
|
4395
4763
|
if (new.target) {
|
|
4396
4764
|
throw new TypeError("execution.trace() wraps function calls, not constructors");
|
|
@@ -4683,10 +5051,9 @@ var abortFrom = (parent, child) => {
|
|
|
4683
5051
|
return () => parent.removeEventListener("abort", onAbort);
|
|
4684
5052
|
};
|
|
4685
5053
|
var createExecutionRecordingCoordinator = (options) => {
|
|
4686
|
-
const environment =
|
|
5054
|
+
const environment = options.environment;
|
|
4687
5055
|
const nowMs = () => options.nowMs?.() ?? Date.now();
|
|
4688
5056
|
const fetchFn = options.fetch ?? defaultIngestFetch();
|
|
4689
|
-
const networkEnabled = environment.length > 0;
|
|
4690
5057
|
const instanceId = crypto.randomUUID();
|
|
4691
5058
|
const startedAt = /* @__PURE__ */ new Date();
|
|
4692
5059
|
const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
|
|
@@ -4939,8 +5306,7 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
4939
5306
|
}
|
|
4940
5307
|
};
|
|
4941
5308
|
const kickNotify = () => {
|
|
4942
|
-
if (
|
|
4943
|
-
return;
|
|
5309
|
+
if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
|
|
4944
5310
|
void drainNotifies(notifySignal());
|
|
4945
5311
|
};
|
|
4946
5312
|
const rememberCatalog = (key, atMs) => {
|
|
@@ -5019,7 +5385,7 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
5019
5385
|
return entries;
|
|
5020
5386
|
};
|
|
5021
5387
|
const syncOnce = async (signal) => {
|
|
5022
|
-
if (
|
|
5388
|
+
if (closed) return;
|
|
5023
5389
|
const types2 = catalogTypes();
|
|
5024
5390
|
try {
|
|
5025
5391
|
const { response, body: payload } = await postJson(
|
|
@@ -5172,7 +5538,7 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
5172
5538
|
}
|
|
5173
5539
|
};
|
|
5174
5540
|
const kickRecordings = () => {
|
|
5175
|
-
if (
|
|
5541
|
+
if (closed || closing || recordings.length === 0) return;
|
|
5176
5542
|
if (recordingPump) return;
|
|
5177
5543
|
const running = drainRecordings(recordingSignal());
|
|
5178
5544
|
recordingPump = running;
|
|
@@ -5190,7 +5556,7 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
5190
5556
|
if (existing !== void 0 && existing > atMs) return;
|
|
5191
5557
|
cache.set(key, window.expiresAtMs);
|
|
5192
5558
|
trimCache();
|
|
5193
|
-
if (
|
|
5559
|
+
if (window.expiresAtMs <= atMs) return;
|
|
5194
5560
|
if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
|
|
5195
5561
|
for (const oldest of pending.keys()) {
|
|
5196
5562
|
if (oldest !== sendingKey) {
|
|
@@ -5235,22 +5601,20 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
5235
5601
|
recordings.push(payload);
|
|
5236
5602
|
kickRecordings();
|
|
5237
5603
|
};
|
|
5238
|
-
|
|
5239
|
-
|
|
5240
|
-
|
|
5241
|
-
|
|
5242
|
-
pollStartTimer =
|
|
5243
|
-
|
|
5604
|
+
const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
5605
|
+
const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
|
|
5606
|
+
const delay = interval + Math.floor(Math.random() * jitterMax);
|
|
5607
|
+
pollStartTimer = setTimeout(() => {
|
|
5608
|
+
pollStartTimer = void 0;
|
|
5609
|
+
if (closed || closing) return;
|
|
5610
|
+
void runSyncOnce(pollSignal());
|
|
5611
|
+
pollTimer = setInterval(() => {
|
|
5244
5612
|
if (closed || closing) return;
|
|
5245
5613
|
void runSyncOnce(pollSignal());
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
pollTimer.unref?.();
|
|
5251
|
-
}, delay);
|
|
5252
|
-
pollStartTimer.unref?.();
|
|
5253
|
-
}
|
|
5614
|
+
}, interval);
|
|
5615
|
+
pollTimer.unref?.();
|
|
5616
|
+
}, delay);
|
|
5617
|
+
pollStartTimer.unref?.();
|
|
5254
5618
|
const stopTimers = () => {
|
|
5255
5619
|
if (pollStartTimer) {
|
|
5256
5620
|
clearTimeout(pollStartTimer);
|
|
@@ -5274,7 +5638,7 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
5274
5638
|
lastAdaptiveFailureKind: lastFailureKind
|
|
5275
5639
|
}),
|
|
5276
5640
|
flush: async (timeoutMs = 2e3) => {
|
|
5277
|
-
if (
|
|
5641
|
+
if (closed || closing) return;
|
|
5278
5642
|
const flushAbort = new AbortController();
|
|
5279
5643
|
const onAbort = () => interruptWork();
|
|
5280
5644
|
flushAbort.signal.addEventListener("abort", onAbort, { once: true });
|
|
@@ -5299,7 +5663,7 @@ var createExecutionRecordingCoordinator = (options) => {
|
|
|
5299
5663
|
interruptWork();
|
|
5300
5664
|
}, 2e3);
|
|
5301
5665
|
try {
|
|
5302
|
-
|
|
5666
|
+
await runSyncOnce(deadline.signal);
|
|
5303
5667
|
if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
|
|
5304
5668
|
await joinUntil(recordingPump, deadline.signal);
|
|
5305
5669
|
if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
|
|
@@ -5322,10 +5686,11 @@ var bindAdaptiveRecorder = (input) => {
|
|
|
5322
5686
|
dsn: input.dsn,
|
|
5323
5687
|
projectApiKey: input.projectApiKey,
|
|
5324
5688
|
apiUrl: input.apiUrl,
|
|
5325
|
-
release: input.release
|
|
5689
|
+
release: input.release,
|
|
5690
|
+
environment: input.environment
|
|
5326
5691
|
});
|
|
5327
5692
|
const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
|
|
5328
|
-
environment:
|
|
5693
|
+
environment: activation.environment,
|
|
5329
5694
|
ingestToken: activation.ingestToken,
|
|
5330
5695
|
activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
|
|
5331
5696
|
syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
|
|
@@ -5338,21 +5703,1116 @@ var bindAdaptiveRecorder = (input) => {
|
|
|
5338
5703
|
mode: adaptiveEnabled ? "adaptive" : "full",
|
|
5339
5704
|
fetch: input.fetch
|
|
5340
5705
|
}) : void 0;
|
|
5706
|
+
const recorderHooks = {};
|
|
5707
|
+
if (coordinator) {
|
|
5708
|
+
recorderHooks.policySnapshot = coordinator.peek;
|
|
5709
|
+
recorderHooks.onQualifyingFailure = adaptiveEnabled ? coordinator.activate : void 0;
|
|
5710
|
+
recorderHooks.getStats = coordinator.getStats;
|
|
5711
|
+
recorderHooks.sessionCaptureSnapshot = coordinator.peekSessions;
|
|
5712
|
+
recorderHooks.consumeSession = coordinator.consumeSession;
|
|
5713
|
+
recorderHooks.observeExecutionType = coordinator.observeType;
|
|
5714
|
+
recorderHooks.onSessionRecording = coordinator.enqueueRecording;
|
|
5715
|
+
}
|
|
5716
|
+
if (input.functionMetrics) recorderHooks.functionMetrics = input.functionMetrics;
|
|
5341
5717
|
const runtime = createExecutionRecorder(
|
|
5342
5718
|
{ ...options, enabled: input.recorderEnabled },
|
|
5343
|
-
|
|
5344
|
-
policySnapshot: coordinator.peek,
|
|
5345
|
-
onQualifyingFailure: adaptiveEnabled ? coordinator.activate : void 0,
|
|
5346
|
-
getStats: coordinator.getStats,
|
|
5347
|
-
sessionCaptureSnapshot: coordinator.peekSessions,
|
|
5348
|
-
consumeSession: coordinator.consumeSession,
|
|
5349
|
-
observeExecutionType: coordinator.observeType,
|
|
5350
|
-
onSessionRecording: coordinator.enqueueRecording
|
|
5351
|
-
} : void 0
|
|
5719
|
+
recorderHooks
|
|
5352
5720
|
);
|
|
5353
5721
|
return { runtime, policy: coordinator };
|
|
5354
5722
|
};
|
|
5355
5723
|
|
|
5724
|
+
// src/function-metrics/bind-function-metrics.ts
|
|
5725
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
5726
|
+
import {
|
|
5727
|
+
defaultIngestFetch as defaultIngestFetch2,
|
|
5728
|
+
resolveEndpointUrls as resolveEndpointUrls3
|
|
5729
|
+
} from "@rasputin-ai/core";
|
|
5730
|
+
|
|
5731
|
+
// src/function-metrics/function-metrics-collector.ts
|
|
5732
|
+
import {
|
|
5733
|
+
durationHistogramBucket,
|
|
5734
|
+
FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT,
|
|
5735
|
+
FUNCTION_METRICS_MAX_ACTIVE_SERIES,
|
|
5736
|
+
FUNCTION_METRICS_MAX_BUFFERED_MS,
|
|
5737
|
+
FUNCTION_METRICS_MAX_EXECUTION_TYPES,
|
|
5738
|
+
FUNCTION_METRICS_MAX_FUNCTIONS,
|
|
5739
|
+
FUNCTION_METRICS_MAX_MINUTE_ROWS,
|
|
5740
|
+
FUNCTION_METRICS_MAX_STATE_BYTES,
|
|
5741
|
+
FUNCTION_METRICS_MINUTE_MS,
|
|
5742
|
+
functionIdentityKey,
|
|
5743
|
+
isCanonicalFunctionMetricsExecutionKey
|
|
5744
|
+
} from "@rasputin-ai/core";
|
|
5745
|
+
|
|
5746
|
+
// src/function-metrics/function-metrics-batches.ts
|
|
5747
|
+
import { randomUUID } from "node:crypto";
|
|
5748
|
+
import {
|
|
5749
|
+
FUNCTION_METRICS_MEASUREMENT_FORMAT,
|
|
5750
|
+
FUNCTION_METRICS_SCHEMA_VERSION
|
|
5751
|
+
} from "@rasputin-ai/core";
|
|
5752
|
+
var emptyCoverage = (buckets) => ({
|
|
5753
|
+
covered_bucket_starts: buckets,
|
|
5754
|
+
skipped_unresolved_execution_type: 0,
|
|
5755
|
+
dropped_active_series: 0,
|
|
5756
|
+
dropped_byte_budget: 0,
|
|
5757
|
+
dropped_queue_budget: 0,
|
|
5758
|
+
dropped_late_completion: 0,
|
|
5759
|
+
dropped_unexportable: 0
|
|
5760
|
+
});
|
|
5761
|
+
var bucketStart = (minute) => new Date(minute * 6e4).toISOString();
|
|
5762
|
+
var sparseHistogram = (histogram) => {
|
|
5763
|
+
const cells = [];
|
|
5764
|
+
for (let index = 0; index < histogram.length; index += 1) {
|
|
5765
|
+
const count = histogram[index] ?? 0;
|
|
5766
|
+
if (count > 0) cells.push([index, count]);
|
|
5767
|
+
}
|
|
5768
|
+
return cells;
|
|
5769
|
+
};
|
|
5770
|
+
var toMinute = (row, functionIndex, executionTypeIndex) => ({
|
|
5771
|
+
function_index: functionIndex,
|
|
5772
|
+
execution_type_index: executionTypeIndex,
|
|
5773
|
+
bucket_start: bucketStart(row.minute),
|
|
5774
|
+
started_calls: row.series.started,
|
|
5775
|
+
completed_calls: row.series.completed,
|
|
5776
|
+
failed_calls: row.series.failed,
|
|
5777
|
+
duration_sample_count: row.series.sampleCount,
|
|
5778
|
+
duration_sample_sum_us: row.series.sampleSumUs,
|
|
5779
|
+
duration_sample_min_us: row.series.sampleMinUs,
|
|
5780
|
+
duration_sample_max_us: row.series.sampleMaxUs,
|
|
5781
|
+
duration_histogram: sparseHistogram(row.series.histogram),
|
|
5782
|
+
invalid_timing_count: row.series.invalidTiming
|
|
5783
|
+
});
|
|
5784
|
+
var rowsFromQueue = (queued) => {
|
|
5785
|
+
const rows = [];
|
|
5786
|
+
for (const queuedMinute of queued) {
|
|
5787
|
+
for (const [functionHandle, byExecution] of queuedMinute.series) {
|
|
5788
|
+
for (const [executionHandle, series] of byExecution) {
|
|
5789
|
+
rows.push({
|
|
5790
|
+
minute: queuedMinute.minute,
|
|
5791
|
+
functionHandle,
|
|
5792
|
+
executionHandle,
|
|
5793
|
+
series
|
|
5794
|
+
});
|
|
5795
|
+
}
|
|
5796
|
+
}
|
|
5797
|
+
}
|
|
5798
|
+
rows.sort((left, right) => {
|
|
5799
|
+
if (left.minute !== right.minute) return left.minute - right.minute;
|
|
5800
|
+
if (left.functionHandle !== right.functionHandle) {
|
|
5801
|
+
return left.functionHandle - right.functionHandle;
|
|
5802
|
+
}
|
|
5803
|
+
return left.executionHandle - right.executionHandle;
|
|
5804
|
+
});
|
|
5805
|
+
return rows;
|
|
5806
|
+
};
|
|
5807
|
+
var chunkRows = (rows, maxFunctions, maxExecutionTypes, maxMinuteRows) => {
|
|
5808
|
+
const chunks = [];
|
|
5809
|
+
let current = [];
|
|
5810
|
+
let functions = /* @__PURE__ */ new Set();
|
|
5811
|
+
let executionTypes = /* @__PURE__ */ new Set();
|
|
5812
|
+
const flush = () => {
|
|
5813
|
+
if (current.length === 0) return;
|
|
5814
|
+
chunks.push(current);
|
|
5815
|
+
current = [];
|
|
5816
|
+
functions = /* @__PURE__ */ new Set();
|
|
5817
|
+
executionTypes = /* @__PURE__ */ new Set();
|
|
5818
|
+
};
|
|
5819
|
+
for (const row of rows) {
|
|
5820
|
+
const nextFunctions = functions.has(row.functionHandle) ? functions.size : functions.size + 1;
|
|
5821
|
+
const nextTypes = executionTypes.has(row.executionHandle) ? executionTypes.size : executionTypes.size + 1;
|
|
5822
|
+
const rowWouldOverflow = current.length >= maxMinuteRows || nextFunctions > maxFunctions || nextTypes > maxExecutionTypes;
|
|
5823
|
+
if (rowWouldOverflow) flush();
|
|
5824
|
+
current.push(row);
|
|
5825
|
+
functions.add(row.functionHandle);
|
|
5826
|
+
executionTypes.add(row.executionHandle);
|
|
5827
|
+
}
|
|
5828
|
+
flush();
|
|
5829
|
+
return chunks;
|
|
5830
|
+
};
|
|
5831
|
+
var batchForChunk = (draft, rows, coverage) => {
|
|
5832
|
+
const functionIndexes = /* @__PURE__ */ new Map();
|
|
5833
|
+
const executionIndexes = /* @__PURE__ */ new Map();
|
|
5834
|
+
const functions = [];
|
|
5835
|
+
const executionTypes = [];
|
|
5836
|
+
const minutes = [];
|
|
5837
|
+
for (const row of rows) {
|
|
5838
|
+
let functionIndex = functionIndexes.get(row.functionHandle);
|
|
5839
|
+
if (functionIndex === void 0) {
|
|
5840
|
+
const declaration = draft.functions[row.functionHandle];
|
|
5841
|
+
if (!declaration) continue;
|
|
5842
|
+
functionIndex = functions.length;
|
|
5843
|
+
functionIndexes.set(row.functionHandle, functionIndex);
|
|
5844
|
+
functions.push(declaration);
|
|
5845
|
+
}
|
|
5846
|
+
let executionTypeIndex = executionIndexes.get(row.executionHandle);
|
|
5847
|
+
if (executionTypeIndex === void 0) {
|
|
5848
|
+
const executionKey = draft.executionKeys[row.executionHandle];
|
|
5849
|
+
if (!executionKey) continue;
|
|
5850
|
+
executionTypeIndex = executionTypes.length;
|
|
5851
|
+
executionIndexes.set(row.executionHandle, executionTypeIndex);
|
|
5852
|
+
executionTypes.push({ execution_key: executionKey });
|
|
5853
|
+
}
|
|
5854
|
+
minutes.push(toMinute(row, functionIndex, executionTypeIndex));
|
|
5855
|
+
}
|
|
5856
|
+
const covered = [...new Set(minutes.map((minute) => minute.bucket_start))].sort();
|
|
5857
|
+
return {
|
|
5858
|
+
schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
|
|
5859
|
+
measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
|
|
5860
|
+
producer_id: draft.producerId,
|
|
5861
|
+
batch_id: draft.batchId(),
|
|
5862
|
+
environment: draft.environment,
|
|
5863
|
+
release: draft.release,
|
|
5864
|
+
functions,
|
|
5865
|
+
execution_types: executionTypes,
|
|
5866
|
+
minutes,
|
|
5867
|
+
coverage: { ...coverage, covered_bucket_starts: covered }
|
|
5868
|
+
};
|
|
5869
|
+
};
|
|
5870
|
+
var functionMetricsBatchesFromQueue = (draft) => {
|
|
5871
|
+
const rows = rowsFromQueue(draft.queued);
|
|
5872
|
+
if (rows.length === 0) {
|
|
5873
|
+
const hasLoss = Object.entries(draft.coverage).some(([key, value]) => {
|
|
5874
|
+
return key !== "covered_bucket_starts" && typeof value === "number" && value > 0;
|
|
5875
|
+
});
|
|
5876
|
+
if (!hasLoss) return [];
|
|
5877
|
+
return [
|
|
5878
|
+
{
|
|
5879
|
+
schema_version: FUNCTION_METRICS_SCHEMA_VERSION,
|
|
5880
|
+
measurement_format: FUNCTION_METRICS_MEASUREMENT_FORMAT,
|
|
5881
|
+
producer_id: draft.producerId,
|
|
5882
|
+
batch_id: draft.batchId(),
|
|
5883
|
+
environment: draft.environment,
|
|
5884
|
+
release: draft.release,
|
|
5885
|
+
functions: [],
|
|
5886
|
+
execution_types: [],
|
|
5887
|
+
minutes: [],
|
|
5888
|
+
coverage: draft.coverage
|
|
5889
|
+
}
|
|
5890
|
+
];
|
|
5891
|
+
}
|
|
5892
|
+
const chunks = chunkRows(rows, draft.maxFunctions, draft.maxExecutionTypes, draft.maxMinuteRows);
|
|
5893
|
+
return chunks.map(
|
|
5894
|
+
(chunk, index) => batchForChunk(draft, chunk, index === 0 ? draft.coverage : emptyCoverage([]))
|
|
5895
|
+
);
|
|
5896
|
+
};
|
|
5897
|
+
var newFunctionMetricsBatchId = () => randomUUID();
|
|
5898
|
+
|
|
5899
|
+
// src/function-metrics/function-metrics-collector.ts
|
|
5900
|
+
var SERIES_BYTES = 256;
|
|
5901
|
+
var HISTOGRAM_BYTES = FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT * 4;
|
|
5902
|
+
var DECLARATION_BYTES = 1024;
|
|
5903
|
+
var MAX_ELAPSED_NS = BigInt(Number.MAX_SAFE_INTEGER);
|
|
5904
|
+
var defaultLimits = () => ({
|
|
5905
|
+
maxActiveSeries: FUNCTION_METRICS_MAX_ACTIVE_SERIES,
|
|
5906
|
+
maxStateBytes: FUNCTION_METRICS_MAX_STATE_BYTES,
|
|
5907
|
+
maxQueuedMinutes: FUNCTION_METRICS_MAX_BUFFERED_MS / FUNCTION_METRICS_MINUTE_MS,
|
|
5908
|
+
maxFunctions: FUNCTION_METRICS_MAX_FUNCTIONS,
|
|
5909
|
+
maxExecutionTypes: FUNCTION_METRICS_MAX_EXECUTION_TYPES,
|
|
5910
|
+
maxMinuteRows: FUNCTION_METRICS_MAX_MINUTE_ROWS
|
|
5911
|
+
});
|
|
5912
|
+
var defaultClock = () => ({
|
|
5913
|
+
monotonicNs: () => process.hrtime.bigint(),
|
|
5914
|
+
wallTimeMs: () => Date.now()
|
|
5915
|
+
});
|
|
5916
|
+
var emptyCoverage2 = () => ({
|
|
5917
|
+
covered_bucket_starts: [],
|
|
5918
|
+
skipped_unresolved_execution_type: 0,
|
|
5919
|
+
dropped_active_series: 0,
|
|
5920
|
+
dropped_byte_budget: 0,
|
|
5921
|
+
dropped_queue_budget: 0,
|
|
5922
|
+
dropped_late_completion: 0,
|
|
5923
|
+
dropped_unexportable: 0
|
|
5924
|
+
});
|
|
5925
|
+
var note = (coverage, counter, amount = 1) => {
|
|
5926
|
+
const next = coverage[counter] + amount;
|
|
5927
|
+
coverage[counter] = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
|
|
5928
|
+
};
|
|
5929
|
+
var countSeries = (table) => {
|
|
5930
|
+
let count = 0;
|
|
5931
|
+
for (const byExecution of table.values()) count += byExecution.size;
|
|
5932
|
+
return count;
|
|
5933
|
+
};
|
|
5934
|
+
var tableBytes = (table) => {
|
|
5935
|
+
let bytes = 0;
|
|
5936
|
+
for (const byExecution of table.values()) {
|
|
5937
|
+
for (const series of byExecution.values()) bytes += series.bytes;
|
|
5938
|
+
}
|
|
5939
|
+
return bytes;
|
|
5940
|
+
};
|
|
5941
|
+
var discardedMarks = (table) => {
|
|
5942
|
+
let marks = 0;
|
|
5943
|
+
for (const byExecution of table.values()) {
|
|
5944
|
+
for (const series of byExecution.values()) {
|
|
5945
|
+
const next = marks + series.started + series.completed;
|
|
5946
|
+
marks = Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
|
|
5947
|
+
}
|
|
5948
|
+
}
|
|
5949
|
+
return marks;
|
|
5950
|
+
};
|
|
5951
|
+
var seriesHasMarks = (series) => series.started > 0 || series.completed > 0 || series.failed > 0 || series.sampleCount > 0 || series.invalidTiming > 0;
|
|
5952
|
+
var copySeries = (series) => ({
|
|
5953
|
+
...series,
|
|
5954
|
+
histogram: series.histogram.slice()
|
|
5955
|
+
});
|
|
5956
|
+
var resetSeries = (series) => {
|
|
5957
|
+
series.started = 0;
|
|
5958
|
+
series.completed = 0;
|
|
5959
|
+
series.failed = 0;
|
|
5960
|
+
series.sampleCount = 0;
|
|
5961
|
+
series.sampleSumUs = 0;
|
|
5962
|
+
series.sampleMinUs = null;
|
|
5963
|
+
series.sampleMaxUs = null;
|
|
5964
|
+
series.invalidTiming = 0;
|
|
5965
|
+
series.histogram.fill(0);
|
|
5966
|
+
};
|
|
5967
|
+
var snapshotAndReset = (table) => {
|
|
5968
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
5969
|
+
for (const [functionHandle, byExecution] of table) {
|
|
5970
|
+
const copied = /* @__PURE__ */ new Map();
|
|
5971
|
+
for (const [executionHandle, series] of byExecution) {
|
|
5972
|
+
if (seriesHasMarks(series)) copied.set(executionHandle, copySeries(series));
|
|
5973
|
+
resetSeries(series);
|
|
5974
|
+
}
|
|
5975
|
+
if (copied.size > 0) snapshot.set(functionHandle, copied);
|
|
5976
|
+
}
|
|
5977
|
+
return snapshot;
|
|
5978
|
+
};
|
|
5979
|
+
var declarationAccepted = (declaration) => {
|
|
5980
|
+
if (declaration.identity_kind !== declaration.descriptor.identity_kind) return false;
|
|
5981
|
+
if (declaration.logical_key !== functionIdentityKey(declaration.descriptor)) return false;
|
|
5982
|
+
if (declaration.descriptor.identity_kind === "release_scoped") {
|
|
5983
|
+
return declaration.descriptor.declaration_id === declaration.runtime_id;
|
|
5984
|
+
}
|
|
5985
|
+
return true;
|
|
5986
|
+
};
|
|
5987
|
+
var createFunctionMetricsCollector = (options) => {
|
|
5988
|
+
const limits = { ...defaultLimits(), ...options.limits };
|
|
5989
|
+
const clock = options.clock ?? defaultClock();
|
|
5990
|
+
const batchId = options.batchId ?? newFunctionMetricsBatchId;
|
|
5991
|
+
const coverage = emptyCoverage2();
|
|
5992
|
+
const functions = [];
|
|
5993
|
+
const functionHandleByRuntimeId = /* @__PURE__ */ new Map();
|
|
5994
|
+
const executionKeys = [];
|
|
5995
|
+
const executionHandleByKey = /* @__PURE__ */ new Map();
|
|
5996
|
+
const active = /* @__PURE__ */ new Map();
|
|
5997
|
+
const queue = [];
|
|
5998
|
+
let lastClosedMinute = Number.NEGATIVE_INFINITY;
|
|
5999
|
+
let lastSeenMinute = Number.NEGATIVE_INFINITY;
|
|
6000
|
+
let stateBytes = 0;
|
|
6001
|
+
let activeSeries = 0;
|
|
6002
|
+
let sealed = false;
|
|
6003
|
+
const reserve = (bytes) => {
|
|
6004
|
+
if (stateBytes > limits.maxStateBytes - bytes) {
|
|
6005
|
+
note(coverage, "dropped_byte_budget");
|
|
6006
|
+
return false;
|
|
6007
|
+
}
|
|
6008
|
+
stateBytes += bytes;
|
|
6009
|
+
return true;
|
|
6010
|
+
};
|
|
6011
|
+
const internDeclaration = (declaration) => {
|
|
6012
|
+
if (!declaration) {
|
|
6013
|
+
note(coverage, "dropped_unexportable");
|
|
6014
|
+
return void 0;
|
|
6015
|
+
}
|
|
6016
|
+
const existing = functionHandleByRuntimeId.get(declaration.runtime_id);
|
|
6017
|
+
if (existing !== void 0) return existing;
|
|
6018
|
+
if (!declarationAccepted(declaration)) {
|
|
6019
|
+
note(coverage, "dropped_unexportable");
|
|
6020
|
+
return void 0;
|
|
6021
|
+
}
|
|
6022
|
+
if (functions.length >= limits.maxFunctions) {
|
|
6023
|
+
note(coverage, "dropped_unexportable");
|
|
6024
|
+
return void 0;
|
|
6025
|
+
}
|
|
6026
|
+
if (!reserve(DECLARATION_BYTES + declaration.runtime_id.length)) return void 0;
|
|
6027
|
+
const handle = functions.length;
|
|
6028
|
+
functions.push(declaration);
|
|
6029
|
+
functionHandleByRuntimeId.set(declaration.runtime_id, handle);
|
|
6030
|
+
return handle;
|
|
6031
|
+
};
|
|
6032
|
+
const internExecutionKey = (key) => {
|
|
6033
|
+
if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return void 0;
|
|
6034
|
+
const existing = executionHandleByKey.get(key);
|
|
6035
|
+
if (existing !== void 0) return existing;
|
|
6036
|
+
if (executionKeys.length >= limits.maxExecutionTypes) {
|
|
6037
|
+
note(coverage, "dropped_unexportable");
|
|
6038
|
+
return void 0;
|
|
6039
|
+
}
|
|
6040
|
+
if (!reserve(key.length)) return void 0;
|
|
6041
|
+
const handle = executionKeys.length;
|
|
6042
|
+
executionKeys.push(key);
|
|
6043
|
+
executionHandleByKey.set(key, handle);
|
|
6044
|
+
return handle;
|
|
6045
|
+
};
|
|
6046
|
+
const ensureSeries = (minute, functionHandle, executionHandle) => {
|
|
6047
|
+
let byFunction = active.get(minute);
|
|
6048
|
+
if (!byFunction) {
|
|
6049
|
+
byFunction = /* @__PURE__ */ new Map();
|
|
6050
|
+
active.set(minute, byFunction);
|
|
6051
|
+
}
|
|
6052
|
+
let byExecution = byFunction.get(functionHandle);
|
|
6053
|
+
if (!byExecution) {
|
|
6054
|
+
byExecution = /* @__PURE__ */ new Map();
|
|
6055
|
+
byFunction.set(functionHandle, byExecution);
|
|
6056
|
+
}
|
|
6057
|
+
const existing = byExecution.get(executionHandle);
|
|
6058
|
+
if (existing) return existing;
|
|
6059
|
+
if (activeSeries >= limits.maxActiveSeries) {
|
|
6060
|
+
note(coverage, "dropped_active_series");
|
|
6061
|
+
return void 0;
|
|
6062
|
+
}
|
|
6063
|
+
if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
|
|
6064
|
+
const series = {
|
|
6065
|
+
started: 0,
|
|
6066
|
+
completed: 0,
|
|
6067
|
+
failed: 0,
|
|
6068
|
+
sampleCount: 0,
|
|
6069
|
+
sampleSumUs: 0,
|
|
6070
|
+
sampleMinUs: null,
|
|
6071
|
+
sampleMaxUs: null,
|
|
6072
|
+
invalidTiming: 0,
|
|
6073
|
+
histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
|
|
6074
|
+
bytes: SERIES_BYTES + HISTOGRAM_BYTES
|
|
6075
|
+
};
|
|
6076
|
+
byExecution.set(executionHandle, series);
|
|
6077
|
+
activeSeries += 1;
|
|
6078
|
+
return series;
|
|
6079
|
+
};
|
|
6080
|
+
const appendQueue = (entry) => {
|
|
6081
|
+
if (discardedMarks(entry.series) === 0) {
|
|
6082
|
+
stateBytes -= entry.bytes;
|
|
6083
|
+
if (stateBytes < 0) stateBytes = 0;
|
|
6084
|
+
return;
|
|
6085
|
+
}
|
|
6086
|
+
queue.push(entry);
|
|
6087
|
+
queue.sort((left, right) => left.minute - right.minute);
|
|
6088
|
+
while (queue.length > limits.maxQueuedMinutes) {
|
|
6089
|
+
const dropped = queue.shift();
|
|
6090
|
+
if (!dropped) break;
|
|
6091
|
+
stateBytes -= dropped.bytes;
|
|
6092
|
+
if (stateBytes < 0) stateBytes = 0;
|
|
6093
|
+
note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
|
|
6094
|
+
}
|
|
6095
|
+
};
|
|
6096
|
+
const closeMinute = (minute, table) => {
|
|
6097
|
+
active.delete(minute);
|
|
6098
|
+
activeSeries -= countSeries(table);
|
|
6099
|
+
if (minute > lastClosedMinute) lastClosedMinute = minute;
|
|
6100
|
+
appendQueue({ minute, series: table, bytes: tableBytes(table) });
|
|
6101
|
+
};
|
|
6102
|
+
const rotate = (currentMinute) => {
|
|
6103
|
+
for (const minute of [...active.keys()]) {
|
|
6104
|
+
if (minute >= currentMinute) continue;
|
|
6105
|
+
const table = active.get(minute);
|
|
6106
|
+
if (table) closeMinute(minute, table);
|
|
6107
|
+
}
|
|
6108
|
+
const closedThrough = currentMinute - 1;
|
|
6109
|
+
if (closedThrough > lastClosedMinute) lastClosedMinute = closedThrough;
|
|
6110
|
+
};
|
|
6111
|
+
const rotateIfNeeded = (minute) => {
|
|
6112
|
+
if (minute === lastSeenMinute) return;
|
|
6113
|
+
lastSeenMinute = minute;
|
|
6114
|
+
rotate(minute);
|
|
6115
|
+
};
|
|
6116
|
+
const snapshotActive = () => {
|
|
6117
|
+
for (const [minute, table] of active) {
|
|
6118
|
+
appendQueue({ minute, series: snapshotAndReset(table), bytes: 0 });
|
|
6119
|
+
}
|
|
6120
|
+
};
|
|
6121
|
+
const moveAllActive = () => {
|
|
6122
|
+
for (const minute of [...active.keys()]) {
|
|
6123
|
+
const table = active.get(minute);
|
|
6124
|
+
if (table) closeMinute(minute, table);
|
|
6125
|
+
}
|
|
6126
|
+
};
|
|
6127
|
+
const rememberSample = (series, durationUs, bucket) => {
|
|
6128
|
+
const sampleCount = series.sampleCount + 1;
|
|
6129
|
+
const sampleSumUs = series.sampleSumUs + durationUs;
|
|
6130
|
+
const previous = series.histogram[bucket];
|
|
6131
|
+
if (previous === void 0) return false;
|
|
6132
|
+
const cell = previous + 1;
|
|
6133
|
+
const sumFits = Number.isFinite(sampleSumUs) && sampleSumUs >= 0 && sampleSumUs <= Number.MAX_SAFE_INTEGER;
|
|
6134
|
+
if (!Number.isSafeInteger(sampleCount) || !Number.isSafeInteger(cell) || !sumFits) return false;
|
|
6135
|
+
series.histogram[bucket] = cell;
|
|
6136
|
+
series.sampleCount = sampleCount;
|
|
6137
|
+
series.sampleSumUs = sampleSumUs;
|
|
6138
|
+
series.sampleMinUs = series.sampleMinUs === null ? durationUs : Math.min(series.sampleMinUs, durationUs);
|
|
6139
|
+
series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
|
|
6140
|
+
return true;
|
|
6141
|
+
};
|
|
6142
|
+
const rememberCompletion = (series, startedNs, failed, endedNs) => {
|
|
6143
|
+
const completed = series.completed + 1;
|
|
6144
|
+
const failures = series.failed + (failed ? 1 : 0);
|
|
6145
|
+
if (!Number.isSafeInteger(completed) || !Number.isSafeInteger(failures)) return false;
|
|
6146
|
+
const elapsed = endedNs - startedNs;
|
|
6147
|
+
const durationUs = Number(elapsed) / 1e3;
|
|
6148
|
+
const placed = durationHistogramBucket(durationUs);
|
|
6149
|
+
const elapsedFits = elapsed >= 0n && elapsed <= MAX_ELAPSED_NS;
|
|
6150
|
+
const sampled = elapsedFits && placed !== void 0 && rememberSample(series, durationUs, placed);
|
|
6151
|
+
if (!sampled) {
|
|
6152
|
+
const invalidTiming = series.invalidTiming + 1;
|
|
6153
|
+
if (!Number.isSafeInteger(invalidTiming)) return false;
|
|
6154
|
+
series.invalidTiming = invalidTiming;
|
|
6155
|
+
}
|
|
6156
|
+
series.completed = completed;
|
|
6157
|
+
series.failed = failures;
|
|
6158
|
+
return true;
|
|
6159
|
+
};
|
|
6160
|
+
const startCall = (functionHandle, executionHandle, startedNs) => {
|
|
6161
|
+
if (sealed) {
|
|
6162
|
+
note(coverage, "dropped_unexportable");
|
|
6163
|
+
return void 0;
|
|
6164
|
+
}
|
|
6165
|
+
if (executionHandle === void 0) {
|
|
6166
|
+
note(coverage, "skipped_unresolved_execution_type");
|
|
6167
|
+
return void 0;
|
|
6168
|
+
}
|
|
6169
|
+
const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
|
|
6170
|
+
rotateIfNeeded(minute);
|
|
6171
|
+
if (minute <= lastClosedMinute) {
|
|
6172
|
+
note(coverage, "dropped_late_completion");
|
|
6173
|
+
return void 0;
|
|
6174
|
+
}
|
|
6175
|
+
const series = ensureSeries(minute, functionHandle, executionHandle);
|
|
6176
|
+
if (!series) return void 0;
|
|
6177
|
+
const started = series.started + 1;
|
|
6178
|
+
if (!Number.isSafeInteger(started)) {
|
|
6179
|
+
note(coverage, "dropped_unexportable");
|
|
6180
|
+
return void 0;
|
|
6181
|
+
}
|
|
6182
|
+
series.started = started;
|
|
6183
|
+
return startedNs ?? clock.monotonicNs();
|
|
6184
|
+
};
|
|
6185
|
+
const finishCall = (functionHandle, executionHandle, startedNs, failed, endedNs) => {
|
|
6186
|
+
if (sealed) {
|
|
6187
|
+
note(coverage, "dropped_late_completion");
|
|
6188
|
+
return;
|
|
6189
|
+
}
|
|
6190
|
+
const minute = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
|
|
6191
|
+
rotateIfNeeded(minute);
|
|
6192
|
+
if (minute <= lastClosedMinute && !active.has(minute)) {
|
|
6193
|
+
note(coverage, "dropped_late_completion");
|
|
6194
|
+
return;
|
|
6195
|
+
}
|
|
6196
|
+
const series = ensureSeries(minute, functionHandle, executionHandle);
|
|
6197
|
+
if (!series) return;
|
|
6198
|
+
const remembered = rememberCompletion(
|
|
6199
|
+
series,
|
|
6200
|
+
startedNs,
|
|
6201
|
+
failed,
|
|
6202
|
+
endedNs ?? clock.monotonicNs()
|
|
6203
|
+
);
|
|
6204
|
+
if (!remembered) note(coverage, "dropped_unexportable");
|
|
6205
|
+
};
|
|
6206
|
+
const beginCall = (input) => {
|
|
6207
|
+
const functionHandle = internDeclaration(input.declaration);
|
|
6208
|
+
if (functionHandle === void 0) return void 0;
|
|
6209
|
+
if (!input.executionKey || !isCanonicalFunctionMetricsExecutionKey(input.executionKey)) {
|
|
6210
|
+
startCall(functionHandle, void 0);
|
|
6211
|
+
return void 0;
|
|
6212
|
+
}
|
|
6213
|
+
const executionHandle = internExecutionKey(input.executionKey);
|
|
6214
|
+
if (executionHandle === void 0) return void 0;
|
|
6215
|
+
const startedNs = startCall(functionHandle, executionHandle);
|
|
6216
|
+
if (startedNs === void 0) return void 0;
|
|
6217
|
+
return { settled: false, functionHandle, executionHandle, startedNs };
|
|
6218
|
+
};
|
|
6219
|
+
const completeCall = (call, failed) => {
|
|
6220
|
+
if (!call || call.settled) return;
|
|
6221
|
+
call.settled = true;
|
|
6222
|
+
finishCall(call.functionHandle, call.executionHandle, call.startedNs, failed);
|
|
6223
|
+
};
|
|
6224
|
+
const drain = (drainOptions) => {
|
|
6225
|
+
if (!sealed) {
|
|
6226
|
+
rotateIfNeeded(Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS));
|
|
6227
|
+
if (drainOptions?.flushAll) snapshotActive();
|
|
6228
|
+
}
|
|
6229
|
+
const batches = functionMetricsBatchesFromQueue({
|
|
6230
|
+
environment: options.environment,
|
|
6231
|
+
release: options.release,
|
|
6232
|
+
producerId: options.producerId,
|
|
6233
|
+
batchId,
|
|
6234
|
+
maxFunctions: limits.maxFunctions,
|
|
6235
|
+
maxExecutionTypes: limits.maxExecutionTypes,
|
|
6236
|
+
maxMinuteRows: limits.maxMinuteRows,
|
|
6237
|
+
functions,
|
|
6238
|
+
executionKeys,
|
|
6239
|
+
queued: queue,
|
|
6240
|
+
coverage: { ...coverage, covered_bucket_starts: [] }
|
|
6241
|
+
});
|
|
6242
|
+
if (batches.length === 0) return [];
|
|
6243
|
+
for (const queued of queue) stateBytes -= queued.bytes;
|
|
6244
|
+
if (stateBytes < 0) stateBytes = 0;
|
|
6245
|
+
queue.length = 0;
|
|
6246
|
+
coverage.skipped_unresolved_execution_type = 0;
|
|
6247
|
+
coverage.dropped_active_series = 0;
|
|
6248
|
+
coverage.dropped_byte_budget = 0;
|
|
6249
|
+
coverage.dropped_queue_budget = 0;
|
|
6250
|
+
coverage.dropped_late_completion = 0;
|
|
6251
|
+
coverage.dropped_unexportable = 0;
|
|
6252
|
+
return batches;
|
|
6253
|
+
};
|
|
6254
|
+
return {
|
|
6255
|
+
internDeclaration,
|
|
6256
|
+
internExecutionKey,
|
|
6257
|
+
startCall,
|
|
6258
|
+
finishCall,
|
|
6259
|
+
beginCall,
|
|
6260
|
+
completeCall,
|
|
6261
|
+
drain,
|
|
6262
|
+
seal: () => {
|
|
6263
|
+
if (sealed) return;
|
|
6264
|
+
sealed = true;
|
|
6265
|
+
moveAllActive();
|
|
6266
|
+
}
|
|
6267
|
+
};
|
|
6268
|
+
};
|
|
6269
|
+
|
|
6270
|
+
// src/function-metrics/encode-function-metrics-upload.ts
|
|
6271
|
+
import {
|
|
6272
|
+
encodeFunctionMetricsBatch,
|
|
6273
|
+
encodeJsonRequestBodyAsync as encodeJsonRequestBodyAsync2,
|
|
6274
|
+
FUNCTION_METRICS_BUCKET_LATENESS_MS,
|
|
6275
|
+
FUNCTION_METRICS_MAX_DECODED_BYTES,
|
|
6276
|
+
FUNCTION_METRICS_MINUTE_MS as FUNCTION_METRICS_MINUTE_MS2,
|
|
6277
|
+
parseFunctionMetricsBucketStart
|
|
6278
|
+
} from "@rasputin-ai/core";
|
|
6279
|
+
var minuteMarks = (minute) => {
|
|
6280
|
+
const next = minute.started_calls + minute.completed_calls;
|
|
6281
|
+
return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
|
|
6282
|
+
};
|
|
6283
|
+
var expiresAtMsFor = (batch, nowMs) => {
|
|
6284
|
+
let oldest;
|
|
6285
|
+
for (const start of batch.coverage.covered_bucket_starts) {
|
|
6286
|
+
const bucket = parseFunctionMetricsBucketStart(start);
|
|
6287
|
+
if (bucket === void 0) continue;
|
|
6288
|
+
if (oldest === void 0 || bucket < oldest) oldest = bucket;
|
|
6289
|
+
}
|
|
6290
|
+
if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
|
|
6291
|
+
return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
|
|
6292
|
+
};
|
|
6293
|
+
var zeroLossCoverage = (coverage) => ({
|
|
6294
|
+
...coverage,
|
|
6295
|
+
skipped_unresolved_execution_type: 0,
|
|
6296
|
+
dropped_active_series: 0,
|
|
6297
|
+
dropped_byte_budget: 0,
|
|
6298
|
+
dropped_queue_budget: 0,
|
|
6299
|
+
dropped_late_completion: 0,
|
|
6300
|
+
dropped_unexportable: 0
|
|
6301
|
+
});
|
|
6302
|
+
var projectMinutes = (source, minutes, coverage, batchId) => {
|
|
6303
|
+
const functionIndexes = /* @__PURE__ */ new Map();
|
|
6304
|
+
const typeIndexes = /* @__PURE__ */ new Map();
|
|
6305
|
+
const functions = [];
|
|
6306
|
+
const executionTypes = [];
|
|
6307
|
+
const remapped = [];
|
|
6308
|
+
for (const minute of minutes) {
|
|
6309
|
+
let functionIndex = functionIndexes.get(minute.function_index);
|
|
6310
|
+
if (functionIndex === void 0) {
|
|
6311
|
+
const declaration = source.functions[minute.function_index];
|
|
6312
|
+
if (!declaration) continue;
|
|
6313
|
+
functionIndex = functions.length;
|
|
6314
|
+
functionIndexes.set(minute.function_index, functionIndex);
|
|
6315
|
+
functions.push(declaration);
|
|
6316
|
+
}
|
|
6317
|
+
let executionTypeIndex = typeIndexes.get(minute.execution_type_index);
|
|
6318
|
+
if (executionTypeIndex === void 0) {
|
|
6319
|
+
const entry = source.execution_types[minute.execution_type_index];
|
|
6320
|
+
if (!entry) continue;
|
|
6321
|
+
executionTypeIndex = executionTypes.length;
|
|
6322
|
+
typeIndexes.set(minute.execution_type_index, executionTypeIndex);
|
|
6323
|
+
executionTypes.push(entry);
|
|
6324
|
+
}
|
|
6325
|
+
remapped.push({
|
|
6326
|
+
...minute,
|
|
6327
|
+
function_index: functionIndex,
|
|
6328
|
+
execution_type_index: executionTypeIndex
|
|
6329
|
+
});
|
|
6330
|
+
}
|
|
6331
|
+
const covered = [...new Set(remapped.map((minute) => minute.bucket_start))].sort();
|
|
6332
|
+
return {
|
|
6333
|
+
...source,
|
|
6334
|
+
batch_id: batchId,
|
|
6335
|
+
functions,
|
|
6336
|
+
execution_types: executionTypes,
|
|
6337
|
+
minutes: remapped,
|
|
6338
|
+
coverage: { ...coverage, covered_bucket_starts: covered }
|
|
6339
|
+
};
|
|
6340
|
+
};
|
|
6341
|
+
var withLoss = (batch, loss) => ({
|
|
6342
|
+
...batch,
|
|
6343
|
+
coverage: {
|
|
6344
|
+
...batch.coverage,
|
|
6345
|
+
dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
|
|
6346
|
+
dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
|
|
6347
|
+
}
|
|
6348
|
+
});
|
|
6349
|
+
var encodeOne = async (batch, nowMs, signal) => {
|
|
6350
|
+
const decodedBytes = encodeFunctionMetricsBatch(batch);
|
|
6351
|
+
if (decodedBytes.byteLength > FUNCTION_METRICS_MAX_DECODED_BYTES) return void 0;
|
|
6352
|
+
const encoded = await encodeJsonRequestBodyAsync2(decodedBytes, void 0, signal);
|
|
6353
|
+
return {
|
|
6354
|
+
decodedBytes,
|
|
6355
|
+
body: encoded.body,
|
|
6356
|
+
gzip: encoded.gzip,
|
|
6357
|
+
batchId: batch.batch_id,
|
|
6358
|
+
expiresAtMs: expiresAtMsFor(batch, nowMs)
|
|
6359
|
+
};
|
|
6360
|
+
};
|
|
6361
|
+
var encodeFitting = async (batch, nowMs, signal) => {
|
|
6362
|
+
const encoded = await encodeOne(batch, nowMs, signal);
|
|
6363
|
+
if (encoded) return { uploads: [encoded], droppedUnexportable: 0 };
|
|
6364
|
+
if (batch.minutes.length <= 1) {
|
|
6365
|
+
return {
|
|
6366
|
+
uploads: [],
|
|
6367
|
+
droppedUnexportable: batch.minutes.reduce((sum, minute) => sum + minuteMarks(minute), 0)
|
|
6368
|
+
};
|
|
6369
|
+
}
|
|
6370
|
+
const mid = Math.ceil(batch.minutes.length / 2);
|
|
6371
|
+
const first = projectMinutes(batch, batch.minutes.slice(0, mid), batch.coverage, batch.batch_id);
|
|
6372
|
+
const rest = projectMinutes(
|
|
6373
|
+
batch,
|
|
6374
|
+
batch.minutes.slice(mid),
|
|
6375
|
+
zeroLossCoverage(batch.coverage),
|
|
6376
|
+
newFunctionMetricsBatchId()
|
|
6377
|
+
);
|
|
6378
|
+
const left = await encodeFitting(first, nowMs, signal);
|
|
6379
|
+
const right = await encodeFitting(rest, nowMs, signal);
|
|
6380
|
+
return {
|
|
6381
|
+
uploads: [...left.uploads, ...right.uploads],
|
|
6382
|
+
droppedUnexportable: left.droppedUnexportable + right.droppedUnexportable
|
|
6383
|
+
};
|
|
6384
|
+
};
|
|
6385
|
+
var encodeFunctionMetricsUploads = async (batches, input) => {
|
|
6386
|
+
const uploads = [];
|
|
6387
|
+
let extra = {
|
|
6388
|
+
dropped_unexportable: 0,
|
|
6389
|
+
dropped_queue_budget: input.queueDrops ?? 0
|
|
6390
|
+
};
|
|
6391
|
+
for (const batch of batches) {
|
|
6392
|
+
const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
|
|
6393
|
+
extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
|
|
6394
|
+
uploads.push(...fitted.uploads);
|
|
6395
|
+
}
|
|
6396
|
+
return uploads;
|
|
6397
|
+
};
|
|
6398
|
+
|
|
6399
|
+
// src/function-metrics/send-function-metrics-batch.ts
|
|
6400
|
+
var REQUEST_TIMEOUT_MS2 = 2e4;
|
|
6401
|
+
var abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
|
|
6402
|
+
var retryAfterMs = (response) => {
|
|
6403
|
+
const header = response.headers.get("retry-after");
|
|
6404
|
+
if (!header) return null;
|
|
6405
|
+
const seconds = Number(header);
|
|
6406
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
|
|
6407
|
+
const date = Date.parse(header);
|
|
6408
|
+
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
|
|
6409
|
+
};
|
|
6410
|
+
var backoffMs2 = (attempt, random) => {
|
|
6411
|
+
const base = Math.min(3e4, 500 * 2 ** attempt);
|
|
6412
|
+
return Math.floor(base * (0.5 + random()));
|
|
6413
|
+
};
|
|
6414
|
+
var fetchUntilAborted = (fetchFn, url, init) => new Promise((resolve, reject) => {
|
|
6415
|
+
const onAbort = () => reject(abortError());
|
|
6416
|
+
init.signal.addEventListener("abort", onAbort, { once: true });
|
|
6417
|
+
if (init.signal.aborted) {
|
|
6418
|
+
init.signal.removeEventListener("abort", onAbort);
|
|
6419
|
+
reject(abortError());
|
|
6420
|
+
return;
|
|
6421
|
+
}
|
|
6422
|
+
void fetchFn(url, init).then(
|
|
6423
|
+
(value) => {
|
|
6424
|
+
init.signal.removeEventListener("abort", onAbort);
|
|
6425
|
+
resolve(value);
|
|
6426
|
+
},
|
|
6427
|
+
(error) => {
|
|
6428
|
+
init.signal.removeEventListener("abort", onAbort);
|
|
6429
|
+
reject(error);
|
|
6430
|
+
}
|
|
6431
|
+
);
|
|
6432
|
+
});
|
|
6433
|
+
var sendFunctionMetricsBatch = async (input) => {
|
|
6434
|
+
if (input.signal.aborted) return { outcome: "aborted" };
|
|
6435
|
+
const nowMs = input.nowMs ?? Date.now;
|
|
6436
|
+
if (input.upload.expiresAtMs <= nowMs())
|
|
6437
|
+
return { outcome: "terminal", status: null, halt: false };
|
|
6438
|
+
const request = new AbortController();
|
|
6439
|
+
const timer = setTimeout(() => request.abort(), REQUEST_TIMEOUT_MS2);
|
|
6440
|
+
timer.unref?.();
|
|
6441
|
+
const onParentAbort = () => request.abort();
|
|
6442
|
+
input.signal.addEventListener("abort", onParentAbort, { once: true });
|
|
6443
|
+
if (input.signal.aborted) request.abort();
|
|
6444
|
+
const headers = {
|
|
6445
|
+
Authorization: `Bearer ${input.ingestToken}`,
|
|
6446
|
+
"Content-Type": "application/json",
|
|
6447
|
+
Accept: "application/json"
|
|
6448
|
+
};
|
|
6449
|
+
if (input.upload.gzip) headers["Content-Encoding"] = "gzip";
|
|
6450
|
+
try {
|
|
6451
|
+
const response = await fetchUntilAborted(input.fetch, input.url, {
|
|
6452
|
+
method: "POST",
|
|
6453
|
+
headers,
|
|
6454
|
+
body: input.upload.body,
|
|
6455
|
+
signal: request.signal
|
|
6456
|
+
});
|
|
6457
|
+
if (response.ok) return { outcome: "ok" };
|
|
6458
|
+
if (response.status === 429) {
|
|
6459
|
+
return {
|
|
6460
|
+
outcome: "retry",
|
|
6461
|
+
waitMs: retryAfterMs(response) ?? backoffMs2(input.attempt, input.random ?? Math.random)
|
|
6462
|
+
};
|
|
6463
|
+
}
|
|
6464
|
+
if (response.status === 401 || response.status === 403 || response.status === 404) {
|
|
6465
|
+
return { outcome: "terminal", status: response.status, halt: true };
|
|
6466
|
+
}
|
|
6467
|
+
if (response.status >= 400 && response.status < 500) {
|
|
6468
|
+
return { outcome: "terminal", status: response.status, halt: false };
|
|
6469
|
+
}
|
|
6470
|
+
return {
|
|
6471
|
+
outcome: "retry",
|
|
6472
|
+
waitMs: backoffMs2(input.attempt, input.random ?? Math.random)
|
|
6473
|
+
};
|
|
6474
|
+
} catch {
|
|
6475
|
+
if (input.signal.aborted) return { outcome: "aborted" };
|
|
6476
|
+
return { outcome: "retry", waitMs: backoffMs2(input.attempt, input.random ?? Math.random) };
|
|
6477
|
+
} finally {
|
|
6478
|
+
clearTimeout(timer);
|
|
6479
|
+
input.signal.removeEventListener("abort", onParentAbort);
|
|
6480
|
+
}
|
|
6481
|
+
};
|
|
6482
|
+
|
|
6483
|
+
// src/function-metrics/function-metrics-exporter.ts
|
|
6484
|
+
var MAX_QUEUE_ITEMS = 32;
|
|
6485
|
+
var MAX_QUEUE_BYTES = 4 * 1024 * 1024;
|
|
6486
|
+
var DEFAULT_SCHEDULE_MS = 6e4;
|
|
6487
|
+
var FLUSH_MS = 1e4;
|
|
6488
|
+
var SHUTDOWN_FLUSH_MS = 2e3;
|
|
6489
|
+
var MAX_ATTEMPTS = 8;
|
|
6490
|
+
var sleep = (ms, signal) => new Promise((resolve) => {
|
|
6491
|
+
if (ms <= 0 || signal.aborted) {
|
|
6492
|
+
resolve();
|
|
6493
|
+
return;
|
|
6494
|
+
}
|
|
6495
|
+
const timer = setTimeout(finish, ms);
|
|
6496
|
+
timer.unref?.();
|
|
6497
|
+
const onAbort = () => {
|
|
6498
|
+
clearTimeout(timer);
|
|
6499
|
+
finish();
|
|
6500
|
+
};
|
|
6501
|
+
function finish() {
|
|
6502
|
+
signal.removeEventListener("abort", onAbort);
|
|
6503
|
+
resolve();
|
|
6504
|
+
}
|
|
6505
|
+
signal.addEventListener("abort", onAbort);
|
|
6506
|
+
if (signal.aborted) onAbort();
|
|
6507
|
+
});
|
|
6508
|
+
var createFunctionMetricsExporter = (input) => {
|
|
6509
|
+
const nowMs = input.nowMs ?? Date.now;
|
|
6510
|
+
const random = input.random ?? Math.random;
|
|
6511
|
+
const scheduleMs = input.scheduleMs ?? DEFAULT_SCHEDULE_MS;
|
|
6512
|
+
const queue = [];
|
|
6513
|
+
let queueBytes = 0;
|
|
6514
|
+
let queueDrops = 0;
|
|
6515
|
+
let timer;
|
|
6516
|
+
let closed = false;
|
|
6517
|
+
let halted = false;
|
|
6518
|
+
let stopped = false;
|
|
6519
|
+
let workAbort;
|
|
6520
|
+
let work;
|
|
6521
|
+
let sent = 0;
|
|
6522
|
+
let dropped = 0;
|
|
6523
|
+
let warnedHalt = null;
|
|
6524
|
+
const dropOldest = () => {
|
|
6525
|
+
const oldest = queue.shift();
|
|
6526
|
+
if (!oldest) return;
|
|
6527
|
+
queueBytes -= oldest.upload.decodedBytes.byteLength;
|
|
6528
|
+
if (queueBytes < 0) queueBytes = 0;
|
|
6529
|
+
queueDrops += 1;
|
|
6530
|
+
dropped += 1;
|
|
6531
|
+
};
|
|
6532
|
+
const enqueue = (upload) => {
|
|
6533
|
+
queue.push({ upload, attempt: 0 });
|
|
6534
|
+
queueBytes += upload.decodedBytes.byteLength;
|
|
6535
|
+
while (queue.length > MAX_QUEUE_ITEMS || queueBytes > MAX_QUEUE_BYTES) dropOldest();
|
|
6536
|
+
};
|
|
6537
|
+
const drainAndEnqueue = async (flushAll2) => {
|
|
6538
|
+
if (halted || stopped) return;
|
|
6539
|
+
const batches = input.collector.drain({ flushAll: flushAll2 });
|
|
6540
|
+
if (batches.length === 0) return;
|
|
6541
|
+
const encoded = await encodeFunctionMetricsUploads(batches, {
|
|
6542
|
+
nowMs: nowMs(),
|
|
6543
|
+
queueDrops
|
|
6544
|
+
});
|
|
6545
|
+
if (encoded.length === 0 || halted || stopped) return;
|
|
6546
|
+
queueDrops = 0;
|
|
6547
|
+
for (const upload of encoded) enqueue(upload);
|
|
6548
|
+
};
|
|
6549
|
+
const warnHalt = (status) => {
|
|
6550
|
+
if (warnedHalt === status) return;
|
|
6551
|
+
warnedHalt = status;
|
|
6552
|
+
if (status === 401 || status === 403) {
|
|
6553
|
+
console.warn("[rasputin] function metrics export stopped: authentication failed");
|
|
6554
|
+
return;
|
|
6555
|
+
}
|
|
6556
|
+
if (status === 404) {
|
|
6557
|
+
console.warn("[rasputin] function metrics export stopped: ingest route is unavailable");
|
|
6558
|
+
}
|
|
6559
|
+
};
|
|
6560
|
+
const pump = async (signal) => {
|
|
6561
|
+
while (queue.length > 0 && !halted && !stopped && !signal.aborted) {
|
|
6562
|
+
const item = queue[0];
|
|
6563
|
+
if (!item) return;
|
|
6564
|
+
if (item.upload.expiresAtMs <= nowMs()) {
|
|
6565
|
+
queue.shift();
|
|
6566
|
+
queueBytes -= item.upload.decodedBytes.byteLength;
|
|
6567
|
+
dropped += 1;
|
|
6568
|
+
continue;
|
|
6569
|
+
}
|
|
6570
|
+
if (item.attempt >= MAX_ATTEMPTS) {
|
|
6571
|
+
queue.shift();
|
|
6572
|
+
queueBytes -= item.upload.decodedBytes.byteLength;
|
|
6573
|
+
dropped += 1;
|
|
6574
|
+
continue;
|
|
6575
|
+
}
|
|
6576
|
+
const result = await sendFunctionMetricsBatch({
|
|
6577
|
+
url: input.url,
|
|
6578
|
+
ingestToken: input.ingestToken,
|
|
6579
|
+
upload: item.upload,
|
|
6580
|
+
fetch: input.fetch,
|
|
6581
|
+
signal,
|
|
6582
|
+
attempt: item.attempt,
|
|
6583
|
+
random,
|
|
6584
|
+
nowMs
|
|
6585
|
+
});
|
|
6586
|
+
if (result.outcome === "aborted") return;
|
|
6587
|
+
if (result.outcome === "ok") {
|
|
6588
|
+
queue.shift();
|
|
6589
|
+
queueBytes -= item.upload.decodedBytes.byteLength;
|
|
6590
|
+
sent += 1;
|
|
6591
|
+
continue;
|
|
6592
|
+
}
|
|
6593
|
+
if (result.outcome === "terminal") {
|
|
6594
|
+
queue.shift();
|
|
6595
|
+
queueBytes -= item.upload.decodedBytes.byteLength;
|
|
6596
|
+
dropped += 1;
|
|
6597
|
+
if (result.halt) {
|
|
6598
|
+
halted = true;
|
|
6599
|
+
warnHalt(result.status);
|
|
6600
|
+
}
|
|
6601
|
+
continue;
|
|
6602
|
+
}
|
|
6603
|
+
item.attempt += 1;
|
|
6604
|
+
await sleep(result.waitMs, signal);
|
|
6605
|
+
}
|
|
6606
|
+
};
|
|
6607
|
+
const abortCurrent = () => {
|
|
6608
|
+
workAbort?.abort();
|
|
6609
|
+
};
|
|
6610
|
+
const raceUntilAborted = async (running, signal) => {
|
|
6611
|
+
if (signal.aborted) return;
|
|
6612
|
+
await new Promise((resolve) => {
|
|
6613
|
+
let settled = false;
|
|
6614
|
+
const finish = () => {
|
|
6615
|
+
if (settled) return;
|
|
6616
|
+
settled = true;
|
|
6617
|
+
signal.removeEventListener("abort", finish);
|
|
6618
|
+
resolve();
|
|
6619
|
+
};
|
|
6620
|
+
signal.addEventListener("abort", finish);
|
|
6621
|
+
if (signal.aborted) {
|
|
6622
|
+
finish();
|
|
6623
|
+
return;
|
|
6624
|
+
}
|
|
6625
|
+
void running.then(finish, finish);
|
|
6626
|
+
});
|
|
6627
|
+
};
|
|
6628
|
+
const runWork = async (signal, task) => {
|
|
6629
|
+
const onAbort = () => abortCurrent();
|
|
6630
|
+
signal.addEventListener("abort", onAbort);
|
|
6631
|
+
if (signal.aborted) abortCurrent();
|
|
6632
|
+
try {
|
|
6633
|
+
while (work) {
|
|
6634
|
+
const previous = work;
|
|
6635
|
+
await raceUntilAborted(previous, signal);
|
|
6636
|
+
if (signal.aborted || halted) return;
|
|
6637
|
+
if (work === previous) return;
|
|
6638
|
+
}
|
|
6639
|
+
if (halted) return;
|
|
6640
|
+
const inner = new AbortController();
|
|
6641
|
+
workAbort = inner;
|
|
6642
|
+
if (signal.aborted) {
|
|
6643
|
+
workAbort = void 0;
|
|
6644
|
+
return;
|
|
6645
|
+
}
|
|
6646
|
+
const running = task(inner.signal).finally(() => {
|
|
6647
|
+
if (workAbort === inner) workAbort = void 0;
|
|
6648
|
+
if (work === running) work = void 0;
|
|
6649
|
+
});
|
|
6650
|
+
work = running;
|
|
6651
|
+
await raceUntilAborted(running, signal);
|
|
6652
|
+
} finally {
|
|
6653
|
+
signal.removeEventListener("abort", onAbort);
|
|
6654
|
+
}
|
|
6655
|
+
};
|
|
6656
|
+
const tick = async () => {
|
|
6657
|
+
if (closed || halted) return;
|
|
6658
|
+
try {
|
|
6659
|
+
await runWork(new AbortController().signal, async (signal) => {
|
|
6660
|
+
if (closed || halted) return;
|
|
6661
|
+
await drainAndEnqueue(false);
|
|
6662
|
+
await pump(signal);
|
|
6663
|
+
});
|
|
6664
|
+
} catch {
|
|
6665
|
+
}
|
|
6666
|
+
if (!closed && !halted) arm();
|
|
6667
|
+
};
|
|
6668
|
+
const arm = () => {
|
|
6669
|
+
if (closed || halted) return;
|
|
6670
|
+
const delay = Math.max(1e3, Math.floor(scheduleMs * (0.85 + random() * 0.3)));
|
|
6671
|
+
timer = setTimeout(() => {
|
|
6672
|
+
void tick();
|
|
6673
|
+
}, delay);
|
|
6674
|
+
timer.unref?.();
|
|
6675
|
+
};
|
|
6676
|
+
arm();
|
|
6677
|
+
const flush = async (timeoutMs) => {
|
|
6678
|
+
if (closed || halted) return;
|
|
6679
|
+
const abort = new AbortController();
|
|
6680
|
+
const budget = timeoutMs ?? FLUSH_MS;
|
|
6681
|
+
const timeout = setTimeout(() => abort.abort(), Math.max(0, budget));
|
|
6682
|
+
try {
|
|
6683
|
+
await runWork(abort.signal, async (signal) => {
|
|
6684
|
+
if (closed || halted) return;
|
|
6685
|
+
await drainAndEnqueue(true);
|
|
6686
|
+
await pump(signal);
|
|
6687
|
+
});
|
|
6688
|
+
} catch {
|
|
6689
|
+
} finally {
|
|
6690
|
+
clearTimeout(timeout);
|
|
6691
|
+
}
|
|
6692
|
+
};
|
|
6693
|
+
return {
|
|
6694
|
+
flush,
|
|
6695
|
+
close: async () => {
|
|
6696
|
+
if (closed) return;
|
|
6697
|
+
closed = true;
|
|
6698
|
+
if (timer) clearTimeout(timer);
|
|
6699
|
+
timer = void 0;
|
|
6700
|
+
const abort = new AbortController();
|
|
6701
|
+
const timeout = setTimeout(() => abort.abort(), SHUTDOWN_FLUSH_MS);
|
|
6702
|
+
abortCurrent();
|
|
6703
|
+
try {
|
|
6704
|
+
await runWork(abort.signal, async (signal) => {
|
|
6705
|
+
input.collector.seal();
|
|
6706
|
+
await drainAndEnqueue(false);
|
|
6707
|
+
await pump(signal);
|
|
6708
|
+
});
|
|
6709
|
+
} catch {
|
|
6710
|
+
} finally {
|
|
6711
|
+
clearTimeout(timeout);
|
|
6712
|
+
stopped = true;
|
|
6713
|
+
input.collector.seal();
|
|
6714
|
+
queue.length = 0;
|
|
6715
|
+
queueBytes = 0;
|
|
6716
|
+
}
|
|
6717
|
+
},
|
|
6718
|
+
getStats: () => ({ sent, dropped, halted })
|
|
6719
|
+
};
|
|
6720
|
+
};
|
|
6721
|
+
|
|
6722
|
+
// src/function-metrics/install-function-metric-declaration-sink.ts
|
|
6723
|
+
var REGISTER = "__rasputinRegisterFunctionMetricDeclarations";
|
|
6724
|
+
var PENDING = "__rasputinPendingFunctionMetricDeclarations";
|
|
6725
|
+
var installFunctionMetricDeclarationSink = () => {
|
|
6726
|
+
Reflect.set(globalThis, REGISTER, registerFunctionMetricDeclarations);
|
|
6727
|
+
const pending = Reflect.get(globalThis, PENDING);
|
|
6728
|
+
if (!Array.isArray(pending) || pending.length === 0) return;
|
|
6729
|
+
registerFunctionMetricDeclarations(pending);
|
|
6730
|
+
pending.length = 0;
|
|
6731
|
+
};
|
|
6732
|
+
|
|
6733
|
+
// src/function-metrics/bind-function-metrics.ts
|
|
6734
|
+
var SLOT = Symbol.for("rasputin.functionMetrics.runtime.v1");
|
|
6735
|
+
var releasedHandles = /* @__PURE__ */ new WeakSet();
|
|
6736
|
+
var isRuntime = (value) => {
|
|
6737
|
+
if (typeof value !== "object" || value === null) return false;
|
|
6738
|
+
return "collector" in value && "exporter" in value && "refs" in value && "identity" in value && "warnedMismatch" in value;
|
|
6739
|
+
};
|
|
6740
|
+
var bindingIdentity = (input) => `${input.ingestToken}
|
|
6741
|
+
${input.url}
|
|
6742
|
+
${input.environment}
|
|
6743
|
+
${input.release}`;
|
|
6744
|
+
var warnIncompatible = (runtime) => {
|
|
6745
|
+
if (runtime.warnedMismatch) return;
|
|
6746
|
+
runtime.warnedMismatch = true;
|
|
6747
|
+
console.warn(
|
|
6748
|
+
"[rasputin] function metrics already running with a different configuration; this client will not collect function metrics"
|
|
6749
|
+
);
|
|
6750
|
+
};
|
|
6751
|
+
var createBindings = (input) => {
|
|
6752
|
+
installFunctionMetricDeclarationSink();
|
|
6753
|
+
const collector = createFunctionMetricsCollector({
|
|
6754
|
+
environment: input.environment,
|
|
6755
|
+
producerId: randomUUID2(),
|
|
6756
|
+
release: input.release
|
|
6757
|
+
});
|
|
6758
|
+
return {
|
|
6759
|
+
collector,
|
|
6760
|
+
exporter: createFunctionMetricsExporter({
|
|
6761
|
+
collector,
|
|
6762
|
+
url: input.url,
|
|
6763
|
+
ingestToken: input.ingestToken,
|
|
6764
|
+
fetch: input.fetch ?? defaultIngestFetch2()
|
|
6765
|
+
})
|
|
6766
|
+
};
|
|
6767
|
+
};
|
|
6768
|
+
var bindFunctionMetrics = (input) => {
|
|
6769
|
+
if (!input.clientEnabled) return void 0;
|
|
6770
|
+
if (input.options?.enabled === false) return void 0;
|
|
6771
|
+
const release = input.release.trim().toLowerCase();
|
|
6772
|
+
if (!/^[0-9a-f]{7,40}$/.test(release)) return void 0;
|
|
6773
|
+
const url = resolveEndpointUrls3(input.apiUrl).functionMetricsUrl;
|
|
6774
|
+
const key = bindingIdentity({
|
|
6775
|
+
ingestToken: input.ingestToken,
|
|
6776
|
+
url,
|
|
6777
|
+
environment: input.environment,
|
|
6778
|
+
release
|
|
6779
|
+
});
|
|
6780
|
+
const existing = Reflect.get(globalThis, SLOT);
|
|
6781
|
+
if (isRuntime(existing)) {
|
|
6782
|
+
if (existing.identity !== key) {
|
|
6783
|
+
warnIncompatible(existing);
|
|
6784
|
+
return void 0;
|
|
6785
|
+
}
|
|
6786
|
+
existing.refs += 1;
|
|
6787
|
+
return { collector: existing.collector, exporter: existing.exporter };
|
|
6788
|
+
}
|
|
6789
|
+
const bindings2 = createBindings({
|
|
6790
|
+
release,
|
|
6791
|
+
ingestToken: input.ingestToken,
|
|
6792
|
+
url,
|
|
6793
|
+
environment: input.environment,
|
|
6794
|
+
fetch: input.fetch
|
|
6795
|
+
});
|
|
6796
|
+
Reflect.set(globalThis, SLOT, {
|
|
6797
|
+
...bindings2,
|
|
6798
|
+
refs: 1,
|
|
6799
|
+
identity: key,
|
|
6800
|
+
warnedMismatch: false
|
|
6801
|
+
});
|
|
6802
|
+
return bindings2;
|
|
6803
|
+
};
|
|
6804
|
+
var releaseFunctionMetricsBindings = async (bindings2) => {
|
|
6805
|
+
if (!bindings2 || releasedHandles.has(bindings2)) return;
|
|
6806
|
+
releasedHandles.add(bindings2);
|
|
6807
|
+
const existing = Reflect.get(globalThis, SLOT);
|
|
6808
|
+
if (isRuntime(existing) && existing.exporter === bindings2.exporter) {
|
|
6809
|
+
existing.refs -= 1;
|
|
6810
|
+
if (existing.refs > 0) return;
|
|
6811
|
+
Reflect.deleteProperty(globalThis, SLOT);
|
|
6812
|
+
}
|
|
6813
|
+
await bindings2.exporter.close();
|
|
6814
|
+
};
|
|
6815
|
+
|
|
5356
6816
|
// src/install-global-handlers.ts
|
|
5357
6817
|
var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
|
|
5358
6818
|
var unhandledRejectionMode = () => {
|
|
@@ -5491,7 +6951,7 @@ var installGlobalHandlers = (client, options = {}) => {
|
|
|
5491
6951
|
|
|
5492
6952
|
// src/sdk-meta.ts
|
|
5493
6953
|
var SDK_NAME = "@rasputin-ai/node";
|
|
5494
|
-
var SDK_VERSION = "0.
|
|
6954
|
+
var SDK_VERSION = "0.13.1";
|
|
5495
6955
|
|
|
5496
6956
|
// src/rasputin-init.ts
|
|
5497
6957
|
var publicExecution = (runtime) => ({
|
|
@@ -5507,7 +6967,7 @@ var publicExecution = (runtime) => ({
|
|
|
5507
6967
|
getStats: runtime.getStats
|
|
5508
6968
|
});
|
|
5509
6969
|
var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
|
|
5510
|
-
}, policy) => {
|
|
6970
|
+
}, policy, metrics) => {
|
|
5511
6971
|
const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
|
|
5512
6972
|
};
|
|
5513
6973
|
const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
|
|
@@ -5527,10 +6987,12 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
|
|
|
5527
6987
|
await client.flush(timeoutMs);
|
|
5528
6988
|
if (timeoutMs === void 0) {
|
|
5529
6989
|
await policy?.flush();
|
|
6990
|
+
await metrics?.exporter.flush();
|
|
5530
6991
|
await manifestUpload.wait();
|
|
5531
6992
|
return;
|
|
5532
6993
|
}
|
|
5533
6994
|
await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
|
|
6995
|
+
await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
|
|
5534
6996
|
await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
|
|
5535
6997
|
},
|
|
5536
6998
|
close: async () => {
|
|
@@ -5540,15 +7002,26 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
|
|
|
5540
7002
|
manifestUpload.disconnect();
|
|
5541
7003
|
const startedAt = Date.now();
|
|
5542
7004
|
await policy?.close();
|
|
7005
|
+
await releaseFunctionMetricsBindings(metrics);
|
|
5543
7006
|
await client.close();
|
|
5544
7007
|
await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
|
|
5545
7008
|
}
|
|
5546
7009
|
};
|
|
5547
7010
|
};
|
|
5548
|
-
|
|
7011
|
+
function RasputinInit(options, hooks = {}) {
|
|
5549
7012
|
try {
|
|
5550
7013
|
const enabled = isClientEnabled(options);
|
|
7014
|
+
const activation = resolveClientActivation2(options);
|
|
5551
7015
|
const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
|
|
7016
|
+
const metrics = activation.enabled ? bindFunctionMetrics({
|
|
7017
|
+
options: options.functionMetrics,
|
|
7018
|
+
clientEnabled: true,
|
|
7019
|
+
environment: activation.environment,
|
|
7020
|
+
release: activation.release,
|
|
7021
|
+
ingestToken: activation.ingestToken,
|
|
7022
|
+
apiUrl: activation.apiUrl,
|
|
7023
|
+
fetch: hooks.fetch
|
|
7024
|
+
}) : void 0;
|
|
5552
7025
|
const { runtime, policy } = bindAdaptiveRecorder({
|
|
5553
7026
|
executionRecorder: options.executionRecorder,
|
|
5554
7027
|
recorderEnabled,
|
|
@@ -5560,11 +7033,14 @@ var RasputinInit = (options) => {
|
|
|
5560
7033
|
enabled: options.enabled,
|
|
5561
7034
|
sdkName: SDK_NAME,
|
|
5562
7035
|
sdkVersion: SDK_VERSION,
|
|
5563
|
-
scrubPII: options.scrubPII
|
|
7036
|
+
scrubPII: options.scrubPII,
|
|
7037
|
+
fetch: hooks.fetch,
|
|
7038
|
+
functionMetrics: metrics?.collector
|
|
5564
7039
|
});
|
|
5565
7040
|
const client = createClient(options, {
|
|
5566
7041
|
sdkVersion: SDK_VERSION,
|
|
5567
7042
|
sdkName: SDK_NAME,
|
|
7043
|
+
fetch: hooks.fetch,
|
|
5568
7044
|
installTransportSignalHandlers: options.installTransportSignalHandlers,
|
|
5569
7045
|
redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
|
|
5570
7046
|
resolveObservation: (observation) => runtime.getErrorState(observation)
|
|
@@ -5579,7 +7055,7 @@ var RasputinInit = (options) => {
|
|
|
5579
7055
|
const wrappedClient = withExecution(
|
|
5580
7056
|
client,
|
|
5581
7057
|
runtime,
|
|
5582
|
-
recorderEnabled,
|
|
7058
|
+
recorderEnabled || Boolean(metrics),
|
|
5583
7059
|
{
|
|
5584
7060
|
projectApiKey: options.projectApiKey,
|
|
5585
7061
|
release: options.release,
|
|
@@ -5590,7 +7066,8 @@ var RasputinInit = (options) => {
|
|
|
5590
7066
|
logSuccess: options.logSuccess
|
|
5591
7067
|
},
|
|
5592
7068
|
() => uninstallHandlers(),
|
|
5593
|
-
policy
|
|
7069
|
+
policy,
|
|
7070
|
+
metrics
|
|
5594
7071
|
);
|
|
5595
7072
|
if (enabled && options.installGlobalHandlers !== false) {
|
|
5596
7073
|
uninstallHandlers = installGlobalHandlers(wrappedClient);
|
|
@@ -5612,7 +7089,7 @@ var RasputinInit = (options) => {
|
|
|
5612
7089
|
}
|
|
5613
7090
|
);
|
|
5614
7091
|
}
|
|
5615
|
-
}
|
|
7092
|
+
}
|
|
5616
7093
|
export {
|
|
5617
7094
|
RasputinInit
|
|
5618
7095
|
};
|