@monocle.sh/adonisjs-agent 1.0.0-beta.11 → 1.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -81,7 +81,7 @@ try {
81
81
  The `config/monocle.ts` file supports the following options:
82
82
 
83
83
  ```typescript
84
- import { defineConfig } from '@monocle.sh/adonisjs-agent'
84
+ import { defineConfig, destinations } from '@monocle.sh/adonisjs-agent'
85
85
  import env from '#start/env'
86
86
 
87
87
  export default defineConfig({
@@ -96,6 +96,14 @@ export default defineConfig({
96
96
  serviceVersion: env.get('APP_VERSION'),
97
97
  environment: env.get('APP_ENV'),
98
98
 
99
+ // Additional OTLP destinations (Monocle is always injected automatically)
100
+ destinations: {
101
+ grafana: destinations.otlp({
102
+ endpoint: env.get('GRAFANA_OTLP_ENDPOINT'),
103
+ signals: 'all',
104
+ }),
105
+ },
106
+
99
107
  // Host metrics (CPU, Memory, Network, etc.)
100
108
  // Set to false to disable
101
109
  hostMetrics: {
@@ -108,13 +116,13 @@ export default defineConfig({
108
116
  exclude: ['make:*', 'generate:*', 'queue:work', 'queue:listen'],
109
117
  },
110
118
 
111
- // Trace batching configuration
119
+ // Trace/log batching configuration for Monocle destination
112
120
  batch: {
113
121
  maxExportBatchSize: 512,
114
122
  scheduledDelayMillis: 5000,
115
123
  },
116
124
 
117
- // Enable gzip compression (default: true)
125
+ // Enable gzip compression for Monocle destination (default: true)
118
126
  compression: true,
119
127
  })
120
128
  ```
package/dist/index.d.mts CHANGED
@@ -4,4 +4,5 @@ import { Monocle } from "./src/monocle.mjs";
4
4
  import { configure } from "./configure.mjs";
5
5
  import { extractTraceContext, getCurrentSpan, handleError, injectTraceContext, otelLoggingPreset, record, recordEvent, setAttributes } from "./helpers.mjs";
6
6
  import { SpanAllOptions, SpanOptions, span, spanAll } from "./decorators.mjs";
7
- export { type BatchConfig, type CliTracingConfig, type HostMetricsConfig, Monocle, type MonocleConfig, type SpanAllOptions, type SpanOptions, configure, defineConfig, extractTraceContext, getCurrentSpan, handleError, injectTraceContext, otelLoggingPreset, record, recordEvent, setAttributes, span, spanAll };
7
+ import { destinations } from "@adonisjs/otel";
8
+ export { type BatchConfig, type CliTracingConfig, type HostMetricsConfig, Monocle, type MonocleConfig, type SpanAllOptions, type SpanOptions, configure, defineConfig, destinations, extractTraceContext, getCurrentSpan, handleError, injectTraceContext, otelLoggingPreset, record, recordEvent, setAttributes, span, spanAll };
package/dist/index.mjs CHANGED
@@ -3,5 +3,6 @@ import { Monocle } from "./src/monocle.mjs";
3
3
  import { configure } from "./configure.mjs";
4
4
  import { extractTraceContext, getCurrentSpan, handleError, injectTraceContext, otelLoggingPreset, record, recordEvent, setAttributes } from "./helpers.mjs";
5
5
  import { span, spanAll } from "./decorators.mjs";
6
+ import { destinations } from "@adonisjs/otel";
6
7
 
7
- export { Monocle, configure, defineConfig, extractTraceContext, getCurrentSpan, handleError, injectTraceContext, otelLoggingPreset, record, recordEvent, setAttributes, span, spanAll };
8
+ export { Monocle, configure, defineConfig, destinations, extractTraceContext, getCurrentSpan, handleError, injectTraceContext, otelLoggingPreset, record, recordEvent, setAttributes, span, spanAll };
package/dist/init.mjs CHANGED
@@ -8,12 +8,6 @@ import { createAddHookMessageChannel } from "import-in-the-middle";
8
8
  * Also stolen and tweaked from @adonisjs/otel in order to use our own config file.
9
9
  * Need to be able to remove this file in the future.
10
10
  */
11
- const DEFAULT_BATCH_CONFIG = {
12
- maxExportBatchSize: 512,
13
- scheduledDelayMillis: 5e3,
14
- exportTimeoutMillis: 3e4,
15
- maxQueueSize: 2048
16
- };
17
11
  async function loadConfig(path) {
18
12
  return await import(pathToFileURL(path).href).then((mod) => mod.default || mod).catch((error) => {
19
13
  throw new Error(`Failed to load Monocle config file at "${path}"`, { cause: error });
@@ -24,49 +18,13 @@ function setupHooks() {
24
18
  register("import-in-the-middle/hook.mjs", import.meta.url, registerOptions);
25
19
  return waitForAllMessagesAcknowledged;
26
20
  }
27
- /**
28
- * Create a metric reader for exporting metrics via OTLP
29
- */
30
- async function createMetricReader(config) {
31
- const { PeriodicExportingMetricReader } = await import("@opentelemetry/sdk-metrics");
32
- const { OTLPMetricExporter } = await import("@opentelemetry/exporter-metrics-otlp-http");
33
- return new PeriodicExportingMetricReader({
34
- exporter: new OTLPMetricExporter({ compression: config.compression !== false ? "gzip" : void 0 }),
35
- exportIntervalMillis: 6e4
36
- });
37
- }
38
- /**
39
- * Create a BatchSpanProcessor for efficient trace export with compression
40
- */
41
- async function createSpanProcessor(config) {
42
- const { BatchSpanProcessor } = await import("@opentelemetry/sdk-trace-base");
43
- const { OTLPTraceExporter } = await import("@opentelemetry/exporter-trace-otlp-http");
44
- const compression = config.compression !== false ? "gzip" : void 0;
45
- const batchConfig = {
46
- ...DEFAULT_BATCH_CONFIG,
47
- ...config.batch
48
- };
49
- return new BatchSpanProcessor(new OTLPTraceExporter({ compression }), {
50
- maxExportBatchSize: batchConfig.maxExportBatchSize,
51
- scheduledDelayMillis: batchConfig.scheduledDelayMillis,
52
- exportTimeoutMillis: batchConfig.exportTimeoutMillis,
53
- maxQueueSize: batchConfig.maxQueueSize
54
- });
55
- }
56
21
  async function init(dirname) {
57
22
  const waitForAllMessagesAcknowledged = setupHooks();
58
23
  const { OtelManager } = await import("@adonisjs/otel/manager");
59
24
  const config = await loadConfig(join(dirname, "config/monocle.js"));
60
25
  if (!config) return;
61
26
  if (!OtelManager.isEnabled(config)) return;
62
- const metricReader = await createMetricReader(config);
63
- const spanProcessor = await createSpanProcessor(config);
64
- const configWithProcessors = {
65
- ...config,
66
- metricReader,
67
- spanProcessors: [spanProcessor, ...config.spanProcessors || []]
68
- };
69
- const manager = OtelManager.create(configWithProcessors);
27
+ const manager = OtelManager.create(config);
70
28
  manager?.start();
71
29
  const shutdown = async () => {
72
30
  await manager?.shutdown().catch(() => {});
@@ -116,6 +74,20 @@ async function init(dirname) {
116
74
  const { instrumentMail } = await import("./src/instrumentations/mail/instrumentation.mjs");
117
75
  await instrumentMail(mailConfig ?? { enabled: true }, dirname);
118
76
  }
77
+ /**
78
+ * Cache Instrumentation
79
+ *
80
+ * Automatically instruments @adonisjs/cache (bentocache) if installed.
81
+ * Creates spans for cache operations (get, set, getOrSet, delete, etc.)
82
+ * and suppresses internal Redis/L2/bus spans.
83
+ *
84
+ * @see ./instrumentations/cache/instrumentation.ts for implementation details
85
+ */
86
+ const cacheConfig = config.cache;
87
+ if (cacheConfig !== false) {
88
+ const { instrumentCache } = await import("./src/instrumentations/cache/instrumentation.mjs");
89
+ await instrumentCache(cacheConfig ?? { enabled: true }, dirname);
90
+ }
119
91
  await waitForAllMessagesAcknowledged();
120
92
  }
121
93
 
@@ -1,7 +1,7 @@
1
1
  import { ExceptionReporter, toHttpError } from "./src/exception_reporter.mjs";
2
+ import { OtelManager } from "@adonisjs/otel";
2
3
  import { getCurrentSpan } from "@adonisjs/otel/helpers";
3
4
  import OtelMiddleware from "@adonisjs/otel/otel_middleware";
4
- import { OtelManager } from "@adonisjs/otel";
5
5
  import { ExceptionHandler } from "@adonisjs/core/http";
6
6
  import { configProvider } from "@adonisjs/core";
7
7
 
@@ -3,7 +3,6 @@ import { MonocleConfig } from "./types.mjs";
3
3
  //#region src/define_config.d.ts
4
4
  /**
5
5
  * Define and validate Monocle agent configuration.
6
- * Sets up environment variables for OTEL exporters to point to Monocle.
7
6
  * Returns undefined if no API key is provided (telemetry will be disabled).
8
7
  */
9
8
  declare function defineConfig(config: MonocleConfig): MonocleConfig | undefined;
@@ -1,4 +1,12 @@
1
+ import { destinations } from "@adonisjs/otel";
2
+
1
3
  //#region src/define_config.ts
4
+ const DEFAULT_BATCH_CONFIG = {
5
+ maxExportBatchSize: 512,
6
+ scheduledDelayMillis: 5e3,
7
+ exportTimeoutMillis: 3e4,
8
+ maxQueueSize: 2048
9
+ };
2
10
  /**
3
11
  * Extracts a header value from either ServerResponse (getHeader) or IncomingMessage (headers object).
4
12
  */
@@ -42,15 +50,17 @@ function extractUserResponseHook(httpConfig) {
42
50
  }
43
51
  /**
44
52
  * Define and validate Monocle agent configuration.
45
- * Sets up environment variables for OTEL exporters to point to Monocle.
46
53
  * Returns undefined if no API key is provided (telemetry will be disabled).
47
54
  */
48
55
  function defineConfig(config) {
49
56
  if (!config.apiKey) return;
50
57
  const endpoint = config.endpoint || "https://ingest.monocle.sh";
51
58
  const environment = config.environment || process.env.NODE_ENV || "development";
52
- process.env.OTEL_EXPORTER_OTLP_ENDPOINT = endpoint;
53
- process.env.OTEL_EXPORTER_OTLP_HEADERS = `x-api-key=${config.apiKey},x-monocle-env=${environment}`;
59
+ const compression = config.compression === false ? "none" : "gzip";
60
+ const batchConfig = {
61
+ ...DEFAULT_BATCH_CONFIG,
62
+ ...config.batch
63
+ };
54
64
  const httpConfig = config.instrumentations?.["@opentelemetry/instrumentation-http"];
55
65
  const userResponseHook = extractUserResponseHook(httpConfig);
56
66
  const instrumentations = {
@@ -60,11 +70,28 @@ function defineConfig(config) {
60
70
  responseHook: createConnectionTypeHook(userResponseHook)
61
71
  }
62
72
  };
73
+ const monocleDestination = destinations.otlp({
74
+ endpoint,
75
+ signals: "all",
76
+ compression,
77
+ headers: {
78
+ "x-api-key": config.apiKey,
79
+ "x-monocle-env": environment
80
+ },
81
+ maxExportBatchSize: batchConfig.maxExportBatchSize,
82
+ scheduledDelayMillis: batchConfig.scheduledDelayMillis,
83
+ exportTimeoutMillis: batchConfig.exportTimeoutMillis,
84
+ maxQueueSize: batchConfig.maxQueueSize
85
+ });
63
86
  return {
64
87
  ...config,
65
88
  endpoint,
66
89
  environment,
67
- instrumentations
90
+ instrumentations,
91
+ destinations: {
92
+ ...config.destinations,
93
+ monocle: monocleDestination
94
+ }
68
95
  };
69
96
  }
70
97
 
@@ -0,0 +1,46 @@
1
+ import { createRequire } from "node:module";
2
+ import { pathToFileURL } from "node:url";
3
+ import { BentoCacheInstrumentation } from "@bentocache/otel";
4
+
5
+ //#region src/instrumentations/cache/instrumentation.ts
6
+ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ const numericPattern = /^\d+$/;
8
+ const hexPattern = /^[0-9a-f]{8,}$/i;
9
+ /**
10
+ * Replaces dynamic-looking segments (UUIDs, numeric IDs, hex hashes)
11
+ * with `*` to reduce cardinality in span attributes.
12
+ */
13
+ function defaultKeySanitizer(key) {
14
+ if (!key) return key;
15
+ return key.split(":").map((segment) => {
16
+ if (uuidPattern.test(segment)) return "*";
17
+ if (numericPattern.test(segment)) return "*";
18
+ if (hexPattern.test(segment)) return "*";
19
+ return segment;
20
+ }).join(":");
21
+ }
22
+ /**
23
+ * Auto-instruments @adonisjs/cache (bentocache) with OpenTelemetry spans
24
+ * for cache operations (get, set, getOrSet, delete, etc.).
25
+ * Internal Redis/L2/bus spans are suppressed via `suppressInternalOperations`.
26
+ */
27
+ async function instrumentCache(config, appRoot) {
28
+ if (config.enabled === false) return void 0;
29
+ const appRequire = createRequire(appRoot ? pathToFileURL(`${appRoot}/package.json`).href : import.meta.url);
30
+ try {
31
+ appRequire.resolve("@adonisjs/cache");
32
+ } catch {
33
+ return;
34
+ }
35
+ const instrumentation = new BentoCacheInstrumentation({
36
+ requireParentSpan: config.requireParentSpan ?? false,
37
+ includeKeys: config.includeKeys ?? true,
38
+ keySanitizer: config.keySanitizer ?? defaultKeySanitizer,
39
+ suppressInternalOperations: true
40
+ });
41
+ instrumentation.enable();
42
+ return instrumentation;
43
+ }
44
+
45
+ //#endregion
46
+ export { instrumentCache };
@@ -15,6 +15,14 @@ interface CaptureMessageContext extends CaptureContext {
15
15
  level?: MessageLevel;
16
16
  }
17
17
  type CaptureExceptionContext = CaptureContext;
18
+ /**
19
+ * User information for tracing. When displayed in the Monocle UI,
20
+ * `name` takes priority over `email` as the display label, with
21
+ * `email` used as fallback.
22
+ */
23
+ interface MonocleUser extends UserContextResult {
24
+ name?: string;
25
+ }
18
26
  /**
19
27
  * Monocle helper class for manual instrumentation.
20
28
  */
@@ -41,8 +49,10 @@ declare class Monocle {
41
49
  static captureMessage(message: string, levelOrContext?: MessageLevel | CaptureMessageContext): Promise<void>;
42
50
  /**
43
51
  * Set user information on the current active span.
52
+ * `name` is displayed with priority over `email` in the Monocle UI.
53
+ * Falls back to `email`, then `id`.
44
54
  */
45
- static setUser(user: UserContextResult): void;
55
+ static setUser(user: MonocleUser): void;
46
56
  }
47
57
  //#endregion
48
- export { Monocle };
58
+ export { Monocle, MonocleUser };
@@ -100,6 +100,8 @@ var Monocle = class {
100
100
  }
101
101
  /**
102
102
  * Set user information on the current active span.
103
+ * `name` is displayed with priority over `email` in the Monocle UI.
104
+ * Falls back to `email`, then `id`.
103
105
  */
104
106
  static setUser(user) {
105
107
  setUser(user);
@@ -1,6 +1,11 @@
1
- import { OtelConfig } from "@adonisjs/otel/types";
1
+ import { DestinationMap, OtelConfig } from "@adonisjs/otel/types";
2
+ import { BentoCacheInstrumentationConfig } from "@bentocache/otel/types";
2
3
 
3
4
  //#region src/types.d.ts
5
+ /**
6
+ * Configuration for cache instrumentation
7
+ */
8
+ interface CacheInstrumentationConfig extends BentoCacheInstrumentationConfig {}
4
9
  /**
5
10
  * Configuration for mail instrumentation
6
11
  */
@@ -95,6 +100,12 @@ interface MonocleConfig extends Omit<OtelConfig, 'traceExporter' | 'metricExport
95
100
  * @default process.env.NODE_ENV || 'development'
96
101
  */
97
102
  environment?: string;
103
+ /**
104
+ * Additional OTLP destinations (Grafana, Honeycomb, etc.).
105
+ *
106
+ * Monocle destination is always injected automatically and cannot be removed.
107
+ */
108
+ destinations?: DestinationMap;
98
109
  /**
99
110
  * Host metrics configuration (CPU, Memory, Network, etc.).
100
111
  * Set to `false` to disable, or pass config object.
@@ -125,6 +136,13 @@ interface MonocleConfig extends Omit<OtelConfig, 'traceExporter' | 'metricExport
125
136
  * @default { enabled: true }
126
137
  */
127
138
  mail?: false | MailInstrumentationConfig;
139
+ /**
140
+ * Cache instrumentation configuration.
141
+ * Automatically instruments @adonisjs/cache (bentocache) if installed.
142
+ * Set to `false` to disable.
143
+ * @default { enabled: true }
144
+ */
145
+ cache?: false | CacheInstrumentationConfig;
128
146
  }
129
147
  //#endregion
130
148
  export { BatchConfig, CliTracingConfig, HostMetricsConfig, MonocleConfig };
package/dist/types.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { BatchConfig, CliTracingConfig, HostMetricsConfig, MonocleConfig } from "./src/types.mjs";
2
+ import { MonocleUser } from "./src/monocle.mjs";
2
3
  import { SpanAllOptions, SpanOptions } from "./decorators.mjs";
3
- import { HeadersCarrier, OtelLoggingPresetOptions, UserContextResult } from "@adonisjs/otel/types";
4
- export { type BatchConfig, type CliTracingConfig, type HeadersCarrier, type HostMetricsConfig, type MonocleConfig, type OtelLoggingPresetOptions, type SpanAllOptions, type SpanOptions, type UserContextResult };
4
+ import { DestinationConfig, DestinationMap, DestinationSignal, DestinationSignals, HeadersCarrier, OtelLoggingPresetOptions, OtlpDestinationConfig, OtlpDestinationOptions, UserContextResult } from "@adonisjs/otel/types";
5
+ export { type BatchConfig, type CliTracingConfig, type DestinationConfig, type DestinationMap, type DestinationSignal, type DestinationSignals, type HeadersCarrier, type HostMetricsConfig, type MonocleConfig, type MonocleUser, type OtelLoggingPresetOptions, type OtlpDestinationConfig, type OtlpDestinationOptions, type SpanAllOptions, type SpanOptions, type UserContextResult };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monocle.sh/adonisjs-agent",
3
- "version": "1.0.0-beta.11",
3
+ "version": "1.0.0-beta.13",
4
4
  "description": "Monocle agent for AdonisJS - sends telemetry to Monocle cloud",
5
5
  "keywords": [
6
6
  "adonisjs",
@@ -31,7 +31,8 @@
31
31
  "tag": "beta"
32
32
  },
33
33
  "dependencies": {
34
- "@adonisjs/otel": "^1.1.2",
34
+ "@adonisjs/otel": "^1.2.0",
35
+ "@bentocache/otel": "^0.1.2",
35
36
  "@opentelemetry/api": "^1.9.0",
36
37
  "@opentelemetry/core": "^2.5.0",
37
38
  "@opentelemetry/exporter-metrics-otlp-http": "^0.211.0",