@rasputin-ai/node 0.13.0 → 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.
Files changed (49) hide show
  1. package/dist/auto-instrumentation/bun-plugin.d.ts.map +1 -1
  2. package/dist/auto-instrumentation/instrument-compiled-esm.d.ts.map +1 -1
  3. package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts.map +1 -1
  4. package/dist/auto-instrumentation/node-hooks.d.ts.map +1 -1
  5. package/dist/auto-instrumentation/transform-disk-cache.d.ts.map +1 -1
  6. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +4 -2
  7. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
  8. package/dist/execution-recorder/execution-recorder-hooks.d.ts +3 -0
  9. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -1
  10. package/dist/execution-recorder/execution-recorder-types.d.ts +1 -2
  11. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  12. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  13. package/dist/execution-recorder/execution-recording-sync.d.ts +2 -2
  14. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
  15. package/dist/execution-recorder/function-plan.d.ts +3 -1
  16. package/dist/execution-recorder/function-plan.d.ts.map +1 -1
  17. package/dist/function-metrics/bind-function-metrics.d.ts +19 -0
  18. package/dist/function-metrics/bind-function-metrics.d.ts.map +1 -0
  19. package/dist/function-metrics/create-metrics-only-runtime.d.ts +4 -0
  20. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -0
  21. package/dist/function-metrics/encode-function-metrics-upload.d.ts +14 -0
  22. package/dist/function-metrics/encode-function-metrics-upload.d.ts.map +1 -0
  23. package/dist/function-metrics/function-metric-declaration-registry.d.ts +9 -0
  24. package/dist/function-metrics/function-metric-declaration-registry.d.ts.map +1 -0
  25. package/dist/function-metrics/function-metrics-batches.d.ts +35 -0
  26. package/dist/function-metrics/function-metrics-batches.d.ts.map +1 -0
  27. package/dist/function-metrics/function-metrics-collector.d.ts +45 -0
  28. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -0
  29. package/dist/function-metrics/function-metrics-exporter.d.ts +23 -0
  30. package/dist/function-metrics/function-metrics-exporter.d.ts.map +1 -0
  31. package/dist/function-metrics/install-function-metric-declaration-sink.d.ts +2 -0
  32. package/dist/function-metrics/install-function-metric-declaration-sink.d.ts.map +1 -0
  33. package/dist/function-metrics/intern-prepared-metrics.d.ts +4 -0
  34. package/dist/function-metrics/intern-prepared-metrics.d.ts.map +1 -0
  35. package/dist/function-metrics/send-function-metrics-batch.d.ts +25 -0
  36. package/dist/function-metrics/send-function-metrics-batch.d.ts.map +1 -0
  37. package/dist/function-metrics/settle-function-metrics.d.ts +5 -0
  38. package/dist/function-metrics/settle-function-metrics.d.ts.map +1 -0
  39. package/dist/index.js +1592 -121
  40. package/dist/instrument/build.js +450 -140
  41. package/dist/instrument/bun.js +454 -132
  42. package/dist/instrument/node.js +452 -132
  43. package/dist/internal.d.ts +2 -0
  44. package/dist/internal.d.ts.map +1 -1
  45. package/dist/internal.js +1568 -113
  46. package/dist/rasputin-init.d.ts +17 -4
  47. package/dist/rasputin-init.d.ts.map +1 -1
  48. package/dist/sdk-meta.d.ts +1 -1
  49. 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,8 +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
