@unieai/rabi-otel 0.0.0-stage → 0.2.2-rc.5
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/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/index.js +409 -0
- package/lib/types/event-log.d.ts +53 -0
- package/lib/types/event-transport.d.ts +10 -0
- package/lib/types/index.d.ts +31 -0
- package/lib/types/session-log.d.ts +72 -0
- package/lib/types/transport.d.ts +33 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +42 -4
- package/src/event-log.ts +94 -0
- package/src/event-transport.ts +57 -0
- package/src/index.ts +35 -0
- package/src/session-log.ts +228 -0
- package/src/transport.ts +61 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unieai/rabi-otel
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cordis service for independent ordinary-event and byte-bounded Session-log OTLP channels
|
|
4
|
+
|
|
5
|
+
Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
|
|
6
|
+
not meant to be used on its own.
|
|
7
|
+
|
|
8
|
+
See LICENSE for the license and copyright of this package.
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import { Service } from "@unieai/cordis";
|
|
2
|
+
import { addAbortListener } from "node:events";
|
|
3
|
+
import { SeverityNumber } from "@opentelemetry/api-logs";
|
|
4
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
5
|
+
import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
6
|
+
import { BatchLogRecordProcessor, LoggerProvider } from "@opentelemetry/sdk-logs";
|
|
7
|
+
import { gzipSync } from "node:zlib";
|
|
8
|
+
import got from "got";
|
|
9
|
+
import { OTLPExporterBase, createOtlpNetworkExportDelegate, getSharedConfigurationDefaults, mergeOtlpSharedConfigurationWithDefaults } from "@opentelemetry/otlp-exporter-base";
|
|
10
|
+
import { JsonLogsSerializer, LogsExporterMetricsHelper } from "@opentelemetry/otlp-transformer";
|
|
11
|
+
import { createOtlpHttpExportDelegate, createOtlpHttpExporterMetrics, getSharedConfigurationFromEnvironment, httpAgentFactoryFromOptions } from "@opentelemetry/otlp-exporter-base/node-http";
|
|
12
|
+
//#region lib/types/transport.js
|
|
13
|
+
/** Explicit OTLP JSON transport for feedback-authorized Session logs. */
|
|
14
|
+
/** `otel.component.type` reported by OTLP HTTP log exporter self-observability metrics. */
|
|
15
|
+
const OTLP_HTTP_LOG_EXPORTER_COMPONENT_TYPE = "otlp_http_log_exporter";
|
|
16
|
+
/**
|
|
17
|
+
* Create an SDK JSON exporter without inheriting another collector's headers or TLS identity.
|
|
18
|
+
* @param options - explicit endpoint, headers, agent, and SDK transport settings.
|
|
19
|
+
* @returns the exporter owned by one independent log pipeline.
|
|
20
|
+
*/
|
|
21
|
+
function createLogExporter(options) {
|
|
22
|
+
return new OTLPExporterBase(createOtlpHttpExportDelegate(logTransportOptions(options), JsonLogsSerializer, OTLP_HTTP_LOG_EXPORTER_COMPONENT_TYPE, LogsExporterMetricsHelper, void 0));
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Create one log exporter's self-observability metrics; without a meter provider they record nothing.
|
|
26
|
+
* @param url - collector endpoint recorded as the metrics server address and port.
|
|
27
|
+
* @returns the metrics recorder required by an OTLP HTTP log export delegate.
|
|
28
|
+
*/
|
|
29
|
+
function createLogExporterMetrics(url) {
|
|
30
|
+
return createOtlpHttpExporterMetrics(OTLP_HTTP_LOG_EXPORTER_COMPONENT_TYPE, LogsExporterMetricsHelper, url, void 0);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Resolve collector-local headers and agents with shared SDK timeout and compression defaults.
|
|
34
|
+
* @param options - explicit endpoint and SDK HTTP settings.
|
|
35
|
+
* @returns resolved transport settings without ambient credentials.
|
|
36
|
+
*/
|
|
37
|
+
function logTransportOptions(options) {
|
|
38
|
+
return {
|
|
39
|
+
...mergeOtlpSharedConfigurationWithDefaults(options, getSharedConfigurationFromEnvironment("LOGS"), getSharedConfigurationDefaults()),
|
|
40
|
+
url: options.url,
|
|
41
|
+
headers: async () => ({
|
|
42
|
+
"Content-Type": "application/json",
|
|
43
|
+
...typeof options.headers === "function" ? await options.headers() : options.headers
|
|
44
|
+
}),
|
|
45
|
+
agentFactory: typeof options.httpAgentOptions === "function" ? options.httpAgentOptions : httpAgentFactoryFromOptions({
|
|
46
|
+
keepAlive: options.keepAlive ?? true,
|
|
47
|
+
...options.httpAgentOptions
|
|
48
|
+
}),
|
|
49
|
+
...options.userAgent === void 0 ? {} : { userAgent: options.userAgent }
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region lib/types/event-transport.js
|
|
54
|
+
/**
|
|
55
|
+
* Create a channel-owned exporter whose cancellation releases requests and retry timers.
|
|
56
|
+
* @param options - explicit collector and SDK HTTP settings.
|
|
57
|
+
* @param signal - channel cancellation, shared by current and future batch exports.
|
|
58
|
+
* @returns the SDK exporter; shutdown also destroys its owned HTTP agent.
|
|
59
|
+
*/
|
|
60
|
+
function createEventLogExporter(options, signal) {
|
|
61
|
+
const config = logTransportOptions(options);
|
|
62
|
+
let agent;
|
|
63
|
+
const exporter = new OTLPExporterBase(createOtlpNetworkExportDelegate(config, JsonLogsSerializer, createLogExporterMetrics(config.url), {
|
|
64
|
+
async send(data, timeoutMillis) {
|
|
65
|
+
signal.throwIfAborted();
|
|
66
|
+
agent ??= config.agentFactory(new URL(config.url).protocol);
|
|
67
|
+
const selectedAgent = await agent;
|
|
68
|
+
const headers = await config.headers();
|
|
69
|
+
signal.throwIfAborted();
|
|
70
|
+
const compressed = config.compression === "gzip";
|
|
71
|
+
const request = got.post(config.url, {
|
|
72
|
+
body: compressed ? gzipSync(data) : Buffer.from(data),
|
|
73
|
+
headers: {
|
|
74
|
+
...headers,
|
|
75
|
+
...compressed ? { "content-encoding": "gzip" } : {},
|
|
76
|
+
...config.userAgent === void 0 ? {} : { "user-agent": config.userAgent }
|
|
77
|
+
},
|
|
78
|
+
agent: new URL(config.url).protocol === "https:" ? { https: selectedAgent } : { http: selectedAgent },
|
|
79
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMillis)]),
|
|
80
|
+
followRedirect: false,
|
|
81
|
+
retry: {
|
|
82
|
+
limit: 5,
|
|
83
|
+
methods: ["POST"],
|
|
84
|
+
statusCodes: [
|
|
85
|
+
429,
|
|
86
|
+
502,
|
|
87
|
+
503,
|
|
88
|
+
504
|
|
89
|
+
],
|
|
90
|
+
errorCodes: [],
|
|
91
|
+
backoffLimit: 5e3
|
|
92
|
+
},
|
|
93
|
+
responseType: "buffer"
|
|
94
|
+
});
|
|
95
|
+
request.on("downloadProgress", ({ transferred }) => {
|
|
96
|
+
if (transferred > 4 * 1024 * 1024) request.cancel();
|
|
97
|
+
});
|
|
98
|
+
const response = await request;
|
|
99
|
+
if (response.statusCode >= 300) throw new Error(`OTLP collector returned HTTP ${response.statusCode}`);
|
|
100
|
+
return {
|
|
101
|
+
status: "success",
|
|
102
|
+
data: response.body
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
shutdown() {}
|
|
106
|
+
}));
|
|
107
|
+
let shutdown;
|
|
108
|
+
return {
|
|
109
|
+
export: (records, callback) => {
|
|
110
|
+
exporter.export(records, callback);
|
|
111
|
+
},
|
|
112
|
+
forceFlush: () => exporter.forceFlush(),
|
|
113
|
+
shutdown() {
|
|
114
|
+
shutdown ??= (async () => {
|
|
115
|
+
try {
|
|
116
|
+
await exporter.shutdown();
|
|
117
|
+
} finally {
|
|
118
|
+
(await agent)?.destroy();
|
|
119
|
+
}
|
|
120
|
+
})();
|
|
121
|
+
return shutdown;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region lib/types/event-log.js
|
|
127
|
+
/** One caller-owned ordinary-event queue, independent of every Session-log queue. */
|
|
128
|
+
var EventLogReporter = class {
|
|
129
|
+
exporter;
|
|
130
|
+
provider;
|
|
131
|
+
logger;
|
|
132
|
+
cancellation = new AbortController();
|
|
133
|
+
/** @param options - explicit transport, resource, scope, queue, and diagnostic settings. */
|
|
134
|
+
constructor(options) {
|
|
135
|
+
const exporter = createEventLogExporter(options.exporter, this.cancellation.signal);
|
|
136
|
+
this.exporter = exporter;
|
|
137
|
+
this.provider = new LoggerProvider({
|
|
138
|
+
resource: resourceFromAttributes(options.resourceAttributes),
|
|
139
|
+
processors: [new BatchLogRecordProcessor({
|
|
140
|
+
...options.processor,
|
|
141
|
+
exporter: {
|
|
142
|
+
export: (records, callback) => {
|
|
143
|
+
exporter.export(records, (result) => {
|
|
144
|
+
if (result.code !== ExportResultCode.SUCCESS) options.onFailure("Product telemetry export failed", result.error);
|
|
145
|
+
callback(result);
|
|
146
|
+
});
|
|
147
|
+
},
|
|
148
|
+
forceFlush: () => exporter.forceFlush(),
|
|
149
|
+
shutdown: () => exporter.shutdown()
|
|
150
|
+
}
|
|
151
|
+
})]
|
|
152
|
+
});
|
|
153
|
+
this.logger = this.provider.getLogger(options.scope.name, options.scope.version);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Enqueue caller-selected analytics fields without acknowledging delivery.
|
|
157
|
+
* @param record - the ordinary event to report.
|
|
158
|
+
*/
|
|
159
|
+
emit(record) {
|
|
160
|
+
const severityNumber = record.severityNumber ?? SeverityNumber.INFO;
|
|
161
|
+
this.logger.emit({
|
|
162
|
+
...record,
|
|
163
|
+
observedTimestamp: Date.now(),
|
|
164
|
+
severityNumber,
|
|
165
|
+
severityText: SeverityNumber[severityNumber]
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Drain the queue and release its transport, cancelling remaining exports when the caller aborts.
|
|
170
|
+
* @param signal - optional shutdown deadline; abort discards pending exports and cancels retry waits.
|
|
171
|
+
* @returns completion of SDK shutdown and transport cleanup.
|
|
172
|
+
*/
|
|
173
|
+
async shutdown(signal) {
|
|
174
|
+
const abort = () => {
|
|
175
|
+
this.cancellation.abort(signal?.reason);
|
|
176
|
+
};
|
|
177
|
+
const listener = signal === void 0 ? void 0 : addAbortListener(signal, abort);
|
|
178
|
+
if (signal?.aborted) abort();
|
|
179
|
+
try {
|
|
180
|
+
await this.provider.shutdown();
|
|
181
|
+
} finally {
|
|
182
|
+
try {
|
|
183
|
+
await this.exporter.shutdown();
|
|
184
|
+
} finally {
|
|
185
|
+
listener?.[Symbol.dispose]();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region lib/types/session-log.js
|
|
192
|
+
/** Collector request ceiling in uncompressed UTF-8 bytes, including the OTLP envelope. */
|
|
193
|
+
const SESSION_LOG_MAX_REQUEST_BYTES = 4e6;
|
|
194
|
+
/**
|
|
195
|
+
* Validate byte and queue settings before constructing an SDK pipeline.
|
|
196
|
+
* @param options - Session-specific limits supplied by the owning composition.
|
|
197
|
+
* @returns the resolved collector request limit.
|
|
198
|
+
*/
|
|
199
|
+
function resolveSessionLogLimits(options) {
|
|
200
|
+
const limit = options.maxRequestBytes ?? 4e6;
|
|
201
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 4e6) throw new Error(`session log maxRequestBytes must be an integer between 1 and ${SESSION_LOG_MAX_REQUEST_BYTES}`);
|
|
202
|
+
for (const key of [
|
|
203
|
+
"maxQueueSize",
|
|
204
|
+
"maxExportBatchSize",
|
|
205
|
+
"scheduledDelayMillis",
|
|
206
|
+
"exportTimeoutMillis"
|
|
207
|
+
]) {
|
|
208
|
+
const value = options.processor?.[key];
|
|
209
|
+
if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) throw new Error(`session log processor.${key} must be a positive integer no greater than 2147483647`);
|
|
210
|
+
}
|
|
211
|
+
const queue = options.processor?.maxQueueSize ?? 2048;
|
|
212
|
+
if ((options.processor?.maxExportBatchSize ?? 512) > queue) throw new Error("session log maxExportBatchSize must not exceed maxQueueSize");
|
|
213
|
+
return limit;
|
|
214
|
+
}
|
|
215
|
+
/** Byte/count batching with one transport request in flight, including after a watchdog warning. */
|
|
216
|
+
var SessionLogProcessor = class {
|
|
217
|
+
exporter;
|
|
218
|
+
limit;
|
|
219
|
+
config;
|
|
220
|
+
warn;
|
|
221
|
+
queue = [];
|
|
222
|
+
bytes = 0;
|
|
223
|
+
timer;
|
|
224
|
+
active;
|
|
225
|
+
shutdownPromise;
|
|
226
|
+
stopped = false;
|
|
227
|
+
constructor(exporter, limit, config, warn) {
|
|
228
|
+
this.exporter = exporter;
|
|
229
|
+
this.limit = limit;
|
|
230
|
+
this.config = config;
|
|
231
|
+
this.warn = warn;
|
|
232
|
+
}
|
|
233
|
+
onEmit(record) {
|
|
234
|
+
if (this.stopped) return;
|
|
235
|
+
if (this.queue.length >= this.config.maxQueueSize) {
|
|
236
|
+
this.warn("Session log queue is full; record rejected");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
let bytes;
|
|
240
|
+
try {
|
|
241
|
+
const serialized = JsonLogsSerializer.serializeRequest([record]);
|
|
242
|
+
if (serialized === void 0) throw new Error("Session log serialization produced no request");
|
|
243
|
+
bytes = serialized.byteLength;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this.warn("Session log serialization failed; record rejected", error instanceof Error ? error : new Error(String(error)));
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (bytes > this.limit) {
|
|
249
|
+
this.warn("Session log record rejected; content was not truncated", /* @__PURE__ */ new Error(`Session log record exceeds maxRequestBytes: ${bytes} > ${this.limit}`));
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
this.queue.push({
|
|
253
|
+
record,
|
|
254
|
+
bytes
|
|
255
|
+
});
|
|
256
|
+
this.bytes += bytes;
|
|
257
|
+
if (this.active !== void 0) return;
|
|
258
|
+
if (this.queue.length >= this.config.maxExportBatchSize || this.bytes >= this.limit) this.forceFlush();
|
|
259
|
+
else if (this.timer === void 0) {
|
|
260
|
+
this.timer = setTimeout(() => {
|
|
261
|
+
this.forceFlush();
|
|
262
|
+
}, this.config.scheduledDelayMillis);
|
|
263
|
+
this.timer.unref();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
forceFlush() {
|
|
267
|
+
clearTimeout(this.timer);
|
|
268
|
+
this.timer = void 0;
|
|
269
|
+
if (this.active !== void 0) return this.active;
|
|
270
|
+
if (this.queue.length === 0) return Promise.resolve();
|
|
271
|
+
this.active = this.drain();
|
|
272
|
+
return this.active;
|
|
273
|
+
}
|
|
274
|
+
async drain() {
|
|
275
|
+
try {
|
|
276
|
+
while (!this.stopped && this.queue.length > 0) {
|
|
277
|
+
let bytes = 0;
|
|
278
|
+
let count = 0;
|
|
279
|
+
for (const entry of this.queue) {
|
|
280
|
+
if (count === this.config.maxExportBatchSize || bytes + entry.bytes > this.limit) break;
|
|
281
|
+
bytes += entry.bytes;
|
|
282
|
+
count++;
|
|
283
|
+
}
|
|
284
|
+
const records = this.queue.splice(0, count).map((entry) => entry.record);
|
|
285
|
+
this.bytes -= bytes;
|
|
286
|
+
await this.send(records);
|
|
287
|
+
await this.exporter.forceFlush();
|
|
288
|
+
}
|
|
289
|
+
} finally {
|
|
290
|
+
this.active = void 0;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
send(records) {
|
|
294
|
+
return new Promise((resolve) => {
|
|
295
|
+
const timer = setTimeout(() => {
|
|
296
|
+
this.warn("Session log request exceeded exportTimeoutMillis; waiting for transport settlement");
|
|
297
|
+
}, this.config.exportTimeoutMillis);
|
|
298
|
+
timer.unref();
|
|
299
|
+
const finish = (error) => {
|
|
300
|
+
clearTimeout(timer);
|
|
301
|
+
if (error !== void 0) this.warn("Session log export failed", error);
|
|
302
|
+
resolve();
|
|
303
|
+
};
|
|
304
|
+
try {
|
|
305
|
+
this.exporter.export(records, (result) => {
|
|
306
|
+
finish(result.code === ExportResultCode.SUCCESS ? void 0 : result.error ?? /* @__PURE__ */ new Error("Session log HTTP export failed"));
|
|
307
|
+
});
|
|
308
|
+
} catch (error) {
|
|
309
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
stopPending() {
|
|
314
|
+
this.stopped = true;
|
|
315
|
+
this.queue.length = 0;
|
|
316
|
+
this.bytes = 0;
|
|
317
|
+
clearTimeout(this.timer);
|
|
318
|
+
this.timer = void 0;
|
|
319
|
+
}
|
|
320
|
+
shutdown() {
|
|
321
|
+
this.shutdownPromise ??= this.forceFlush().then(() => this.exporter.shutdown());
|
|
322
|
+
return this.shutdownPromise;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
/** Owns feedback-authorized Session logs; no product-event provider or queue is mounted. */
|
|
326
|
+
var SessionLogReporter = class {
|
|
327
|
+
provider;
|
|
328
|
+
processor;
|
|
329
|
+
logger;
|
|
330
|
+
/** @param options - explicit transport, resource identity, queue limits, and diagnostics. */
|
|
331
|
+
constructor(options) {
|
|
332
|
+
const limit = resolveSessionLogLimits(options);
|
|
333
|
+
this.processor = new SessionLogProcessor(createLogExporter(options.exporter), limit, {
|
|
334
|
+
maxQueueSize: options.processor?.maxQueueSize ?? 2048,
|
|
335
|
+
maxExportBatchSize: options.processor?.maxExportBatchSize ?? 512,
|
|
336
|
+
scheduledDelayMillis: options.processor?.scheduledDelayMillis ?? 1e3,
|
|
337
|
+
exportTimeoutMillis: options.processor?.exportTimeoutMillis ?? 3e4
|
|
338
|
+
}, options.onFailure);
|
|
339
|
+
this.provider = new LoggerProvider({
|
|
340
|
+
logRecordLimits: {
|
|
341
|
+
attributeValueLengthLimit: Infinity,
|
|
342
|
+
attributeCountLimit: Infinity
|
|
343
|
+
},
|
|
344
|
+
resource: resourceFromAttributes(options.resourceAttributes),
|
|
345
|
+
processors: [this.processor]
|
|
346
|
+
});
|
|
347
|
+
this.logger = this.provider.getLogger(options.scope.name, options.scope.version);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Enqueue one complete event without acknowledging network delivery.
|
|
351
|
+
* @param record - event with redacted data and its original Session id.
|
|
352
|
+
*/
|
|
353
|
+
reportSessionLog(record) {
|
|
354
|
+
const severityNumber = record.severityNumber ?? SeverityNumber.INFO;
|
|
355
|
+
this.logger.emit({
|
|
356
|
+
eventName: "session-log",
|
|
357
|
+
body: "session-log",
|
|
358
|
+
timestamp: record.event.time,
|
|
359
|
+
observedTimestamp: record.event.time,
|
|
360
|
+
severityNumber,
|
|
361
|
+
severityText: SeverityNumber[severityNumber],
|
|
362
|
+
attributes: {
|
|
363
|
+
...record.attributes,
|
|
364
|
+
sessionId: record.sessionId,
|
|
365
|
+
content: JSON.stringify(record.event)
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
/** Stop queued requests after the owning backend's shutdown deadline; an active transport may still settle. */
|
|
370
|
+
stopPending() {
|
|
371
|
+
this.processor.stopPending();
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Drain queued requests and release the SDK transport.
|
|
375
|
+
* @returns completion after queued requests settle and the SDK transport shuts down.
|
|
376
|
+
*/
|
|
377
|
+
shutdown() {
|
|
378
|
+
return this.provider.shutdown();
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
//#endregion
|
|
382
|
+
//#region lib/types/index.js
|
|
383
|
+
/** Cordis entry for independent ordinary-event and Session-log OTLP channels. */
|
|
384
|
+
/** Shared transport provider. Mounting creates no queue, identity, or network connection. */
|
|
385
|
+
var OTel = class extends Service {
|
|
386
|
+
constructor(ctx) {
|
|
387
|
+
super(ctx, "otel");
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Create an independent ordinary-event channel with count-based batching.
|
|
391
|
+
* The injected consumer must drain it during its fiber disposal.
|
|
392
|
+
* @param options - transport, scope, resource, queue, and diagnostic settings selected by the consumer.
|
|
393
|
+
* @returns the caller-owned channel; no state is shared with other channels.
|
|
394
|
+
*/
|
|
395
|
+
createEventReporter(options) {
|
|
396
|
+
return new EventLogReporter(options);
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Create an independent byte-bounded Session-log channel.
|
|
400
|
+
* Authorization and redaction precede reporting; the consumer owns shutdown and its outer deadline.
|
|
401
|
+
* @param options - transport, scope, resource, queue, and diagnostic settings selected by the consumer.
|
|
402
|
+
* @returns the caller-owned channel, preserving complete accepted events within the request byte ceiling.
|
|
403
|
+
*/
|
|
404
|
+
createSessionLogReporter(options) {
|
|
405
|
+
return new SessionLogReporter(options);
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
//#endregion
|
|
409
|
+
export { OTel as default };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Ordinary event SDK batching over a cancellable HTTP transport. */
|
|
2
|
+
import type { Attributes } from '@opentelemetry/api';
|
|
3
|
+
import { SeverityNumber } from '@opentelemetry/api-logs';
|
|
4
|
+
import type { BatchLogRecordProcessorOptions } from '@opentelemetry/sdk-logs';
|
|
5
|
+
import type { SessionLogOptions } from './session-log.ts';
|
|
6
|
+
import type { LogExporterOptions } from './transport.ts';
|
|
7
|
+
/** Scalar values accepted by the collector's Arrow attributes map. */
|
|
8
|
+
export type OTelEventScalar = string | number | boolean;
|
|
9
|
+
/** Explicitly selected analytics fields; object values may contain scalars only. */
|
|
10
|
+
export interface OTelEventRecord {
|
|
11
|
+
/** Product/DA-owned event name. */
|
|
12
|
+
eventName: string;
|
|
13
|
+
/** Human-readable summary; never a prompt, response, credential, or file contents. */
|
|
14
|
+
body: string;
|
|
15
|
+
/** Event occurrence time in Unix milliseconds. Observation time is assigned on enqueue. */
|
|
16
|
+
timestamp: number;
|
|
17
|
+
/** OTel severity; omitted values use INFO. */
|
|
18
|
+
severityNumber?: SeverityNumber;
|
|
19
|
+
/** Business fields selected by the caller; no automatic device or account identity. */
|
|
20
|
+
attributes?: Record<string, OTelEventScalar | Record<string, OTelEventScalar>>;
|
|
21
|
+
}
|
|
22
|
+
/** Ordinary-event transport, resource, scope, and count-batching options. */
|
|
23
|
+
export interface EventLogOptions {
|
|
24
|
+
exporter: LogExporterOptions;
|
|
25
|
+
resourceAttributes: Attributes;
|
|
26
|
+
scope: {
|
|
27
|
+
name: string;
|
|
28
|
+
version?: string;
|
|
29
|
+
};
|
|
30
|
+
processor: Omit<BatchLogRecordProcessorOptions, 'exporter'>;
|
|
31
|
+
onFailure: SessionLogOptions['onFailure'];
|
|
32
|
+
}
|
|
33
|
+
/** One caller-owned ordinary-event queue, independent of every Session-log queue. */
|
|
34
|
+
export declare class EventLogReporter {
|
|
35
|
+
private readonly exporter;
|
|
36
|
+
private readonly provider;
|
|
37
|
+
private readonly logger;
|
|
38
|
+
private readonly cancellation;
|
|
39
|
+
/** @param options - explicit transport, resource, scope, queue, and diagnostic settings. */
|
|
40
|
+
constructor(options: EventLogOptions);
|
|
41
|
+
/**
|
|
42
|
+
* Enqueue caller-selected analytics fields without acknowledging delivery.
|
|
43
|
+
* @param record - the ordinary event to report.
|
|
44
|
+
*/
|
|
45
|
+
emit(record: OTelEventRecord): void;
|
|
46
|
+
/**
|
|
47
|
+
* Drain the queue and release its transport, cancelling remaining exports when the caller aborts.
|
|
48
|
+
* @param signal - optional shutdown deadline; abort discards pending exports and cancels retry waits.
|
|
49
|
+
* @returns completion of SDK shutdown and transport cleanup.
|
|
50
|
+
*/
|
|
51
|
+
shutdown(signal?: AbortSignal): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=event-log.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { LogRecordExporter } from '@opentelemetry/sdk-logs';
|
|
2
|
+
import { type LogExporterOptions } from './transport.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Create a channel-owned exporter whose cancellation releases requests and retry timers.
|
|
5
|
+
* @param options - explicit collector and SDK HTTP settings.
|
|
6
|
+
* @param signal - channel cancellation, shared by current and future batch exports.
|
|
7
|
+
* @returns the SDK exporter; shutdown also destroys its owned HTTP agent.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createEventLogExporter(options: LogExporterOptions, signal: AbortSignal): LogRecordExporter;
|
|
10
|
+
//# sourceMappingURL=event-transport.d.ts.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Cordis entry for independent ordinary-event and Session-log OTLP channels. */
|
|
2
|
+
import { Context, Service } from '@unieai/cordis';
|
|
3
|
+
import { EventLogReporter, type EventLogOptions } from './event-log.ts';
|
|
4
|
+
import { SessionLogReporter, type SessionLogOptions } from './session-log.ts';
|
|
5
|
+
declare module '@unieai/cordis' {
|
|
6
|
+
interface Context {
|
|
7
|
+
otel: OTel;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Shared transport provider. Mounting creates no queue, identity, or network connection. */
|
|
11
|
+
export default class OTel extends Service {
|
|
12
|
+
constructor(ctx: Context);
|
|
13
|
+
/**
|
|
14
|
+
* Create an independent ordinary-event channel with count-based batching.
|
|
15
|
+
* The injected consumer must drain it during its fiber disposal.
|
|
16
|
+
* @param options - transport, scope, resource, queue, and diagnostic settings selected by the consumer.
|
|
17
|
+
* @returns the caller-owned channel; no state is shared with other channels.
|
|
18
|
+
*/
|
|
19
|
+
createEventReporter(options: EventLogOptions): EventLogReporter;
|
|
20
|
+
/**
|
|
21
|
+
* Create an independent byte-bounded Session-log channel.
|
|
22
|
+
* Authorization and redaction precede reporting; the consumer owns shutdown and its outer deadline.
|
|
23
|
+
* @param options - transport, scope, resource, queue, and diagnostic settings selected by the consumer.
|
|
24
|
+
* @returns the caller-owned channel, preserving complete accepted events within the request byte ceiling.
|
|
25
|
+
*/
|
|
26
|
+
createSessionLogReporter(options: SessionLogOptions): SessionLogReporter;
|
|
27
|
+
}
|
|
28
|
+
export type { EventLogOptions, OTelEventRecord, OTelEventScalar, EventLogReporter } from './event-log.ts';
|
|
29
|
+
export type { SessionLogProcessorOptions, SessionLogRecord, SessionLogOptions, SessionLogReporter } from './session-log.ts';
|
|
30
|
+
export type { LogExporterOptions } from './transport.ts';
|
|
31
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Session-log records in an independent byte-bounded OTLP queue. */
|
|
2
|
+
import type { SessionEvent, SessionId } from '@unieai/rabi-session';
|
|
3
|
+
import type { Attributes } from '@opentelemetry/api';
|
|
4
|
+
import { SeverityNumber } from '@opentelemetry/api-logs';
|
|
5
|
+
import { type BatchLogRecordProcessorOptions } from '@opentelemetry/sdk-logs';
|
|
6
|
+
import { type LogExporterOptions } from './transport.ts';
|
|
7
|
+
/** Collector request ceiling in uncompressed UTF-8 bytes, including the OTLP envelope. */
|
|
8
|
+
export declare const SESSION_LOG_MAX_REQUEST_BYTES = 4000000;
|
|
9
|
+
/** One canonical event with its separately owned Session identity and redacted payload. */
|
|
10
|
+
export interface SessionLogRecord {
|
|
11
|
+
sessionId: SessionId;
|
|
12
|
+
/** Complete event envelope; data is the capture policy's exported copy. */
|
|
13
|
+
event: Omit<SessionEvent, 'data'> & {
|
|
14
|
+
data: unknown;
|
|
15
|
+
};
|
|
16
|
+
/** Additional capture metadata; sessionId and content are always assigned by the reporter. */
|
|
17
|
+
attributes?: Attributes;
|
|
18
|
+
/** Omitted values use INFO. */
|
|
19
|
+
severityNumber?: SeverityNumber;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Byte and count batching fields implemented by {@link SessionLogProcessor}.
|
|
23
|
+
*
|
|
24
|
+
* `exporter` belongs to the owning channel, and `selfObsMeterProvider` is
|
|
25
|
+
* excluded because this processor implements no self-observability metering.
|
|
26
|
+
*/
|
|
27
|
+
export type SessionLogProcessorOptions = Omit<BatchLogRecordProcessorOptions, 'exporter' | 'selfObsMeterProvider'>;
|
|
28
|
+
/** Session-log transport and byte/count queue settings. */
|
|
29
|
+
export interface SessionLogOptions {
|
|
30
|
+
/** Explicit destination and SDK transport settings; exporter self-observability metering is not supported. */
|
|
31
|
+
exporter: LogExporterOptions;
|
|
32
|
+
/** Session-only queue settings, independent of product-event aggregation. */
|
|
33
|
+
processor?: SessionLogProcessorOptions;
|
|
34
|
+
/** May lower, but never exceed, the collector's 4,000,000-byte limit. */
|
|
35
|
+
maxRequestBytes?: number;
|
|
36
|
+
/** Instrumentation scope supplied by the business owner. */
|
|
37
|
+
scope: {
|
|
38
|
+
name: string;
|
|
39
|
+
version?: string;
|
|
40
|
+
};
|
|
41
|
+
/** Application and anonymous identity carried on the OTLP resource. */
|
|
42
|
+
resourceAttributes: Attributes;
|
|
43
|
+
/** Report rejected single records and network failures without recording their content. */
|
|
44
|
+
onFailure: (message: string, error?: Error) => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Validate byte and queue settings before constructing an SDK pipeline.
|
|
48
|
+
* @param options - Session-specific limits supplied by the owning composition.
|
|
49
|
+
* @returns the resolved collector request limit.
|
|
50
|
+
*/
|
|
51
|
+
export declare function resolveSessionLogLimits(options: Pick<SessionLogOptions, 'maxRequestBytes' | 'processor'>): number;
|
|
52
|
+
/** Owns feedback-authorized Session logs; no product-event provider or queue is mounted. */
|
|
53
|
+
export declare class SessionLogReporter {
|
|
54
|
+
private readonly provider;
|
|
55
|
+
private readonly processor;
|
|
56
|
+
private readonly logger;
|
|
57
|
+
/** @param options - explicit transport, resource identity, queue limits, and diagnostics. */
|
|
58
|
+
constructor(options: SessionLogOptions);
|
|
59
|
+
/**
|
|
60
|
+
* Enqueue one complete event without acknowledging network delivery.
|
|
61
|
+
* @param record - event with redacted data and its original Session id.
|
|
62
|
+
*/
|
|
63
|
+
reportSessionLog(record: SessionLogRecord): void;
|
|
64
|
+
/** Stop queued requests after the owning backend's shutdown deadline; an active transport may still settle. */
|
|
65
|
+
stopPending(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Drain queued requests and release the SDK transport.
|
|
68
|
+
* @returns completion after queued requests settle and the SDK transport shuts down.
|
|
69
|
+
*/
|
|
70
|
+
shutdown(): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=session-log.d.ts.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Explicit OTLP JSON transport for feedback-authorized Session logs. */
|
|
2
|
+
import { createOtlpHttpExportDelegate } from '@opentelemetry/otlp-exporter-base/node-http';
|
|
3
|
+
import { type ExporterMetrics, type OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base';
|
|
4
|
+
import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs';
|
|
5
|
+
/**
|
|
6
|
+
* Collector and SDK HTTP settings accepted by this package's log exporters.
|
|
7
|
+
*
|
|
8
|
+
* `OTLPExporterConfigBase.selfObsMeterProvider` is excluded: every channel here
|
|
9
|
+
* passes no meter provider to the exporter metrics recorder, which stays noop.
|
|
10
|
+
*/
|
|
11
|
+
export type LogExporterOptions = Omit<OTLPExporterNodeConfigBase, 'selfObsMeterProvider'> & {
|
|
12
|
+
/** Full HTTP(S) logs destination. */
|
|
13
|
+
url: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Create an SDK JSON exporter without inheriting another collector's headers or TLS identity.
|
|
17
|
+
* @param options - explicit endpoint, headers, agent, and SDK transport settings.
|
|
18
|
+
* @returns the exporter owned by one independent log pipeline.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createLogExporter(options: LogExporterOptions): LogRecordExporter;
|
|
21
|
+
/**
|
|
22
|
+
* Create one log exporter's self-observability metrics; without a meter provider they record nothing.
|
|
23
|
+
* @param url - collector endpoint recorded as the metrics server address and port.
|
|
24
|
+
* @returns the metrics recorder required by an OTLP HTTP log export delegate.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createLogExporterMetrics(url: string): ExporterMetrics<ReadableLogRecord[]>;
|
|
27
|
+
/**
|
|
28
|
+
* Resolve collector-local headers and agents with shared SDK timeout and compression defaults.
|
|
29
|
+
* @param options - explicit endpoint and SDK HTTP settings.
|
|
30
|
+
* @returns resolved transport settings without ambient credentials.
|
|
31
|
+
*/
|
|
32
|
+
export declare function logTransportOptions(options: LogExporterOptions): Parameters<typeof createOtlpHttpExportDelegate>[0];
|
|
33
|
+
//# sourceMappingURL=transport.d.ts.map
|
package/locale/de.json
ADDED
package/locale/es.json
ADDED
package/locale/fr.json
ADDED
package/locale/ja.json
ADDED
package/locale/pt.json
ADDED
package/locale/ru.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unieai/rabi-otel",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "Cordis service for independent ordinary-event and byte-bounded Session-log OTLP channels",
|
|
4
|
+
"version": "0.2.2-rc.5",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "lib/index.js",
|
|
10
|
+
"types": "lib/types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./lib/types/index.d.ts",
|
|
14
|
+
"default": "./lib/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./src/*": "./src/*",
|
|
17
|
+
"./package.json": "./package.json",
|
|
18
|
+
"./locale/*.json": "./locale/*.json"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"locale/*.json",
|
|
22
|
+
"lib/index.js",
|
|
23
|
+
"lib/types/**/*.d.ts",
|
|
24
|
+
"lib/types/**/*.d.ts.map",
|
|
25
|
+
"lib/**/*.js.map",
|
|
26
|
+
"src",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@opentelemetry/api": "^1.9.1",
|
|
32
|
+
"@opentelemetry/api-logs": "0.222.0",
|
|
33
|
+
"@opentelemetry/otlp-exporter-base": "0.222.0",
|
|
34
|
+
"@opentelemetry/resources": "2.11.0",
|
|
35
|
+
"@opentelemetry/sdk-logs": "0.222.0",
|
|
36
|
+
"@opentelemetry/core": "2.11.0",
|
|
37
|
+
"@opentelemetry/otlp-transformer": "0.222.0",
|
|
38
|
+
"got": "^14.6.6"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@unieai/cordis": "4.1.0",
|
|
42
|
+
"@unieai/rabi-session": "0.2.2-rc.5"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/event-log.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** Ordinary event SDK batching over a cancellable HTTP transport. */
|
|
2
|
+
import type { Attributes } from '@opentelemetry/api'
|
|
3
|
+
import { addAbortListener } from 'node:events'
|
|
4
|
+
import { SeverityNumber, type Logger } from '@opentelemetry/api-logs'
|
|
5
|
+
import { ExportResultCode } from '@opentelemetry/core'
|
|
6
|
+
import { resourceFromAttributes } from '@opentelemetry/resources'
|
|
7
|
+
import { BatchLogRecordProcessor, LoggerProvider } from '@opentelemetry/sdk-logs'
|
|
8
|
+
import type { BatchLogRecordProcessorOptions, LogRecordExporter } from '@opentelemetry/sdk-logs'
|
|
9
|
+
import type { SessionLogOptions } from './session-log.ts'
|
|
10
|
+
import { createEventLogExporter } from './event-transport.ts'
|
|
11
|
+
import type { LogExporterOptions } from './transport.ts'
|
|
12
|
+
|
|
13
|
+
/** Scalar values accepted by the collector's Arrow attributes map. */
|
|
14
|
+
export type OTelEventScalar = string | number | boolean
|
|
15
|
+
|
|
16
|
+
/** Explicitly selected analytics fields; object values may contain scalars only. */
|
|
17
|
+
export interface OTelEventRecord {
|
|
18
|
+
/** Product/DA-owned event name. */
|
|
19
|
+
eventName: string
|
|
20
|
+
/** Human-readable summary; never a prompt, response, credential, or file contents. */
|
|
21
|
+
body: string
|
|
22
|
+
/** Event occurrence time in Unix milliseconds. Observation time is assigned on enqueue. */
|
|
23
|
+
timestamp: number
|
|
24
|
+
/** OTel severity; omitted values use INFO. */
|
|
25
|
+
severityNumber?: SeverityNumber
|
|
26
|
+
/** Business fields selected by the caller; no automatic device or account identity. */
|
|
27
|
+
attributes?: Record<string, OTelEventScalar | Record<string, OTelEventScalar>>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Ordinary-event transport, resource, scope, and count-batching options. */
|
|
31
|
+
export interface EventLogOptions {
|
|
32
|
+
exporter: LogExporterOptions
|
|
33
|
+
resourceAttributes: Attributes
|
|
34
|
+
scope: { name: string; version?: string }
|
|
35
|
+
processor: Omit<BatchLogRecordProcessorOptions, 'exporter'>
|
|
36
|
+
onFailure: SessionLogOptions['onFailure']
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** One caller-owned ordinary-event queue, independent of every Session-log queue. */
|
|
40
|
+
export class EventLogReporter {
|
|
41
|
+
private readonly exporter: LogRecordExporter
|
|
42
|
+
private readonly provider: LoggerProvider
|
|
43
|
+
private readonly logger: Logger
|
|
44
|
+
private readonly cancellation = new AbortController()
|
|
45
|
+
|
|
46
|
+
/** @param options - explicit transport, resource, scope, queue, and diagnostic settings. */
|
|
47
|
+
constructor(options: EventLogOptions) {
|
|
48
|
+
const exporter = createEventLogExporter(options.exporter, this.cancellation.signal)
|
|
49
|
+
this.exporter = exporter
|
|
50
|
+
this.provider = new LoggerProvider({
|
|
51
|
+
resource: resourceFromAttributes(options.resourceAttributes),
|
|
52
|
+
processors: [new BatchLogRecordProcessor({
|
|
53
|
+
...options.processor,
|
|
54
|
+
exporter: {
|
|
55
|
+
export: (records, callback) => {
|
|
56
|
+
exporter.export(records, (result) => {
|
|
57
|
+
if (result.code !== ExportResultCode.SUCCESS) options.onFailure('Product telemetry export failed', result.error)
|
|
58
|
+
callback(result)
|
|
59
|
+
})
|
|
60
|
+
},
|
|
61
|
+
forceFlush: () => exporter.forceFlush(),
|
|
62
|
+
shutdown: () => exporter.shutdown(),
|
|
63
|
+
},
|
|
64
|
+
})],
|
|
65
|
+
})
|
|
66
|
+
this.logger = this.provider.getLogger(options.scope.name, options.scope.version)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Enqueue caller-selected analytics fields without acknowledging delivery.
|
|
71
|
+
* @param record - the ordinary event to report.
|
|
72
|
+
*/
|
|
73
|
+
emit(record: OTelEventRecord): void {
|
|
74
|
+
const severityNumber = record.severityNumber ?? SeverityNumber.INFO
|
|
75
|
+
this.logger.emit({ ...record, observedTimestamp: Date.now(), severityNumber, severityText: SeverityNumber[severityNumber] })
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Drain the queue and release its transport, cancelling remaining exports when the caller aborts.
|
|
80
|
+
* @param signal - optional shutdown deadline; abort discards pending exports and cancels retry waits.
|
|
81
|
+
* @returns completion of SDK shutdown and transport cleanup.
|
|
82
|
+
*/
|
|
83
|
+
async shutdown(signal?: AbortSignal): Promise<void> {
|
|
84
|
+
const abort = (): void => { this.cancellation.abort(signal?.reason) }
|
|
85
|
+
const listener = signal === undefined ? undefined : addAbortListener(signal, abort)
|
|
86
|
+
if (signal?.aborted) abort()
|
|
87
|
+
try { await this.provider.shutdown() }
|
|
88
|
+
finally {
|
|
89
|
+
// SDK batch shutdown can reject before it releases the exporter.
|
|
90
|
+
try { await this.exporter.shutdown() }
|
|
91
|
+
finally { listener?.[Symbol.dispose]() }
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Cancellable ordinary-event HTTP exports, including retry waits and response reads. */
|
|
2
|
+
import type { Agent as HttpsAgent } from 'node:https'
|
|
3
|
+
import { gzipSync } from 'node:zlib'
|
|
4
|
+
import got from 'got'
|
|
5
|
+
import { createOtlpNetworkExportDelegate, OTLPExporterBase } from '@opentelemetry/otlp-exporter-base'
|
|
6
|
+
import { JsonLogsSerializer } from '@opentelemetry/otlp-transformer'
|
|
7
|
+
import type { LogRecordExporter } from '@opentelemetry/sdk-logs'
|
|
8
|
+
import { createLogExporterMetrics, type LogExporterOptions, logTransportOptions } from './transport.ts'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Create a channel-owned exporter whose cancellation releases requests and retry timers.
|
|
12
|
+
* @param options - explicit collector and SDK HTTP settings.
|
|
13
|
+
* @param signal - channel cancellation, shared by current and future batch exports.
|
|
14
|
+
* @returns the SDK exporter; shutdown also destroys its owned HTTP agent.
|
|
15
|
+
*/
|
|
16
|
+
export function createEventLogExporter(options: LogExporterOptions, signal: AbortSignal): LogRecordExporter {
|
|
17
|
+
const config = logTransportOptions(options)
|
|
18
|
+
let agent: ReturnType<typeof config.agentFactory> | undefined
|
|
19
|
+
const exporter = new OTLPExporterBase(createOtlpNetworkExportDelegate(config, JsonLogsSerializer, createLogExporterMetrics(config.url), {
|
|
20
|
+
async send(data, timeoutMillis) {
|
|
21
|
+
signal.throwIfAborted()
|
|
22
|
+
agent ??= config.agentFactory(new URL(config.url).protocol)
|
|
23
|
+
const selectedAgent = await agent
|
|
24
|
+
const headers = await config.headers()
|
|
25
|
+
signal.throwIfAborted()
|
|
26
|
+
const compressed = config.compression === 'gzip'
|
|
27
|
+
const request = got.post(config.url, {
|
|
28
|
+
body: compressed ? gzipSync(data) : Buffer.from(data),
|
|
29
|
+
headers: { ...headers, ...(compressed ? { 'content-encoding': 'gzip' } : {}),
|
|
30
|
+
...(config.userAgent === undefined ? {} : { 'user-agent': config.userAgent }) },
|
|
31
|
+
agent: new URL(config.url).protocol === 'https:' ? { https: selectedAgent as HttpsAgent } : { http: selectedAgent },
|
|
32
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMillis)]),
|
|
33
|
+
followRedirect: false,
|
|
34
|
+
retry: { limit: 5, methods: ['POST'], statusCodes: [429, 502, 503, 504], errorCodes: [], backoffLimit: 5000 },
|
|
35
|
+
responseType: 'buffer',
|
|
36
|
+
})
|
|
37
|
+
// Match the SDK's OTLP response-body limit, including chunked responses.
|
|
38
|
+
void request.on('downloadProgress', ({ transferred }) => { if (transferred > 4 * 1024 * 1024) request.cancel() })
|
|
39
|
+
const response = await request
|
|
40
|
+
if (response.statusCode >= 300) throw new Error(`OTLP collector returned HTTP ${response.statusCode}`)
|
|
41
|
+
return { status: 'success', data: response.body }
|
|
42
|
+
},
|
|
43
|
+
shutdown() { /* The exporter awaits agent cleanup below. */ },
|
|
44
|
+
}))
|
|
45
|
+
let shutdown: Promise<void> | undefined
|
|
46
|
+
return {
|
|
47
|
+
export: (records, callback) => { exporter.export(records, callback) },
|
|
48
|
+
forceFlush: () => exporter.forceFlush(),
|
|
49
|
+
shutdown() {
|
|
50
|
+
shutdown ??= (async () => {
|
|
51
|
+
try { await exporter.shutdown() }
|
|
52
|
+
finally { (await agent)?.destroy() }
|
|
53
|
+
})()
|
|
54
|
+
return shutdown
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Cordis entry for independent ordinary-event and Session-log OTLP channels. */
|
|
2
|
+
import { Context, Service } from '@unieai/cordis'
|
|
3
|
+
import { EventLogReporter, type EventLogOptions } from './event-log.ts'
|
|
4
|
+
import { SessionLogReporter, type SessionLogOptions } from './session-log.ts'
|
|
5
|
+
|
|
6
|
+
declare module '@unieai/cordis' {
|
|
7
|
+
interface Context {
|
|
8
|
+
otel: OTel
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Shared transport provider. Mounting creates no queue, identity, or network connection. */
|
|
13
|
+
export default class OTel extends Service {
|
|
14
|
+
constructor(ctx: Context) { super(ctx, 'otel') }
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Create an independent ordinary-event channel with count-based batching.
|
|
18
|
+
* The injected consumer must drain it during its fiber disposal.
|
|
19
|
+
* @param options - transport, scope, resource, queue, and diagnostic settings selected by the consumer.
|
|
20
|
+
* @returns the caller-owned channel; no state is shared with other channels.
|
|
21
|
+
*/
|
|
22
|
+
createEventReporter(options: EventLogOptions): EventLogReporter { return new EventLogReporter(options) }
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Create an independent byte-bounded Session-log channel.
|
|
26
|
+
* Authorization and redaction precede reporting; the consumer owns shutdown and its outer deadline.
|
|
27
|
+
* @param options - transport, scope, resource, queue, and diagnostic settings selected by the consumer.
|
|
28
|
+
* @returns the caller-owned channel, preserving complete accepted events within the request byte ceiling.
|
|
29
|
+
*/
|
|
30
|
+
createSessionLogReporter(options: SessionLogOptions): SessionLogReporter { return new SessionLogReporter(options) }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type { EventLogOptions, OTelEventRecord, OTelEventScalar, EventLogReporter } from './event-log.ts'
|
|
34
|
+
export type { SessionLogProcessorOptions, SessionLogRecord, SessionLogOptions, SessionLogReporter } from './session-log.ts'
|
|
35
|
+
export type { LogExporterOptions } from './transport.ts'
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/** Session-log records in an independent byte-bounded OTLP queue. */
|
|
2
|
+
import type { SessionEvent, SessionId } from '@unieai/rabi-session'
|
|
3
|
+
import type { Attributes } from '@opentelemetry/api'
|
|
4
|
+
import { SeverityNumber } from '@opentelemetry/api-logs'
|
|
5
|
+
import { ExportResultCode } from '@opentelemetry/core'
|
|
6
|
+
import { JsonLogsSerializer } from '@opentelemetry/otlp-transformer'
|
|
7
|
+
import { resourceFromAttributes } from '@opentelemetry/resources'
|
|
8
|
+
import { LoggerProvider, type BatchLogRecordProcessorOptions, type LogRecordExporter, type ReadableLogRecord, type LogRecordProcessor } from '@opentelemetry/sdk-logs'
|
|
9
|
+
import { createLogExporter, type LogExporterOptions } from './transport.ts'
|
|
10
|
+
|
|
11
|
+
/** Collector request ceiling in uncompressed UTF-8 bytes, including the OTLP envelope. */
|
|
12
|
+
export const SESSION_LOG_MAX_REQUEST_BYTES = 4_000_000
|
|
13
|
+
|
|
14
|
+
/** One canonical event with its separately owned Session identity and redacted payload. */
|
|
15
|
+
export interface SessionLogRecord {
|
|
16
|
+
sessionId: SessionId
|
|
17
|
+
/** Complete event envelope; data is the capture policy's exported copy. */
|
|
18
|
+
event: Omit<SessionEvent, 'data'> & { data: unknown }
|
|
19
|
+
/** Additional capture metadata; sessionId and content are always assigned by the reporter. */
|
|
20
|
+
attributes?: Attributes
|
|
21
|
+
/** Omitted values use INFO. */
|
|
22
|
+
severityNumber?: SeverityNumber
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Byte and count batching fields implemented by {@link SessionLogProcessor}.
|
|
27
|
+
*
|
|
28
|
+
* `exporter` belongs to the owning channel, and `selfObsMeterProvider` is
|
|
29
|
+
* excluded because this processor implements no self-observability metering.
|
|
30
|
+
*/
|
|
31
|
+
export type SessionLogProcessorOptions = Omit<BatchLogRecordProcessorOptions, 'exporter' | 'selfObsMeterProvider'>
|
|
32
|
+
|
|
33
|
+
/** Session-log transport and byte/count queue settings. */
|
|
34
|
+
export interface SessionLogOptions {
|
|
35
|
+
/** Explicit destination and SDK transport settings; exporter self-observability metering is not supported. */
|
|
36
|
+
exporter: LogExporterOptions
|
|
37
|
+
/** Session-only queue settings, independent of product-event aggregation. */
|
|
38
|
+
processor?: SessionLogProcessorOptions
|
|
39
|
+
/** May lower, but never exceed, the collector's 4,000,000-byte limit. */
|
|
40
|
+
maxRequestBytes?: number
|
|
41
|
+
/** Instrumentation scope supplied by the business owner. */
|
|
42
|
+
scope: { name: string; version?: string }
|
|
43
|
+
/** Application and anonymous identity carried on the OTLP resource. */
|
|
44
|
+
resourceAttributes: Attributes
|
|
45
|
+
/** Report rejected single records and network failures without recording their content. */
|
|
46
|
+
onFailure: (message: string, error?: Error) => void
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Validate byte and queue settings before constructing an SDK pipeline.
|
|
51
|
+
* @param options - Session-specific limits supplied by the owning composition.
|
|
52
|
+
* @returns the resolved collector request limit.
|
|
53
|
+
*/
|
|
54
|
+
export function resolveSessionLogLimits(options: Pick<SessionLogOptions, 'maxRequestBytes' | 'processor'>): number {
|
|
55
|
+
const limit = options.maxRequestBytes ?? SESSION_LOG_MAX_REQUEST_BYTES
|
|
56
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > SESSION_LOG_MAX_REQUEST_BYTES) {
|
|
57
|
+
throw new Error(`session log maxRequestBytes must be an integer between 1 and ${SESSION_LOG_MAX_REQUEST_BYTES}`)
|
|
58
|
+
}
|
|
59
|
+
for (const key of ['maxQueueSize', 'maxExportBatchSize', 'scheduledDelayMillis', 'exportTimeoutMillis'] as const) {
|
|
60
|
+
const value = options.processor?.[key]
|
|
61
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2_147_483_647)) {
|
|
62
|
+
throw new Error(`session log processor.${key} must be a positive integer no greater than 2147483647`)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const queue = options.processor?.maxQueueSize ?? 2048
|
|
66
|
+
const batch = options.processor?.maxExportBatchSize ?? 512
|
|
67
|
+
if (batch > queue) throw new Error('session log maxExportBatchSize must not exceed maxQueueSize')
|
|
68
|
+
return limit
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Byte/count batching with one transport request in flight, including after a watchdog warning. */
|
|
72
|
+
class SessionLogProcessor implements LogRecordProcessor {
|
|
73
|
+
private readonly queue: { record: ReadableLogRecord; bytes: number }[] = []
|
|
74
|
+
private bytes = 0
|
|
75
|
+
private timer: ReturnType<typeof setTimeout> | undefined
|
|
76
|
+
private active: Promise<void> | undefined
|
|
77
|
+
private shutdownPromise: Promise<void> | undefined
|
|
78
|
+
private stopped = false
|
|
79
|
+
|
|
80
|
+
constructor(
|
|
81
|
+
private readonly exporter: LogRecordExporter,
|
|
82
|
+
private readonly limit: number,
|
|
83
|
+
private readonly config: Required<Pick<SessionLogProcessorOptions, 'maxQueueSize' | 'maxExportBatchSize' | 'scheduledDelayMillis' | 'exportTimeoutMillis'>>,
|
|
84
|
+
private readonly warn: SessionLogOptions['onFailure'],
|
|
85
|
+
) {}
|
|
86
|
+
|
|
87
|
+
onEmit(record: ReadableLogRecord): void {
|
|
88
|
+
if (this.stopped) return
|
|
89
|
+
if (this.queue.length >= this.config.maxQueueSize) {
|
|
90
|
+
this.warn('Session log queue is full; record rejected')
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
let bytes: number
|
|
94
|
+
try {
|
|
95
|
+
const serialized = JsonLogsSerializer.serializeRequest([record])
|
|
96
|
+
if (serialized === undefined) throw new Error('Session log serialization produced no request')
|
|
97
|
+
bytes = serialized.byteLength
|
|
98
|
+
} catch (error) {
|
|
99
|
+
this.warn('Session log serialization failed; record rejected', error instanceof Error ? error : new Error(String(error)))
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
if (bytes > this.limit) {
|
|
103
|
+
this.warn('Session log record rejected; content was not truncated', new Error(`Session log record exceeds maxRequestBytes: ${bytes} > ${this.limit}`))
|
|
104
|
+
return
|
|
105
|
+
}
|
|
106
|
+
this.queue.push({ record, bytes })
|
|
107
|
+
this.bytes += bytes
|
|
108
|
+
if (this.active !== undefined) return
|
|
109
|
+
if (this.queue.length >= this.config.maxExportBatchSize || this.bytes >= this.limit) {
|
|
110
|
+
void this.forceFlush()
|
|
111
|
+
} else if (this.timer === undefined) {
|
|
112
|
+
this.timer = setTimeout(() => { void this.forceFlush() }, this.config.scheduledDelayMillis)
|
|
113
|
+
this.timer.unref()
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
forceFlush(): Promise<void> {
|
|
118
|
+
clearTimeout(this.timer)
|
|
119
|
+
this.timer = undefined
|
|
120
|
+
if (this.active !== undefined) return this.active
|
|
121
|
+
if (this.queue.length === 0) return Promise.resolve()
|
|
122
|
+
this.active = this.drain()
|
|
123
|
+
return this.active
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private async drain(): Promise<void> {
|
|
127
|
+
try {
|
|
128
|
+
while (!this.stopped && this.queue.length > 0) {
|
|
129
|
+
let bytes = 0
|
|
130
|
+
let count = 0
|
|
131
|
+
for (const entry of this.queue) {
|
|
132
|
+
if (count === this.config.maxExportBatchSize || bytes + entry.bytes > this.limit) break
|
|
133
|
+
bytes += entry.bytes
|
|
134
|
+
count++
|
|
135
|
+
}
|
|
136
|
+
// Each measured record includes its resource/scope envelope. The shared
|
|
137
|
+
// envelope in this provider's multi-record request cannot exceed their sum.
|
|
138
|
+
const records = this.queue.splice(0, count).map(entry => entry.record)
|
|
139
|
+
this.bytes -= bytes
|
|
140
|
+
await this.send(records)
|
|
141
|
+
// The export callback precedes removal from the SDK concurrency queue.
|
|
142
|
+
await this.exporter.forceFlush()
|
|
143
|
+
}
|
|
144
|
+
} finally { this.active = undefined }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private send(records: ReadableLogRecord[]): Promise<void> {
|
|
148
|
+
return new Promise((resolve) => {
|
|
149
|
+
const timer = setTimeout(() => {
|
|
150
|
+
this.warn('Session log request exceeded exportTimeoutMillis; waiting for transport settlement')
|
|
151
|
+
}, this.config.exportTimeoutMillis)
|
|
152
|
+
timer.unref()
|
|
153
|
+
const finish = (error?: Error): void => {
|
|
154
|
+
clearTimeout(timer)
|
|
155
|
+
if (error !== undefined) this.warn('Session log export failed', error)
|
|
156
|
+
resolve()
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
this.exporter.export(records, (result) => {
|
|
160
|
+
finish(result.code === ExportResultCode.SUCCESS
|
|
161
|
+
? undefined : result.error ?? new Error('Session log HTTP export failed'))
|
|
162
|
+
})
|
|
163
|
+
} catch (error) {
|
|
164
|
+
finish(error instanceof Error ? error : new Error(String(error)))
|
|
165
|
+
}
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
stopPending(): void {
|
|
170
|
+
this.stopped = true
|
|
171
|
+
this.queue.length = 0
|
|
172
|
+
this.bytes = 0
|
|
173
|
+
clearTimeout(this.timer)
|
|
174
|
+
this.timer = undefined
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
shutdown(): Promise<void> {
|
|
178
|
+
this.shutdownPromise ??= this.forceFlush().then(() => this.exporter.shutdown())
|
|
179
|
+
return this.shutdownPromise
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Owns feedback-authorized Session logs; no product-event provider or queue is mounted. */
|
|
184
|
+
export class SessionLogReporter {
|
|
185
|
+
private readonly provider: LoggerProvider
|
|
186
|
+
private readonly processor: SessionLogProcessor
|
|
187
|
+
private readonly logger: ReturnType<LoggerProvider['getLogger']>
|
|
188
|
+
|
|
189
|
+
/** @param options - explicit transport, resource identity, queue limits, and diagnostics. */
|
|
190
|
+
constructor(options: SessionLogOptions) {
|
|
191
|
+
const limit = resolveSessionLogLimits(options)
|
|
192
|
+
this.processor = new SessionLogProcessor(createLogExporter(options.exporter), limit, {
|
|
193
|
+
maxQueueSize: options.processor?.maxQueueSize ?? 2048,
|
|
194
|
+
maxExportBatchSize: options.processor?.maxExportBatchSize ?? 512,
|
|
195
|
+
scheduledDelayMillis: options.processor?.scheduledDelayMillis ?? 1000,
|
|
196
|
+
exportTimeoutMillis: options.processor?.exportTimeoutMillis ?? 30000,
|
|
197
|
+
}, options.onFailure)
|
|
198
|
+
this.provider = new LoggerProvider({
|
|
199
|
+
logRecordLimits: { attributeValueLengthLimit: Infinity, attributeCountLimit: Infinity },
|
|
200
|
+
resource: resourceFromAttributes(options.resourceAttributes),
|
|
201
|
+
processors: [this.processor],
|
|
202
|
+
})
|
|
203
|
+
this.logger = this.provider.getLogger(options.scope.name, options.scope.version)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Enqueue one complete event without acknowledging network delivery.
|
|
208
|
+
* @param record - event with redacted data and its original Session id.
|
|
209
|
+
*/
|
|
210
|
+
reportSessionLog(record: SessionLogRecord): void {
|
|
211
|
+
const severityNumber = record.severityNumber ?? SeverityNumber.INFO
|
|
212
|
+
this.logger.emit({
|
|
213
|
+
eventName: 'session-log', body: 'session-log',
|
|
214
|
+
timestamp: record.event.time, observedTimestamp: record.event.time,
|
|
215
|
+
severityNumber, severityText: SeverityNumber[severityNumber],
|
|
216
|
+
attributes: { ...record.attributes, sessionId: record.sessionId, content: JSON.stringify(record.event) },
|
|
217
|
+
})
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Stop queued requests after the owning backend's shutdown deadline; an active transport may still settle. */
|
|
221
|
+
stopPending(): void { this.processor.stopPending() }
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Drain queued requests and release the SDK transport.
|
|
225
|
+
* @returns completion after queued requests settle and the SDK transport shuts down.
|
|
226
|
+
*/
|
|
227
|
+
shutdown(): Promise<void> { return this.provider.shutdown() }
|
|
228
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Explicit OTLP JSON transport for feedback-authorized Session logs. */
|
|
2
|
+
import { createOtlpHttpExportDelegate, createOtlpHttpExporterMetrics, getSharedConfigurationFromEnvironment, httpAgentFactoryFromOptions } from '@opentelemetry/otlp-exporter-base/node-http'
|
|
3
|
+
import { type ExporterMetrics, getSharedConfigurationDefaults, mergeOtlpSharedConfigurationWithDefaults, OTLPExporterBase, type OTLPExporterNodeConfigBase } from '@opentelemetry/otlp-exporter-base'
|
|
4
|
+
import { JsonLogsSerializer, LogsExporterMetricsHelper } from '@opentelemetry/otlp-transformer'
|
|
5
|
+
import type { LogRecordExporter, ReadableLogRecord } from '@opentelemetry/sdk-logs'
|
|
6
|
+
|
|
7
|
+
/** `otel.component.type` reported by OTLP HTTP log exporter self-observability metrics. */
|
|
8
|
+
const OTLP_HTTP_LOG_EXPORTER_COMPONENT_TYPE = 'otlp_http_log_exporter'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Collector and SDK HTTP settings accepted by this package's log exporters.
|
|
12
|
+
*
|
|
13
|
+
* `OTLPExporterConfigBase.selfObsMeterProvider` is excluded: every channel here
|
|
14
|
+
* passes no meter provider to the exporter metrics recorder, which stays noop.
|
|
15
|
+
*/
|
|
16
|
+
export type LogExporterOptions = Omit<OTLPExporterNodeConfigBase, 'selfObsMeterProvider'> & {
|
|
17
|
+
/** Full HTTP(S) logs destination. */
|
|
18
|
+
url: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Create an SDK JSON exporter without inheriting another collector's headers or TLS identity.
|
|
23
|
+
* @param options - explicit endpoint, headers, agent, and SDK transport settings.
|
|
24
|
+
* @returns the exporter owned by one independent log pipeline.
|
|
25
|
+
*/
|
|
26
|
+
export function createLogExporter(options: LogExporterOptions): LogRecordExporter {
|
|
27
|
+
return new OTLPExporterBase(createOtlpHttpExportDelegate(
|
|
28
|
+
logTransportOptions(options), JsonLogsSerializer, OTLP_HTTP_LOG_EXPORTER_COMPONENT_TYPE, LogsExporterMetricsHelper, undefined))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Create one log exporter's self-observability metrics; without a meter provider they record nothing.
|
|
33
|
+
* @param url - collector endpoint recorded as the metrics server address and port.
|
|
34
|
+
* @returns the metrics recorder required by an OTLP HTTP log export delegate.
|
|
35
|
+
*/
|
|
36
|
+
export function createLogExporterMetrics(url: string): ExporterMetrics<ReadableLogRecord[]> {
|
|
37
|
+
return createOtlpHttpExporterMetrics(OTLP_HTTP_LOG_EXPORTER_COMPONENT_TYPE, LogsExporterMetricsHelper, url, undefined)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolve collector-local headers and agents with shared SDK timeout and compression defaults.
|
|
42
|
+
* @param options - explicit endpoint and SDK HTTP settings.
|
|
43
|
+
* @returns resolved transport settings without ambient credentials.
|
|
44
|
+
*/
|
|
45
|
+
export function logTransportOptions(
|
|
46
|
+
options: LogExporterOptions,
|
|
47
|
+
): Parameters<typeof createOtlpHttpExportDelegate>[0] {
|
|
48
|
+
const shared = mergeOtlpSharedConfigurationWithDefaults(options, getSharedConfigurationFromEnvironment('LOGS'), getSharedConfigurationDefaults())
|
|
49
|
+
return {
|
|
50
|
+
...shared,
|
|
51
|
+
url: options.url,
|
|
52
|
+
headers: async () => ({
|
|
53
|
+
'Content-Type': 'application/json',
|
|
54
|
+
...typeof options.headers === 'function' ? await options.headers() : options.headers,
|
|
55
|
+
}),
|
|
56
|
+
// An agent factory owns the returned agent, including its keepAlive setting.
|
|
57
|
+
agentFactory: typeof options.httpAgentOptions === 'function' ? options.httpAgentOptions
|
|
58
|
+
: httpAgentFactoryFromOptions({ keepAlive: options.keepAlive ?? true, ...options.httpAgentOptions }),
|
|
59
|
+
...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
|
|
60
|
+
}
|
|
61
|
+
}
|