- const callSites = [];
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
+ );
225
230
  const remember = (manifest) => {
226
231
  registry.snapshotCache = {
227
232
  generation: registry.generation,
@@ -234,7 +239,11 @@ var snapshotInstrumentationManifest = (options = {}) => {
234
239
  for (const fn of delta.functions) {
235
240
  const definition = definitionFromEncodedPlan(fn.plan);
236
241
  if (!definition.source) continue;
237
- functions.push({
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),
238
247
  functionId: definition.functionId,
239
248
  source: {
240
249
  packageRelativePath: definition.source.packageRelativePath,
@@ -246,21 +255,23 @@ var snapshotInstrumentationManifest = (options = {}) => {
246
255
  startColumn: fn.startColumn,
247
256
  endLine: fn.endLine,
248
257
  endColumn: fn.endColumn,
258
+ metricsDeclaration: fn.metricsDeclaration,
249
259
  ...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
250
260
  });
251
261
  }
252
262
  for (const site of delta.callSites) {
253
263
  const source = sourceAt(site.filePath, site.line, site.column);
254
264
  if (!source) continue;
255
- callSites.push({
256
- id: stableId(
257
- "cs",
258
- site.callerFunctionId,
259
- source.packageName ?? "",
260
- source.packageRelativePath,
261
- site.line,
262
- site.column
263
- ),
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,
264
275
  callerFunctionId: site.callerFunctionId,
265
276
  calleeName: site.calleeName,
266
277
  calleeText: site.calleeText,
@@ -282,20 +293,21 @@ var snapshotInstrumentationManifest = (options = {}) => {
282
293
  }
283
294
  });
284
295
  }
285
- if (functions.length === 0 && callSites.length === 0) {
296
+ if (functions.size === 0 && callSites.size === 0) {
286
297
  return remember(void 0);
287
298
  }
288
- const packages = { ...options.sourceRoots ?? {} };
299
+ const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
300
+ const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
289
301
  return remember({
290
302
  schema_version: INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
291
- ...options.sourceRoot || Object.keys(packages).length > 0 ? {
303
+ ...sourceRoot || Object.keys(packages).length > 0 ? {
292
304
  sourceRoots: {
293
- ...options.sourceRoot ? { default: options.sourceRoot } : {},
305
+ ...sourceRoot ? { default: sourceRoot } : {},
294
306
  packages
295
307
  }
296
308
  } : {},
297
- functions,
298
- callSites
309
+ functions: [...functions.values()],
310
+ callSites: [...callSites.values()]
299
311
  });
300
312
  };
301
313
  var collectParamsByFunctionId = () => {
@@ -667,13 +679,318 @@ var scheduleInstrumentationManifestUpload = (options) => {
667
679
  };
668
680
 
669
681
  // src/execution-recorder/execution-recorder.ts
670
- import { AsyncLocalStorage } from "node:async_hooks";
682
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
671
683
  import {
684
+ functionMetricsTraceDeclaration as functionMetricsTraceDeclaration3,
672
685
  rasputinOmitted,
673
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,
674
694
  runtimeFunctionId as runtimeFunctionId2
675
695
  } from "@rasputin-ai/core";
676
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
+
677
994
  // src/execution-recorder/adaptive-recording-options.ts
678
995
  var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
679
996
  var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
@@ -750,45 +1067,6 @@ var createDynamicDurationSampleBuckets = (options) => {
750
1067
  };
751
1068
  };
752
1069
 
753
- // src/execution-recorder/error-observation.ts
754
- var bindings = /* @__PURE__ */ new WeakMap();
755
- var mintErrorObservation = (binding) => {
756
- const observation = Object.freeze(/* @__PURE__ */ Object.create(null));
757
- bindings.set(observation, binding);
758
- return observation;
759
- };
760
- var bindingForObservation = (value) => {
761
- if (typeof value !== "object" || value === null) return void 0;
762
- return bindings.get(value);
763
- };
764
- var inertErrorObservation = () => {
765
- return Object.freeze(/* @__PURE__ */ Object.create(null));
766
- };
767
-
768
- // src/execution-recorder/execution-identity.ts
769
- var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
770
- var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
771
- var trimmed = (value) => typeof value === "string" ? value.trim() : "";
772
- var boundedKey = (key) => {
773
- return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
774
- };
775
- var executionTypeKey = (metadata) => {
776
- if (metadata.kind === "http") {
777
- const method = trimmed(metadata.request?.method).toUpperCase();
778
- const route = trimmed(metadata.request?.route);
779
- if (!method || !route) return void 0;
780
- if (route.includes("?") || route.includes("://")) return void 0;
781
- return boundedKey(`http:${method}:${route}`);
782
- }
783
- if (!NAMED_KINDS.has(metadata.kind)) return void 0;
784
- const name = trimmed(metadata.name);
785
- if (!name) return void 0;
786
- return boundedKey(`${metadata.kind}:${name}`);
787
- };
788
- var isHttpClientErrorStatus = (status) => {
789
- return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
790
- };
791
-
792
1070
  // src/execution-recorder/execution-journal.ts
793
1071
  var KIND_ENTER = 1;
794
1072
  var KIND_EXIT = 2;
@@ -1188,10 +1466,6 @@ var ExecutionJournalPool = class {
1188
1466
  }
1189
1467
  };
1190
1468
 
1191
- // src/execution-recorder/function-plan.ts
1192
- var EVENT_PAIR_BASE_ESTIMATED_BYTES = 512;
1193
- var estimatedCallBytesFor = (functionId) => EVENT_PAIR_BASE_ESTIMATED_BYTES + Buffer.byteLength(functionId, "utf8") * 2;
1194
-
1195
1469
  // src/execution-recorder/publish-runtime-state.ts
1196
1470
  var measured = (value) => typeof value === "number";
1197
1471
  var eventsAreFullyTimed = (events) => {
@@ -2690,7 +2964,7 @@ var manualFunctionDefinition = (value) => {
2690
2964
  ...located?.[4] ? { column: Number(located[4]) } : {}
2691
2965
  } : void 0;
2692
2966
  const definition = { name, ...source ? { source } : {} };
2693
- return { ...definition, functionId: runtimeFunctionId2(definition) };
2967
+ return { ...definition, functionId: runtimeFunctionId3(definition) };
2694
2968
  };
2695
2969
  var normalizeFunctionDefinition = (value) => typeof value === "string" ? manualFunctionDefinition(value) : value;
2696
2970
  var elapsedMs2 = (startedAtNs, endedAtNs = process.hrtime.bigint()) => Number(endedAtNs - startedAtNs) / 1e6;
@@ -2731,7 +3005,7 @@ var observeRecordedCallback = function __rasputinHandleRun__3(recording, recorde
2731
3005
  recordExitWork(phaseTimingEnabled ? process.hrtime.bigint() : recorderStartedAtNs);
2732
3006
  return result;
2733
3007
  };
2734
- var emptyStats = {
3008
+ var emptyStats2 = {
2735
3009
  functionCallsObserved: 0,
2736
3010
  functionCallsCaptured: 0,
2737
3011
  functionCallsExcluded: 0,
@@ -2792,7 +3066,7 @@ var noOpExecution = {
2792
3066
  resume: (value) => value
2793
3067
  }),
2794
3068
  trace: (_functionId, fn) => fn,
2795
- getStats: () => ({ ...emptyStats }),
3069
+ getStats: () => ({ ...emptyStats2 }),
2796
3070
  close: () => {
2797
3071
  }
2798
3072
  };
@@ -2826,7 +3100,16 @@ var newSuppression = (group, parentCallId, startedAtNs, endedAtNs, timed) => {
2826
3100
  var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
2827
3101
  var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
2828
3102
  var createExecutionRecorder = (options, hooks = {}) => {
2829
- if (!options?.enabled) return noOpExecution;
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
+ };
2830
3113
  warnIfMissingAsyncContextFrame();
2831
3114
  const adaptiveEnabled = options.adaptive?.enabled === true;
2832
3115
  const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
@@ -2848,7 +3131,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
2848
3131
  if (!key) return false;
2849
3132
  return keyIsActive(snapshot, key, atMs);
2850
3133
  };
2851
- const storage = new AsyncLocalStorage();
3134
+ const storage = new AsyncLocalStorage2();
2852
3135
  const currentStore = () => {
2853
3136
  try {
2854
3137
  return storage.getStore();
@@ -3099,7 +3382,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
3099
3382
  functionId: definition.functionId,
3100
3383
  excluded: excludesSource(definition),
3101
3384
  estimatedCallBytes: estimatedCallBytesFor(definition.functionId),
3102
- omitCallValues: false
3385
+ omitCallValues: false,
3386
+ metricsDeclaration: functionMetricDeclarationFor(definition.functionId)
3103
3387
  });
3104
3388
  internedPlans.set(definition.functionId, plan);
3105
3389
  return plan;
@@ -3117,7 +3401,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
3117
3401
  functionId: withParams.functionId,
3118
3402
  excluded: excludesSource(withParams),
3119
3403
  estimatedCallBytes: estimatedCallBytesFor(withParams.functionId),
3120
- omitCallValues: encodedPlanOmitsCallValues(encoded)
3404
+ omitCallValues: encodedPlanOmitsCallValues(encoded),
3405
+ metricsDeclaration: functionMetricDeclarationFor(withParams.functionId)
3121
3406
  });
3122
3407
  });
3123
3408
  preparedModules.set(plans, prepared);
@@ -3636,7 +3921,10 @@ var createExecutionRecorder = (options, hooks = {}) => {
3636
3921
  }
3637
3922
  const recorderStartedAtNs = process.hrtime.bigint();
3638
3923
  recording.finished = true;
3639
- if (metadata) mergeExecutionMetadata(recording.execution, metadata);
3924
+ if (metadata) {
3925
+ mergeExecutionMetadata(recording.execution, metadata);
3926
+ bindMetricsExecution(recording);
3927
+ }
3640
3928
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3641
3929
  if (recording.runFailed && !recording.hasError) {
3642
3930
  retainFailure(recording);
@@ -3705,6 +3993,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3705
3993
  sessionCaptureSnapshot
3706
3994
  };
3707
3995
  if (identityComplete) tryAdmitLiveSession(recording);
3996
+ bindMetricsExecution(recording);
3708
3997
  stats.activeExecutions++;
3709
3998
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3710
3999
  liveRecordings.push(recording);
@@ -3756,6 +4045,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
3756
4045
  try {
3757
4046
  mergeExecutionMetadata(recording.execution, nextMetadata);
3758
4047
  completeIdentityFromSnapshot(recording);
4048
+ bindMetricsExecution(recording);
3759
4049
  } catch {
3760
4050
  }
3761
4051
  }
@@ -3772,9 +4062,22 @@ var createExecutionRecorder = (options, hooks = {}) => {
3772
4062
  }
3773
4063
  };
3774
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
+ };
3775
4078
  let startedCallback = false;
3776
4079
  try {
3777
- return runPreparedFunctionFromStoreInner(
4080
+ const result = runPreparedFunctionFromStoreInner(
3778
4081
  store,
3779
4082
  plan,
3780
4083
  args,
@@ -3784,9 +4087,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
3784
4087
  },
3785
4088
  omitValues
3786
4089
  );
4090
+ settle(result, false);
4091
+ return result;
3787
4092
  } catch (error) {
3788
- if (startedCallback) throw error;
3789
- return callback();
4093
+ if (startedCallback) {
4094
+ settle(error, true);
4095
+ throw error;
4096
+ }
4097
+ const result = callback();
4098
+ settle(result, false);
4099
+ return result;
3790
4100
  }
3791
4101
  };
3792
4102
  const runPreparedFunctionFromStoreInner = function __rasputinHandleRun__4(store, plan, args, callback, omitValues) {
@@ -3991,6 +4301,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
3991
4301
  this.group = group;
3992
4302
  this.captureDroppedThrow = captureDroppedThrow;
3993
4303
  this.callerClaimed = false;
4304
+ this.metricsOpen = false;
4305
+ this.metricsFailed = false;
4306
+ this.metricsFunctionHandle = 0;
4307
+ this.metricsExecutionHandle = 0;
4308
+ this.metricsStartedNs = 0n;
3994
4309
  }
3995
4310
  claimCaller() {
3996
4311
  if (this.callerClaimed || !durationSamplingEnabled || !this.plan) return;
@@ -4025,6 +4340,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4025
4340
  try {
4026
4341
  if (this.status === "failed") return;
4027
4342
  this.status = "failed";
4343
+ this.metricsFailed = true;
4028
4344
  if (this.mode === "captured") writeCapturedThrow(this, error);
4029
4345
  else if (this.mode === "suppressed" && this.plan) {
4030
4346
  captureCompletedThrow(
@@ -4053,18 +4369,38 @@ var createExecutionRecorder = (options, hooks = {}) => {
4053
4369
  }
4054
4370
  }
4055
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
+ }
4056
4388
  if (this.mode === "expired") return;
4057
4389
  try {
4058
4390
  if (this.status !== "failed") {
4059
4391
  if (this.mode === "captured") {
4060
- writeCapturedExit(this, this.status === "left" ? this.pendingReturn : void 0);
4392
+ writeCapturedExit(
4393
+ this,
4394
+ this.status === "left" ? this.pendingReturn : void 0,
4395
+ endedAtNs
4396
+ );
4061
4397
  } else if (this.mode === "suppressed" && this.group) {
4062
4398
  recordSuppressedCall(
4063
4399
  this.recording,
4064
4400
  this.group,
4065
4401
  this.parentCallId,
4066
4402
  this.startedAtNs,
4067
- this.timed ? readCallClock() : 0n,
4403
+ this.timed ? endedAtNs ?? readCallClock() : 0n,
4068
4404
  this.timed
4069
4405
  );
4070
4406
  } else if (this.mode === "dropped") {
@@ -4137,9 +4473,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
4137
4473
  const expectStore = (frame, expected) => {
4138
4474
  if (currentStore() !== expected && frame.plan) degradeAttribution(frame.recording, frame.plan);
4139
4475
  };
4140
- const writeCapturedExit = (frame, value) => {
4476
+ const writeCapturedExit = (frame, value, completedAtNs) => {
4141
4477
  if (!frame.recording.journal) return;
4142
- const endedAtNs = frame.timed ? readCallClock() : void 0;
4478
+ const endedAtNs = frame.timed ? completedAtNs ?? readCallClock() : void 0;
4143
4479
  const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
4144
4480
  if (endedAtNs !== void 0) {
4145
4481
  frame.recording.journal.finishCall(
@@ -4174,6 +4510,24 @@ var createExecutionRecorder = (options, hooks = {}) => {
4174
4510
  stats.functionCallsCaptured++;
4175
4511
  capturedError.commit();
4176
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
+ };
4177
4531
  const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow) => {
4178
4532
  const frame = new CallFrame(
4179
4533
  mode,
@@ -4192,6 +4546,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4192
4546
  );
4193
4547
  frame.claimCaller();
4194
4548
  enterStore(frame, parentStore);
4549
+ armCallFrameMetrics(frame, plan);
4195
4550
  return frame;
4196
4551
  };
4197
4552
  const enterPreparedFunctionFromStore = (store, plan, args, omitValues) => {
@@ -4203,7 +4558,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4203
4558
  if (store.recording.finished) {
4204
4559
  if (!store.recording.budgetExpired && !store.recording.evicted) return noopHandle2;
4205
4560
  const expiredStore = { recording: store.recording };
4206
- return new CallFrame(
4561
+ const expired = new CallFrame(
4207
4562
  "expired",
4208
4563
  store.recording,
4209
4564
  expiredStore,
@@ -4218,6 +4573,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4218
4573
  void 0,
4219
4574
  false
4220
4575
  );
4576
+ armCallFrameMetrics(expired, plan);
4577
+ return expired;
4221
4578
  }
4222
4579
  stats.functionCallsObserved++;
4223
4580
  const recording = store.recording;
@@ -4242,6 +4599,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4242
4599
  false
4243
4600
  );
4244
4601
  enterStore(frame, excludedStore);
4602
+ armCallFrameMetrics(frame, plan);
4245
4603
  return frame;
4246
4604
  }
4247
4605
  recording.inFlightCalls++;
@@ -4355,6 +4713,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4355
4713
  false
4356
4714
  );
4357
4715
  enterStore(captured, callStore);
4716
+ armCallFrameMetrics(captured, plan);
4358
4717
  return captured;
4359
4718
  };
4360
4719
  const runPreparedFunction = (plan, args, callback, omitValues) => {
@@ -4395,8 +4754,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
4395
4754
  };
4396
4755
  const prepareFunctionPlans = (plans) => preparedPlansFor(plans);
4397
4756
  function trace(input, fn) {
4398
- const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId2(input) };
4757
+ const definition = typeof input === "string" ? manualFunctionDefinition(input) : { ...input, functionId: runtimeFunctionId3(input) };
4399
4758
  const plan = preparePlan(definition);
4759
+ plan.metricsDeclaration ??= functionMetricsTraceDeclaration3({
4760
+ runtimeId: definition.functionId
4761
+ });
4400
4762
  return function __rasputinHandleRun__4(...args) {
4401
4763
  if (new.target) {
4402
4764
  throw new TypeError("execution.trace() wraps function calls, not constructors");
@@ -4689,10 +5051,9 @@ var abortFrom = (parent, child) => {
4689
5051
  return () => parent.removeEventListener("abort", onAbort);
4690
5052
  };
4691
5053
  var createExecutionRecordingCoordinator = (options) => {
4692
- const environment = trimmed2(options.environment);
5054
+ const environment = options.environment;
4693
5055
  const nowMs = () => options.nowMs?.() ?? Date.now();
4694
5056
  const fetchFn = options.fetch ?? defaultIngestFetch();
4695
- const networkEnabled = environment.length > 0;
4696
5057
  const instanceId = crypto.randomUUID();
4697
5058
  const startedAt = /* @__PURE__ */ new Date();
4698
5059
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
@@ -4945,8 +5306,7 @@ var createExecutionRecordingCoordinator = (options) => {
4945
5306
  }
4946
5307
  };
4947
5308
  const kickNotify = () => {
4948
- if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
4949
- return;
5309
+ if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
4950
5310
  void drainNotifies(notifySignal());
4951
5311
  };
4952
5312
  const rememberCatalog = (key, atMs) => {
@@ -5025,7 +5385,7 @@ var createExecutionRecordingCoordinator = (options) => {
5025
5385
  return entries;
5026
5386
  };
5027
5387
  const syncOnce = async (signal) => {
5028
- if (!networkEnabled || closed) return;
5388
+ if (closed) return;
5029
5389
  const types2 = catalogTypes();
5030
5390
  try {
5031
5391
  const { response, body: payload } = await postJson(
@@ -5178,7 +5538,7 @@ var createExecutionRecordingCoordinator = (options) => {
5178
5538
  }
5179
5539
  };
5180
5540
  const kickRecordings = () => {
5181
- if (!networkEnabled || closed || closing || recordings.length === 0) return;
5541
+ if (closed || closing || recordings.length === 0) return;
5182
5542
  if (recordingPump) return;
5183
5543
  const running = drainRecordings(recordingSignal());
5184
5544
  recordingPump = running;
@@ -5196,7 +5556,7 @@ var createExecutionRecordingCoordinator = (options) => {
5196
5556
  if (existing !== void 0 && existing > atMs) return;
5197
5557
  cache.set(key, window.expiresAtMs);
5198
5558
  trimCache();
5199
- if (!networkEnabled || window.expiresAtMs <= atMs) return;
5559
+ if (window.expiresAtMs <= atMs) return;
5200
5560
  if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
5201
5561
  for (const oldest of pending.keys()) {
5202
5562
  if (oldest !== sendingKey) {
@@ -5241,22 +5601,20 @@ var createExecutionRecordingCoordinator = (options) => {
5241
5601
  recordings.push(payload);
5242
5602
  kickRecordings();
5243
5603
  };
5244
- if (networkEnabled) {
5245
- const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
5246
- const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
5247
- const delay = interval + Math.floor(Math.random() * jitterMax);
5248
- pollStartTimer = setTimeout(() => {
5249
- pollStartTimer = void 0;
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(() => {
5250
5612
  if (closed || closing) return;
5251
5613
  void runSyncOnce(pollSignal());
5252
- pollTimer = setInterval(() => {
5253
- if (closed || closing) return;
5254
- void runSyncOnce(pollSignal());
5255
- }, interval);
5256
- pollTimer.unref?.();
5257
- }, delay);
5258
- pollStartTimer.unref?.();
5259
- }
5614
+ }, interval);
5615
+ pollTimer.unref?.();
5616
+ }, delay);
5617
+ pollStartTimer.unref?.();
5260
5618
  const stopTimers = () => {
5261
5619
  if (pollStartTimer) {
5262
5620
  clearTimeout(pollStartTimer);
@@ -5280,7 +5638,7 @@ var createExecutionRecordingCoordinator = (options) => {
5280
5638
  lastAdaptiveFailureKind: lastFailureKind
5281
5639
  }),
5282
5640
  flush: async (timeoutMs = 2e3) => {
5283
- if (!networkEnabled || closed || closing) return;
5641
+ if (closed || closing) return;
5284
5642
  const flushAbort = new AbortController();
5285
5643
  const onAbort = () => interruptWork();
5286
5644
  flushAbort.signal.addEventListener("abort", onAbort, { once: true });
@@ -5305,7 +5663,7 @@ var createExecutionRecordingCoordinator = (options) => {
5305
5663
  interruptWork();
5306
5664
  }, 2e3);
5307
5665
  try {
5308
- if (networkEnabled) await runSyncOnce(deadline.signal);
5666
+ await runSyncOnce(deadline.signal);
5309
5667
  if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
5310
5668
  await joinUntil(recordingPump, deadline.signal);
5311
5669
  if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
@@ -5328,10 +5686,11 @@ var bindAdaptiveRecorder = (input) => {
5328
5686
  dsn: input.dsn,
5329
5687
  projectApiKey: input.projectApiKey,
5330
5688
  apiUrl: input.apiUrl,
5331
- release: input.release
5689
+ release: input.release,
5690
+ environment: input.environment
5332
5691
  });
5333
5692
  const coordinator = input.recorderEnabled && activation.enabled && options?.sessions !== false ? createExecutionRecordingCoordinator({
5334
- environment: input.environment ?? "",
5693
+ environment: activation.environment,
5335
5694
  ingestToken: activation.ingestToken,
5336
5695
  activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5337
5696
  syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
@@ -5344,21 +5703,1116 @@ var bindAdaptiveRecorder = (input) => {
5344
5703
  mode: adaptiveEnabled ? "adaptive" : "full",
5345
5704
  fetch: input.fetch
5346
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;
5347
5717
  const runtime = createExecutionRecorder(
5348
5718
  { ...options, enabled: input.recorderEnabled },
5349
- coordinator ? {
5350
- policySnapshot: coordinator.peek,
5351
- onQualifyingFailure: adaptiveEnabled ? coordinator.activate : void 0,
5352
- getStats: coordinator.getStats,
5353
- sessionCaptureSnapshot: coordinator.peekSessions,
5354
- consumeSession: coordinator.consumeSession,
5355
- observeExecutionType: coordinator.observeType,
5356
- onSessionRecording: coordinator.enqueueRecording
5357
- } : void 0
5719
+ recorderHooks
5358
5720
  );
5359
5721
  return { runtime, policy: coordinator };
5360
5722
  };
5361
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
+
5362
6816
  // src/install-global-handlers.ts
5363
6817
  var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
5364
6818
  var unhandledRejectionMode = () => {
@@ -5497,7 +6951,7 @@ var installGlobalHandlers = (client, options = {}) => {
5497
6951
 
5498
6952
  // src/sdk-meta.ts
5499
6953
  var SDK_NAME = "@rasputin-ai/node";
5500
- var SDK_VERSION = "0.13.0";
6954
+ var SDK_VERSION = "0.13.1";
5501
6955
 
5502
6956
  // src/rasputin-init.ts
5503
6957
  var publicExecution = (runtime) => ({
@@ -5513,7 +6967,7 @@ var publicExecution = (runtime) => ({
5513
6967
  getStats: runtime.getStats
5514
6968
  });
5515
6969
  var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
5516
- }, policy) => {
6970
+ }, policy, metrics) => {
5517
6971
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
5518
6972
  };
5519
6973
  const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
@@ -5533,10 +6987,12 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
5533
6987
  await client.flush(timeoutMs);
5534
6988
  if (timeoutMs === void 0) {
5535
6989
  await policy?.flush();
6990
+ await metrics?.exporter.flush();
5536
6991
  await manifestUpload.wait();
5537
6992
  return;
5538
6993
  }
5539
6994
  await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
6995
+ await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
5540
6996
  await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
5541
6997
  },
5542
6998
  close: async () => {
@@ -5546,15 +7002,26 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
5546
7002
  manifestUpload.disconnect();
5547
7003
  const startedAt = Date.now();
5548
7004
  await policy?.close();
7005
+ await releaseFunctionMetricsBindings(metrics);
5549
7006
  await client.close();
5550
7007
  await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
5551
7008
  }
5552
7009
  };
5553
7010
  };
5554
- var RasputinInit = (options) => {
7011
+ function RasputinInit(options, hooks = {}) {
5555
7012
  try {
5556
7013
  const enabled = isClientEnabled(options);
7014
+ const activation = resolveClientActivation2(options);
5557
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;
5558
7025
  const { runtime, policy } = bindAdaptiveRecorder({
5559
7026
  executionRecorder: options.executionRecorder,
5560
7027
  recorderEnabled,
@@ -5566,11 +7033,14 @@ var RasputinInit = (options) => {
5566
7033
  enabled: options.enabled,
5567
7034
  sdkName: SDK_NAME,
5568
7035
  sdkVersion: SDK_VERSION,
5569
- scrubPII: options.scrubPII
7036
+ scrubPII: options.scrubPII,
7037
+ fetch: hooks.fetch,
7038
+ functionMetrics: metrics?.collector
5570
7039
  });
5571
7040
  const client = createClient(options, {
5572
7041
  sdkVersion: SDK_VERSION,
5573
7042
  sdkName: SDK_NAME,
7043
+ fetch: hooks.fetch,
5574
7044
  installTransportSignalHandlers: options.installTransportSignalHandlers,
5575
7045
  redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
5576
7046
  resolveObservation: (observation) => runtime.getErrorState(observation)
@@ -5585,7 +7055,7 @@ var RasputinInit = (options) => {
5585
7055
  const wrappedClient = withExecution(
5586
7056
  client,
5587
7057
  runtime,
5588
- recorderEnabled,
7058
+ recorderEnabled || Boolean(metrics),
5589
7059
  {
5590
7060
  projectApiKey: options.projectApiKey,
5591
7061
  release: options.release,
@@ -5596,7 +7066,8 @@ var RasputinInit = (options) => {
5596
7066
  logSuccess: options.logSuccess
5597
7067
  },
5598
7068
  () => uninstallHandlers(),
5599
- policy
7069
+ policy,
7070
+ metrics
5600
7071
  );
5601
7072
  if (enabled && options.installGlobalHandlers !== false) {
5602
7073
  uninstallHandlers = installGlobalHandlers(wrappedClient);
@@ -5618,7 +7089,7 @@ var RasputinInit = (options) => {
5618
7089
  }
5619
7090
  );
5620
7091
  }
5621
- };
7092
+ }
5622
7093
  export {
5623
7094
  RasputinInit
5624
7095
  };