@grow-codes/grafana-loki 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +81 -0
- package/README.md +47 -2
- package/lib/chunk-VGAJJR3M.cjs +564 -0
- package/lib/chunk-VGAJJR3M.cjs.map +1 -0
- package/lib/chunk-ZH5T5C4R.js +526 -0
- package/lib/chunk-ZH5T5C4R.js.map +1 -0
- package/lib/index.cjs +3895 -0
- package/lib/index.cjs.map +1 -0
- package/lib/index.d.cts +1348 -0
- package/lib/index.d.ts +1348 -0
- package/lib/index.js +3642 -0
- package/lib/index.js.map +1 -0
- package/lib/query-CofVHbt1.d.cts +471 -0
- package/lib/query-CofVHbt1.d.ts +471 -0
- package/lib/testing/index.cjs +674 -0
- package/lib/testing/index.cjs.map +1 -0
- package/lib/testing/index.d.cts +296 -0
- package/lib/testing/index.d.ts +296 -0
- package/lib/testing/index.js +649 -0
- package/lib/testing/index.js.map +1 -0
- package/package.json +118 -4
package/lib/index.cjs
ADDED
|
@@ -0,0 +1,3895 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunkVGAJJR3M_cjs = require('./chunk-VGAJJR3M.cjs');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var undici = require('undici');
|
|
6
|
+
var zlib = require('zlib');
|
|
7
|
+
var api = require('@opentelemetry/api');
|
|
8
|
+
var stream = require('stream');
|
|
9
|
+
var snappyjs = require('snappyjs');
|
|
10
|
+
var WebSocket = require('ws');
|
|
11
|
+
|
|
12
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
13
|
+
|
|
14
|
+
var WebSocket__default = /*#__PURE__*/_interopDefault(WebSocket);
|
|
15
|
+
|
|
16
|
+
// src/core/redaction.ts
|
|
17
|
+
var REDACTED = "[REDACTED]";
|
|
18
|
+
var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
19
|
+
var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
|
|
20
|
+
"authorization",
|
|
21
|
+
"proxy-authorization",
|
|
22
|
+
"cookie",
|
|
23
|
+
"set-cookie"
|
|
24
|
+
]);
|
|
25
|
+
var SENSITIVE_HEADER_PARTS = [
|
|
26
|
+
"token",
|
|
27
|
+
"secret",
|
|
28
|
+
"password",
|
|
29
|
+
"api-key",
|
|
30
|
+
"apikey",
|
|
31
|
+
"key",
|
|
32
|
+
"auth",
|
|
33
|
+
"session",
|
|
34
|
+
"signature",
|
|
35
|
+
"credential"
|
|
36
|
+
];
|
|
37
|
+
var SENSITIVE_FIELD_PARTS = [
|
|
38
|
+
"password",
|
|
39
|
+
"passwd",
|
|
40
|
+
"secret",
|
|
41
|
+
"token",
|
|
42
|
+
"authorization",
|
|
43
|
+
"cookie",
|
|
44
|
+
"api_key",
|
|
45
|
+
"apikey",
|
|
46
|
+
"api-key",
|
|
47
|
+
"access_key",
|
|
48
|
+
"private_key",
|
|
49
|
+
"client_secret",
|
|
50
|
+
"credential",
|
|
51
|
+
"session",
|
|
52
|
+
"signature"
|
|
53
|
+
];
|
|
54
|
+
var MIN_SECRET_LENGTH = 4;
|
|
55
|
+
function isSensitiveHeader(name) {
|
|
56
|
+
const n = name.toLowerCase();
|
|
57
|
+
return SENSITIVE_HEADERS.has(n) || SENSITIVE_HEADER_PARTS.some((p) => n.includes(p));
|
|
58
|
+
}
|
|
59
|
+
var PATH_NAME = /path$/;
|
|
60
|
+
function isSensitiveField(name, extraKeys = []) {
|
|
61
|
+
const n = name.toLowerCase();
|
|
62
|
+
return !PATH_NAME.test(n) && SENSITIVE_FIELD_PARTS.some((p) => n.includes(p)) || extraKeys.some((k) => k !== "" && n.includes(k.toLowerCase()));
|
|
63
|
+
}
|
|
64
|
+
function headerEntries(headers) {
|
|
65
|
+
if (Symbol.iterator in headers) {
|
|
66
|
+
return Array.from(headers, ([k, v]) => [k, v]);
|
|
67
|
+
}
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
70
|
+
if (v === void 0) continue;
|
|
71
|
+
out.push([k, typeof v === "string" ? v : v.join(", ")]);
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
function redactHeaders(headers) {
|
|
76
|
+
const out = {};
|
|
77
|
+
for (const [k, v] of headerEntries(headers)) {
|
|
78
|
+
out[k] = isSensitiveHeader(k) ? REDACTED : v;
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
function redactUrl(url) {
|
|
83
|
+
let parsed;
|
|
84
|
+
try {
|
|
85
|
+
parsed = new URL(url.toString());
|
|
86
|
+
} catch {
|
|
87
|
+
return redactQueryString(url.toString());
|
|
88
|
+
}
|
|
89
|
+
if (parsed.password !== "") parsed.password = REDACTED;
|
|
90
|
+
if (parsed.password === "" && parsed.username !== "" && parsed.username !== REDACTED) {
|
|
91
|
+
parsed.username = REDACTED;
|
|
92
|
+
}
|
|
93
|
+
const params = parsed.searchParams;
|
|
94
|
+
let changed = false;
|
|
95
|
+
const next = new URLSearchParams();
|
|
96
|
+
for (const [k, v] of params) {
|
|
97
|
+
if (isSensitiveField(k)) {
|
|
98
|
+
next.append(k, REDACTED);
|
|
99
|
+
changed = true;
|
|
100
|
+
} else {
|
|
101
|
+
next.append(k, v);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (changed) parsed.search = next.toString();
|
|
105
|
+
return parsed.toString().replaceAll(encodeURIComponent(REDACTED), REDACTED);
|
|
106
|
+
}
|
|
107
|
+
function redactQueryString(text) {
|
|
108
|
+
return text.replace(
|
|
109
|
+
/([?&])([^=&#?\s]+)=([^&#\s]*)/g,
|
|
110
|
+
(m, sep, k) => isSensitiveField(k) ? `${sep}${k}=${REDACTED}` : m
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
function redactFields(value, extraKeys = []) {
|
|
114
|
+
return redactValue(value, extraKeys, /* @__PURE__ */ new WeakMap());
|
|
115
|
+
}
|
|
116
|
+
function redactValue(value, extraKeys, seen) {
|
|
117
|
+
if (value === null || typeof value !== "object") return value;
|
|
118
|
+
if (value instanceof Date || value instanceof Uint8Array) return value;
|
|
119
|
+
const cached = seen.get(value);
|
|
120
|
+
if (cached !== void 0) return cached;
|
|
121
|
+
if (Array.isArray(value)) {
|
|
122
|
+
const arr = [];
|
|
123
|
+
seen.set(value, arr);
|
|
124
|
+
for (const item of value) arr.push(redactValue(item, extraKeys, seen));
|
|
125
|
+
return arr;
|
|
126
|
+
}
|
|
127
|
+
if (value instanceof Map) {
|
|
128
|
+
const map = /* @__PURE__ */ new Map();
|
|
129
|
+
seen.set(value, map);
|
|
130
|
+
for (const [k, v] of value) {
|
|
131
|
+
map.set(
|
|
132
|
+
k,
|
|
133
|
+
typeof k === "string" && isSensitiveField(k, extraKeys) ? REDACTED : redactValue(v, extraKeys, seen)
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
return map;
|
|
137
|
+
}
|
|
138
|
+
const out = {};
|
|
139
|
+
seen.set(value, out);
|
|
140
|
+
for (const [k, v] of Object.entries(value)) {
|
|
141
|
+
out[k] = isSensitiveField(k, extraKeys) ? REDACTED : redactValue(v, extraKeys, seen);
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
function redactText(text, knownSecrets = []) {
|
|
146
|
+
const values = /* @__PURE__ */ new Set();
|
|
147
|
+
for (const s of knownSecrets) {
|
|
148
|
+
const v = s instanceof Secret ? s.reveal() : s;
|
|
149
|
+
if (typeof v === "string" && v.length >= MIN_SECRET_LENGTH) values.add(v);
|
|
150
|
+
}
|
|
151
|
+
let out = text;
|
|
152
|
+
for (const v of [...values].sort((a, b) => b.length - a.length)) {
|
|
153
|
+
out = out.split(v).join(REDACTED);
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
var Secret = class _Secret {
|
|
158
|
+
#value;
|
|
159
|
+
constructor(value) {
|
|
160
|
+
this.#value = value;
|
|
161
|
+
}
|
|
162
|
+
/** Wraps a string (returns `undefined` for `undefined`/empty, keeps an existing Secret). */
|
|
163
|
+
static from(value) {
|
|
164
|
+
if (value === void 0 || value === null) return void 0;
|
|
165
|
+
if (value instanceof _Secret) return value;
|
|
166
|
+
return value === "" ? void 0 : new _Secret(value);
|
|
167
|
+
}
|
|
168
|
+
/** The wrapped value. */
|
|
169
|
+
reveal() {
|
|
170
|
+
return this.#value;
|
|
171
|
+
}
|
|
172
|
+
/** Constant-time-ish comparison with another value. */
|
|
173
|
+
equals(other) {
|
|
174
|
+
const a = this.#value;
|
|
175
|
+
const b = other instanceof _Secret ? other.reveal() : other;
|
|
176
|
+
if (a.length !== b.length) return false;
|
|
177
|
+
let diff = 0;
|
|
178
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
179
|
+
return diff === 0;
|
|
180
|
+
}
|
|
181
|
+
toString() {
|
|
182
|
+
return REDACTED;
|
|
183
|
+
}
|
|
184
|
+
toJSON() {
|
|
185
|
+
return REDACTED;
|
|
186
|
+
}
|
|
187
|
+
[INSPECT]() {
|
|
188
|
+
return REDACTED;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
function redactError(err, knownSecrets = []) {
|
|
192
|
+
const secrets = [...knownSecrets];
|
|
193
|
+
if (err instanceof Error) {
|
|
194
|
+
const copy = new Error(redactText(redactQueryString(err.message), secrets));
|
|
195
|
+
copy.name = err.name;
|
|
196
|
+
const code = err.code;
|
|
197
|
+
if (typeof code === "string") copy.code = code;
|
|
198
|
+
if (err.cause !== void 0) copy.cause = redactError(err.cause, secrets);
|
|
199
|
+
return copy;
|
|
200
|
+
}
|
|
201
|
+
return new Error(redactText(String(err), secrets));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/core/env.ts
|
|
205
|
+
var UNIT_MS = {
|
|
206
|
+
ns: 1e-6,
|
|
207
|
+
us: 1e-3,
|
|
208
|
+
\u00B5s: 1e-3,
|
|
209
|
+
ms: 1,
|
|
210
|
+
s: 1e3,
|
|
211
|
+
m: 6e4,
|
|
212
|
+
h: 36e5
|
|
213
|
+
};
|
|
214
|
+
var DURATION_UNITS = ["ns", "us", "\xB5s", "ms", "s", "m", "h"];
|
|
215
|
+
function parseDuration(raw) {
|
|
216
|
+
const text = raw.trim();
|
|
217
|
+
if (/^\d+$/.test(text)) return Number(text);
|
|
218
|
+
if (text === "") return void 0;
|
|
219
|
+
let total = 0;
|
|
220
|
+
let i = 0;
|
|
221
|
+
const isDigit = (at) => at < text.length && text.charCodeAt(at) >= 48 && text.charCodeAt(at) <= 57;
|
|
222
|
+
while (i < text.length) {
|
|
223
|
+
const start = i;
|
|
224
|
+
while (isDigit(i)) i += 1;
|
|
225
|
+
const intDigits = i - start;
|
|
226
|
+
if (text[i] === ".") {
|
|
227
|
+
i += 1;
|
|
228
|
+
const fracStart = i;
|
|
229
|
+
while (isDigit(i)) i += 1;
|
|
230
|
+
if (i === fracStart) return void 0;
|
|
231
|
+
} else if (intDigits === 0) {
|
|
232
|
+
return void 0;
|
|
233
|
+
}
|
|
234
|
+
const value = Number(text.slice(start, i));
|
|
235
|
+
const unit = DURATION_UNITS.find((u) => text.startsWith(u, i));
|
|
236
|
+
if (unit === void 0) return void 0;
|
|
237
|
+
total += value * UNIT_MS[unit];
|
|
238
|
+
i += unit.length;
|
|
239
|
+
}
|
|
240
|
+
return Math.round(total);
|
|
241
|
+
}
|
|
242
|
+
var TRUE_WORDS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
243
|
+
var FALSE_WORDS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
244
|
+
function parseBool(raw) {
|
|
245
|
+
const text = raw.trim().toLowerCase();
|
|
246
|
+
if (TRUE_WORDS.has(text)) return true;
|
|
247
|
+
if (FALSE_WORDS.has(text)) return false;
|
|
248
|
+
return void 0;
|
|
249
|
+
}
|
|
250
|
+
function parseInteger(raw) {
|
|
251
|
+
const text = raw.trim();
|
|
252
|
+
if (!/^[+-]?\d+$/.test(text)) return void 0;
|
|
253
|
+
const n = Number(text);
|
|
254
|
+
return Number.isSafeInteger(n) ? n : void 0;
|
|
255
|
+
}
|
|
256
|
+
var EnvReader = class {
|
|
257
|
+
prefix;
|
|
258
|
+
#env;
|
|
259
|
+
/**
|
|
260
|
+
* @param prefix e.g. `"GROW_GRAFANA_LOKI_"`.
|
|
261
|
+
* @param env environment map, defaults to `process.env`.
|
|
262
|
+
*/
|
|
263
|
+
constructor(prefix, env = process.env) {
|
|
264
|
+
this.prefix = prefix;
|
|
265
|
+
this.#env = env;
|
|
266
|
+
}
|
|
267
|
+
/** Finds the first present variable: `<prefix><name>`, then each vendor name. */
|
|
268
|
+
lookup(name, vendorNames = []) {
|
|
269
|
+
for (const candidate of [this.prefix + name, ...vendorNames]) {
|
|
270
|
+
const value = this.#env[candidate];
|
|
271
|
+
if (value !== void 0 && value !== "") return { name: candidate, value };
|
|
272
|
+
}
|
|
273
|
+
return void 0;
|
|
274
|
+
}
|
|
275
|
+
/** String value. */
|
|
276
|
+
string(name, vendorNames = []) {
|
|
277
|
+
return this.lookup(name, vendorNames)?.value;
|
|
278
|
+
}
|
|
279
|
+
/** Credential value wrapped in a {@link Secret}. */
|
|
280
|
+
secret(name, vendorNames = []) {
|
|
281
|
+
return Secret.from(this.string(name, vendorNames));
|
|
282
|
+
}
|
|
283
|
+
/** Duration in milliseconds (see {@link parseDuration}). */
|
|
284
|
+
duration(name, vendorNames = []) {
|
|
285
|
+
return this.#parse(name, vendorNames, parseDuration, "a duration such as 1500, 500ms or 10s");
|
|
286
|
+
}
|
|
287
|
+
/** Boolean (see {@link parseBool}). */
|
|
288
|
+
bool(name, vendorNames = []) {
|
|
289
|
+
return this.#parse(name, vendorNames, parseBool, "a boolean (true/false/1/0/yes/no/on/off)");
|
|
290
|
+
}
|
|
291
|
+
/** Integer. */
|
|
292
|
+
int(name, vendorNames = []) {
|
|
293
|
+
return this.#parse(name, vendorNames, parseInteger, "an integer");
|
|
294
|
+
}
|
|
295
|
+
#parse(name, vendorNames, parse, expected) {
|
|
296
|
+
const hit = this.lookup(name, vendorNames);
|
|
297
|
+
if (hit === void 0) return void 0;
|
|
298
|
+
const value = parse(hit.value);
|
|
299
|
+
if (value === void 0) {
|
|
300
|
+
throw new chunkVGAJJR3M_cjs.ConfigError(
|
|
301
|
+
`invalid value in environment variable ${hit.name}: expected ${expected}`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
return value;
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
// src/core/health.ts
|
|
309
|
+
var HEALTHY_WORDS = /* @__PURE__ */ new Set([
|
|
310
|
+
"ok",
|
|
311
|
+
"up",
|
|
312
|
+
"healthy",
|
|
313
|
+
"pass",
|
|
314
|
+
"passing",
|
|
315
|
+
"green",
|
|
316
|
+
"ready",
|
|
317
|
+
"available",
|
|
318
|
+
"running",
|
|
319
|
+
"serving"
|
|
320
|
+
]);
|
|
321
|
+
function isHealthyWord(status) {
|
|
322
|
+
return HEALTHY_WORDS.has(status.trim().toLowerCase());
|
|
323
|
+
}
|
|
324
|
+
function healthStatus(status, details = {}, healthy = isHealthyWord(status)) {
|
|
325
|
+
const flat = {};
|
|
326
|
+
for (const [k, v] of Object.entries(details)) {
|
|
327
|
+
if (v === void 0 || v === null) continue;
|
|
328
|
+
if (typeof v === "string") flat[k] = v;
|
|
329
|
+
else if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint")
|
|
330
|
+
flat[k] = String(v);
|
|
331
|
+
else if (typeof v === "object") flat[k] = JSON.stringify(v);
|
|
332
|
+
}
|
|
333
|
+
return { healthy, status, details: flat };
|
|
334
|
+
}
|
|
335
|
+
async function probeHealth(probe) {
|
|
336
|
+
try {
|
|
337
|
+
return await probe();
|
|
338
|
+
} catch (err) {
|
|
339
|
+
if (err instanceof chunkVGAJJR3M_cjs.LokiError) {
|
|
340
|
+
if (err.code === chunkVGAJJR3M_cjs.ErrorCode.Cancelled || err.code === chunkVGAJJR3M_cjs.ErrorCode.Config) throw err;
|
|
341
|
+
if (err.httpStatus !== void 0) {
|
|
342
|
+
return healthStatus("unhealthy", { httpStatus: err.httpStatus, error: err.code }, false);
|
|
343
|
+
}
|
|
344
|
+
return healthStatus("unreachable", { error: err.code }, false);
|
|
345
|
+
}
|
|
346
|
+
return healthStatus("unreachable", { error: chunkVGAJJR3M_cjs.ErrorCode.Unavailable }, false);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/core/hooks.ts
|
|
351
|
+
var silentLogger = Object.freeze({
|
|
352
|
+
debug: () => void 0,
|
|
353
|
+
info: () => void 0,
|
|
354
|
+
warn: () => void 0,
|
|
355
|
+
error: () => void 0
|
|
356
|
+
});
|
|
357
|
+
function safeCall(fn, ...args) {
|
|
358
|
+
if (fn === void 0) return;
|
|
359
|
+
try {
|
|
360
|
+
const result = fn(...args);
|
|
361
|
+
if (result instanceof Promise) result.catch(() => void 0);
|
|
362
|
+
} catch {
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function safeLogger(logger) {
|
|
366
|
+
if (logger === void 0) return silentLogger;
|
|
367
|
+
return {
|
|
368
|
+
debug: (m, f) => {
|
|
369
|
+
safeCall(
|
|
370
|
+
(a, b) => {
|
|
371
|
+
logger.debug(a, b);
|
|
372
|
+
},
|
|
373
|
+
m,
|
|
374
|
+
f
|
|
375
|
+
);
|
|
376
|
+
},
|
|
377
|
+
info: (m, f) => {
|
|
378
|
+
safeCall(
|
|
379
|
+
(a, b) => {
|
|
380
|
+
logger.info(a, b);
|
|
381
|
+
},
|
|
382
|
+
m,
|
|
383
|
+
f
|
|
384
|
+
);
|
|
385
|
+
},
|
|
386
|
+
warn: (m, f) => {
|
|
387
|
+
safeCall(
|
|
388
|
+
(a, b) => {
|
|
389
|
+
logger.warn(a, b);
|
|
390
|
+
},
|
|
391
|
+
m,
|
|
392
|
+
f
|
|
393
|
+
);
|
|
394
|
+
},
|
|
395
|
+
error: (m, f) => {
|
|
396
|
+
safeCall(
|
|
397
|
+
(a, b) => {
|
|
398
|
+
logger.error(a, b);
|
|
399
|
+
},
|
|
400
|
+
m,
|
|
401
|
+
f
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// src/core/retry.ts
|
|
408
|
+
var RetryPolicy = class _RetryPolicy {
|
|
409
|
+
static DEFAULTS = Object.freeze({
|
|
410
|
+
maxRetries: 3,
|
|
411
|
+
initialBackoffMs: 100,
|
|
412
|
+
maxBackoffMs: 1e4,
|
|
413
|
+
multiplier: 2,
|
|
414
|
+
maxRetryAfterMs: 6e4
|
|
415
|
+
});
|
|
416
|
+
maxRetries;
|
|
417
|
+
initialBackoffMs;
|
|
418
|
+
maxBackoffMs;
|
|
419
|
+
multiplier;
|
|
420
|
+
maxRetryAfterMs;
|
|
421
|
+
random;
|
|
422
|
+
constructor(options = {}) {
|
|
423
|
+
const d = _RetryPolicy.DEFAULTS;
|
|
424
|
+
this.maxRetries = options.maxRetries ?? d.maxRetries;
|
|
425
|
+
this.initialBackoffMs = options.initialBackoffMs ?? d.initialBackoffMs;
|
|
426
|
+
this.maxBackoffMs = options.maxBackoffMs ?? d.maxBackoffMs;
|
|
427
|
+
this.multiplier = options.multiplier ?? d.multiplier;
|
|
428
|
+
this.maxRetryAfterMs = options.maxRetryAfterMs ?? d.maxRetryAfterMs;
|
|
429
|
+
this.random = options.random ?? Math.random;
|
|
430
|
+
Object.freeze(this);
|
|
431
|
+
}
|
|
432
|
+
/** Returns a policy from options, keeping an existing instance as is. */
|
|
433
|
+
static from(value) {
|
|
434
|
+
return value instanceof _RetryPolicy ? value : new _RetryPolicy(value);
|
|
435
|
+
}
|
|
436
|
+
/** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
|
|
437
|
+
backoffCapMs(retry) {
|
|
438
|
+
return Math.min(this.maxBackoffMs, this.initialBackoffMs * this.multiplier ** retry);
|
|
439
|
+
}
|
|
440
|
+
/** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
|
|
441
|
+
backoffMs(retry) {
|
|
442
|
+
return this.random() * this.backoffCapMs(retry);
|
|
443
|
+
}
|
|
444
|
+
/** Validation problems (empty when valid). */
|
|
445
|
+
problems() {
|
|
446
|
+
const out = [];
|
|
447
|
+
if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0)
|
|
448
|
+
out.push("retry.maxRetries must be an integer >= 0");
|
|
449
|
+
if (!(this.initialBackoffMs >= 0)) out.push("retry.initialBackoffMs must be >= 0");
|
|
450
|
+
if (!(this.maxBackoffMs >= 0)) out.push("retry.maxBackoffMs must be >= 0");
|
|
451
|
+
if (!(this.multiplier >= 1)) out.push("retry.multiplier must be >= 1");
|
|
452
|
+
if (!(this.maxRetryAfterMs >= 0)) out.push("retry.maxRetryAfterMs must be >= 0");
|
|
453
|
+
return out;
|
|
454
|
+
}
|
|
455
|
+
toJSON() {
|
|
456
|
+
return {
|
|
457
|
+
maxRetries: this.maxRetries,
|
|
458
|
+
initialBackoffMs: this.initialBackoffMs,
|
|
459
|
+
maxBackoffMs: this.maxBackoffMs,
|
|
460
|
+
multiplier: this.multiplier,
|
|
461
|
+
maxRetryAfterMs: this.maxRetryAfterMs
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
466
|
+
if (value === null || value === void 0) return void 0;
|
|
467
|
+
const text = value.trim();
|
|
468
|
+
if (text === "") return void 0;
|
|
469
|
+
if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1e3);
|
|
470
|
+
if (!/[a-z]/i.test(text)) return void 0;
|
|
471
|
+
const at = Date.parse(text);
|
|
472
|
+
if (Number.isNaN(at)) return void 0;
|
|
473
|
+
return Math.max(0, at - now);
|
|
474
|
+
}
|
|
475
|
+
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
|
|
476
|
+
"GET",
|
|
477
|
+
"HEAD",
|
|
478
|
+
"OPTIONS",
|
|
479
|
+
"PUT",
|
|
480
|
+
"DELETE"
|
|
481
|
+
]);
|
|
482
|
+
function isIdempotentMethod(method) {
|
|
483
|
+
return IDEMPOTENT_METHODS.has(method.toUpperCase());
|
|
484
|
+
}
|
|
485
|
+
function isRetryableStatus(status, idempotent) {
|
|
486
|
+
if (status === 429) return true;
|
|
487
|
+
if (!idempotent) return false;
|
|
488
|
+
return status === 408 || status === 500 || status === 502 || status === 503 || status === 504;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// src/core/options.ts
|
|
492
|
+
var DEFAULT_TIMEOUTS = Object.freeze({
|
|
493
|
+
connectTimeoutMs: 1e4,
|
|
494
|
+
requestTimeoutMs: 3e4,
|
|
495
|
+
totalTimeoutMs: 12e4
|
|
496
|
+
});
|
|
497
|
+
function resolveCommonConfig(options, defaultUrl) {
|
|
498
|
+
const out = {
|
|
499
|
+
url: options.url ?? defaultUrl,
|
|
500
|
+
connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_TIMEOUTS.connectTimeoutMs,
|
|
501
|
+
requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_TIMEOUTS.requestTimeoutMs,
|
|
502
|
+
totalTimeoutMs: options.totalTimeoutMs ?? DEFAULT_TIMEOUTS.totalTimeoutMs,
|
|
503
|
+
retry: RetryPolicy.from(options.retry),
|
|
504
|
+
tls: Object.freeze({ ...options.tls }),
|
|
505
|
+
headers: Object.freeze({ ...options.headers })
|
|
506
|
+
};
|
|
507
|
+
if (options.proxy !== void 0) out.proxy = options.proxy;
|
|
508
|
+
if (options.userAgentSuffix !== void 0) out.userAgentSuffix = options.userAgentSuffix;
|
|
509
|
+
if (options.hooks !== void 0) out.hooks = options.hooks;
|
|
510
|
+
if (options.logger !== void 0) out.logger = options.logger;
|
|
511
|
+
return out;
|
|
512
|
+
}
|
|
513
|
+
function isHttpUrl(value) {
|
|
514
|
+
try {
|
|
515
|
+
const u = new URL(value);
|
|
516
|
+
return u.protocol === "http:" || u.protocol === "https:";
|
|
517
|
+
} catch {
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
function validateCommonConfig(config) {
|
|
522
|
+
const problems = [];
|
|
523
|
+
if (!isHttpUrl(config.url)) problems.push("url must be an http or https URL");
|
|
524
|
+
for (const key of ["connectTimeoutMs", "requestTimeoutMs", "totalTimeoutMs"]) {
|
|
525
|
+
const v = config[key];
|
|
526
|
+
if (!Number.isFinite(v) || v <= 0) problems.push(`${key} must be a positive number`);
|
|
527
|
+
}
|
|
528
|
+
problems.push(...config.retry.problems());
|
|
529
|
+
const tls = config.tls;
|
|
530
|
+
if (tls.clientCertPath === void 0 !== (tls.clientKeyPath === void 0)) {
|
|
531
|
+
problems.push("tls.clientCertPath and tls.clientKeyPath must be given together");
|
|
532
|
+
}
|
|
533
|
+
if (config.proxy !== void 0 && !isHttpUrl(config.proxy)) {
|
|
534
|
+
problems.push("proxy must be an http or https URL");
|
|
535
|
+
}
|
|
536
|
+
if (problems.length > 0) throw new chunkVGAJJR3M_cjs.ConfigError(`invalid configuration: ${problems.join("; ")}`);
|
|
537
|
+
}
|
|
538
|
+
function readCommonEnv(reader, vendor = {}) {
|
|
539
|
+
const out = {};
|
|
540
|
+
const url = reader.string("URL", vendor.url);
|
|
541
|
+
if (url !== void 0) out.url = url;
|
|
542
|
+
const connect = reader.duration("CONNECT_TIMEOUT");
|
|
543
|
+
if (connect !== void 0) out.connectTimeoutMs = connect;
|
|
544
|
+
const request = reader.duration("REQUEST_TIMEOUT");
|
|
545
|
+
if (request !== void 0) out.requestTimeoutMs = request;
|
|
546
|
+
const total = reader.duration("TOTAL_TIMEOUT");
|
|
547
|
+
if (total !== void 0) out.totalTimeoutMs = total;
|
|
548
|
+
const maxRetries = reader.int("MAX_RETRIES");
|
|
549
|
+
if (maxRetries !== void 0) out.retry = { maxRetries };
|
|
550
|
+
const tls = {};
|
|
551
|
+
const ca = reader.string("CA_CERT", vendor.caCert);
|
|
552
|
+
if (ca !== void 0) tls.caCertPath = ca;
|
|
553
|
+
const cert = reader.string("CLIENT_CERT", vendor.clientCert);
|
|
554
|
+
if (cert !== void 0) tls.clientCertPath = cert;
|
|
555
|
+
const key = reader.string("CLIENT_KEY", vendor.clientKey);
|
|
556
|
+
if (key !== void 0) tls.clientKeyPath = key;
|
|
557
|
+
const insecure = reader.bool("INSECURE_SKIP_VERIFY", vendor.insecureSkipVerify);
|
|
558
|
+
if (insecure !== void 0) tls.insecureSkipVerify = insecure;
|
|
559
|
+
if (Object.keys(tls).length > 0) out.tls = tls;
|
|
560
|
+
const proxy = reader.string("PROXY", vendor.proxy);
|
|
561
|
+
if (proxy !== void 0) out.proxy = proxy;
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
function definedOnly(value) {
|
|
565
|
+
const out = {};
|
|
566
|
+
for (const [k, v] of Object.entries(value)) {
|
|
567
|
+
if (v !== void 0) out[k] = v;
|
|
568
|
+
}
|
|
569
|
+
return out;
|
|
570
|
+
}
|
|
571
|
+
function mergeOptions(...layers) {
|
|
572
|
+
const out = {};
|
|
573
|
+
for (const layer of layers) {
|
|
574
|
+
if (layer === void 0) continue;
|
|
575
|
+
for (const [k, v] of Object.entries(definedOnly(layer))) {
|
|
576
|
+
const prev = out[k];
|
|
577
|
+
if ((k === "tls" || k === "headers" || k === "retry" && !(v instanceof RetryPolicy)) && typeof prev === "object" && prev !== null) {
|
|
578
|
+
const base = prev instanceof RetryPolicy ? prev.toJSON() : prev;
|
|
579
|
+
out[k] = { ...base, ...definedOnly(v) };
|
|
580
|
+
} else {
|
|
581
|
+
out[k] = v;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return out;
|
|
586
|
+
}
|
|
587
|
+
function describeCommonConfig(config) {
|
|
588
|
+
const headers = {};
|
|
589
|
+
for (const k of Object.keys(config.headers)) headers[k] = REDACTED;
|
|
590
|
+
const out = {
|
|
591
|
+
url: redactUrl(config.url),
|
|
592
|
+
connectTimeoutMs: config.connectTimeoutMs,
|
|
593
|
+
requestTimeoutMs: config.requestTimeoutMs,
|
|
594
|
+
totalTimeoutMs: config.totalTimeoutMs,
|
|
595
|
+
retry: config.retry.toJSON(),
|
|
596
|
+
tls: {
|
|
597
|
+
...config.tls,
|
|
598
|
+
...config.tls.caCertPem === void 0 ? {} : { caCertPem: REDACTED }
|
|
599
|
+
},
|
|
600
|
+
headers
|
|
601
|
+
};
|
|
602
|
+
if (config.proxy !== void 0) out.proxy = redactUrl(config.proxy);
|
|
603
|
+
if (config.userAgentSuffix !== void 0) out.userAgentSuffix = config.userAgentSuffix;
|
|
604
|
+
return out;
|
|
605
|
+
}
|
|
606
|
+
function secretValues(...values) {
|
|
607
|
+
return values.filter((v) => v instanceof Secret).map((s) => s.reveal());
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// src/core/version.ts
|
|
611
|
+
var SDK_VERSION = "0.1.1";
|
|
612
|
+
var PACKAGE_KEY = "grafana-loki";
|
|
613
|
+
var LANGUAGE = "typescript";
|
|
614
|
+
var SDK_KIT_VERSION = "0.3.0";
|
|
615
|
+
|
|
616
|
+
// src/core/transport.ts
|
|
617
|
+
var DEFAULT_REQUEST_ID_HEADERS = [
|
|
618
|
+
"x-request-id",
|
|
619
|
+
"x-amzn-requestid",
|
|
620
|
+
"x-amz-request-id",
|
|
621
|
+
"x-datadog-request-id",
|
|
622
|
+
"request-id",
|
|
623
|
+
"x-correlation-id"
|
|
624
|
+
];
|
|
625
|
+
var MAX_VENDOR_TEXT = 300;
|
|
626
|
+
var PRE_SEND_CODES = /* @__PURE__ */ new Set([
|
|
627
|
+
"ECONNREFUSED",
|
|
628
|
+
"ENOTFOUND",
|
|
629
|
+
"EAI_AGAIN",
|
|
630
|
+
"EHOSTUNREACH",
|
|
631
|
+
"ENETUNREACH",
|
|
632
|
+
"EADDRNOTAVAIL",
|
|
633
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
634
|
+
]);
|
|
635
|
+
var TLS_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS|ERR_SSL|DEPTH_ZERO/;
|
|
636
|
+
var CANCEL = /* @__PURE__ */ Symbol("cancel");
|
|
637
|
+
var ATTEMPT_TIMEOUT = /* @__PURE__ */ Symbol("attempt-timeout");
|
|
638
|
+
var insecureWarned = false;
|
|
639
|
+
var AbortedAttempt = class extends Error {
|
|
640
|
+
kind;
|
|
641
|
+
constructor(kind) {
|
|
642
|
+
super("aborted");
|
|
643
|
+
this.kind = kind;
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
function errorCode(err) {
|
|
647
|
+
let current = err;
|
|
648
|
+
for (let depth = 0; depth < 5 && current !== void 0 && current !== null; depth++) {
|
|
649
|
+
const code = current.code;
|
|
650
|
+
if (typeof code === "string") return code;
|
|
651
|
+
current = current.cause;
|
|
652
|
+
}
|
|
653
|
+
return void 0;
|
|
654
|
+
}
|
|
655
|
+
function readPem(path) {
|
|
656
|
+
return path === void 0 ? void 0 : fs.readFileSync(path, "utf8");
|
|
657
|
+
}
|
|
658
|
+
function createDispatcher(config, logger = safeLogger(config.logger)) {
|
|
659
|
+
const tls = config.tls;
|
|
660
|
+
if (tls.insecureSkipVerify === true && !insecureWarned) {
|
|
661
|
+
insecureWarned = true;
|
|
662
|
+
logger.warn("TLS certificate verification is disabled (insecureSkipVerify); use only in tests");
|
|
663
|
+
}
|
|
664
|
+
const caParts = [tls.caCertPem, readPem(tls.caCertPath)].filter(
|
|
665
|
+
(v) => v !== void 0
|
|
666
|
+
);
|
|
667
|
+
const tlsOptions2 = {
|
|
668
|
+
timeout: config.connectTimeoutMs,
|
|
669
|
+
rejectUnauthorized: tls.insecureSkipVerify !== true,
|
|
670
|
+
...caParts.length > 0 ? { ca: caParts } : {},
|
|
671
|
+
...tls.clientCertPath === void 0 ? {} : { cert: readPem(tls.clientCertPath) },
|
|
672
|
+
...tls.clientKeyPath === void 0 ? {} : { key: readPem(tls.clientKeyPath) }
|
|
673
|
+
};
|
|
674
|
+
if (config.proxy !== void 0) {
|
|
675
|
+
return new undici.ProxyAgent({
|
|
676
|
+
uri: config.proxy,
|
|
677
|
+
connect: { timeout: config.connectTimeoutMs },
|
|
678
|
+
requestTls: tlsOptions2
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
return new undici.Agent({ connect: tlsOptions2 });
|
|
682
|
+
}
|
|
683
|
+
var HttpTransport = class {
|
|
684
|
+
/** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
|
|
685
|
+
userAgent;
|
|
686
|
+
retry;
|
|
687
|
+
#config;
|
|
688
|
+
#options;
|
|
689
|
+
#logger;
|
|
690
|
+
#hooks;
|
|
691
|
+
#fetch;
|
|
692
|
+
#sleep;
|
|
693
|
+
#now;
|
|
694
|
+
#requestIdHeaders;
|
|
695
|
+
#dispatcher;
|
|
696
|
+
#closed = false;
|
|
697
|
+
constructor(options) {
|
|
698
|
+
this.#options = options;
|
|
699
|
+
this.#config = options.config;
|
|
700
|
+
this.retry = options.config.retry;
|
|
701
|
+
this.#logger = safeLogger(options.config.logger);
|
|
702
|
+
this.#hooks = options.config.hooks ?? {};
|
|
703
|
+
this.#fetch = undici.fetch;
|
|
704
|
+
this.#sleep = options.sleep ?? chunkVGAJJR3M_cjs.sleep;
|
|
705
|
+
this.#now = options.now ?? Date.now;
|
|
706
|
+
this.#requestIdHeaders = options.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS;
|
|
707
|
+
this.#dispatcher = options.dispatcher;
|
|
708
|
+
const suffix = options.config.userAgentSuffix;
|
|
709
|
+
this.userAgent = `grow-codes-${PACKAGE_KEY}/${SDK_VERSION} (${LANGUAGE})` + (suffix !== void 0 && suffix !== "" ? ` ${suffix}` : "");
|
|
710
|
+
}
|
|
711
|
+
/** Whether {@link close} was called. */
|
|
712
|
+
get closed() {
|
|
713
|
+
return this.#closed;
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Throws `CancelledError` (`"<operation>: client is closed"`, not retryable) once {@link close}
|
|
717
|
+
* was called (SPEC §2.4). Requests check this themselves; service methods that send no request
|
|
718
|
+
* (cached reads, local helpers) call it first.
|
|
719
|
+
*/
|
|
720
|
+
ensureOpen(operation) {
|
|
721
|
+
if (this.#closed) throw new chunkVGAJJR3M_cjs.CancelledError(`${operation}: client is closed`);
|
|
722
|
+
}
|
|
723
|
+
/** Builds the absolute URL for a path and query. */
|
|
724
|
+
buildUrl(path, query) {
|
|
725
|
+
let url;
|
|
726
|
+
if (/^https?:\/\//i.test(path)) {
|
|
727
|
+
url = new URL(path);
|
|
728
|
+
} else {
|
|
729
|
+
const base = this.#config.url.endsWith("/") ? this.#config.url : this.#config.url + "/";
|
|
730
|
+
url = new URL(path.replace(/^\/+/, ""), base);
|
|
731
|
+
}
|
|
732
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
733
|
+
if (v === void 0 || v === null) continue;
|
|
734
|
+
if (Array.isArray(v)) {
|
|
735
|
+
for (const item of v)
|
|
736
|
+
url.searchParams.append(k, String(item));
|
|
737
|
+
} else {
|
|
738
|
+
url.searchParams.append(k, String(v));
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return url;
|
|
742
|
+
}
|
|
743
|
+
/** Redacts known secrets from a text (error messages, vendor text). */
|
|
744
|
+
redact(text) {
|
|
745
|
+
return redactText(text, this.#knownSecrets());
|
|
746
|
+
}
|
|
747
|
+
#knownSecrets() {
|
|
748
|
+
return [...this.#options.knownSecrets?.() ?? []];
|
|
749
|
+
}
|
|
750
|
+
#getDispatcher() {
|
|
751
|
+
this.#dispatcher ??= createDispatcher(this.#config, this.#logger);
|
|
752
|
+
return this.#dispatcher;
|
|
753
|
+
}
|
|
754
|
+
/** `GET` shortcut. */
|
|
755
|
+
get(path, options = {}) {
|
|
756
|
+
return this.request({ ...options, method: "GET", path });
|
|
757
|
+
}
|
|
758
|
+
/** `POST` shortcut. */
|
|
759
|
+
post(path, options = {}) {
|
|
760
|
+
return this.request({ ...options, method: "POST", path });
|
|
761
|
+
}
|
|
762
|
+
/** `PUT` shortcut. */
|
|
763
|
+
put(path, options = {}) {
|
|
764
|
+
return this.request({ ...options, method: "PUT", path });
|
|
765
|
+
}
|
|
766
|
+
/** `DELETE` shortcut. */
|
|
767
|
+
delete(path, options = {}) {
|
|
768
|
+
return this.request({ ...options, method: "DELETE", path });
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Sends a request with retries; throws an SDK error on failure. Every error message passes
|
|
772
|
+
* through {@link redact} with the known secrets.
|
|
773
|
+
*/
|
|
774
|
+
async request(options) {
|
|
775
|
+
try {
|
|
776
|
+
return await this.#request(options);
|
|
777
|
+
} catch (err) {
|
|
778
|
+
if (err instanceof chunkVGAJJR3M_cjs.LokiError) err.message = this.redact(err.message);
|
|
779
|
+
throw err;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
async #request(options) {
|
|
783
|
+
const method = (options.method ?? "GET").toUpperCase();
|
|
784
|
+
const operation = options.operation ?? `${method} ${options.path.split("?")[0] ?? ""}`;
|
|
785
|
+
this.ensureOpen(operation);
|
|
786
|
+
const signal = options.signal;
|
|
787
|
+
if (signal?.aborted === true) throw new chunkVGAJJR3M_cjs.CancelledError(`${operation}: cancelled`);
|
|
788
|
+
const url = this.buildUrl(options.path, options.query);
|
|
789
|
+
const safeUrl = redactUrl(url);
|
|
790
|
+
const headers = this.#buildHeaders(options);
|
|
791
|
+
const body = options.json !== void 0 ? JSON.stringify(options.json) : options.body;
|
|
792
|
+
const idempotent = options.idempotent ?? isIdempotentMethod(method);
|
|
793
|
+
const requestTimeout = options.requestTimeoutMs ?? this.#config.requestTimeoutMs;
|
|
794
|
+
const totalTimeout = options.totalTimeoutMs ?? this.#config.totalTimeoutMs;
|
|
795
|
+
const start = this.#now();
|
|
796
|
+
const deadline = start + totalTimeout;
|
|
797
|
+
const policy = this.retry;
|
|
798
|
+
for (let attempt = 1; ; attempt++) {
|
|
799
|
+
const remaining = deadline - this.#now();
|
|
800
|
+
if (remaining <= 0) {
|
|
801
|
+
throw new chunkVGAJJR3M_cjs.TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`);
|
|
802
|
+
}
|
|
803
|
+
const attemptTimeout = Math.min(requestTimeout, remaining);
|
|
804
|
+
const isTotal = attemptTimeout < requestTimeout;
|
|
805
|
+
safeCall(this.#hooks.onRequest, {
|
|
806
|
+
method,
|
|
807
|
+
url: safeUrl,
|
|
808
|
+
headers: redactHeaders(headers),
|
|
809
|
+
attempt
|
|
810
|
+
});
|
|
811
|
+
this.#logger.debug("http request", { method, url: safeUrl, attempt });
|
|
812
|
+
const attemptStart = this.#now();
|
|
813
|
+
let failure;
|
|
814
|
+
let willRetry = false;
|
|
815
|
+
let waitMs = 0;
|
|
816
|
+
try {
|
|
817
|
+
const res = await this.#attempt(
|
|
818
|
+
url,
|
|
819
|
+
method,
|
|
820
|
+
headers,
|
|
821
|
+
body,
|
|
822
|
+
attemptTimeout,
|
|
823
|
+
signal,
|
|
824
|
+
options.responseType ?? "json",
|
|
825
|
+
options.allowStatus ?? []
|
|
826
|
+
);
|
|
827
|
+
const durationMs = this.#now() - attemptStart;
|
|
828
|
+
const requestId = this.#requestId(res.headers);
|
|
829
|
+
safeCall(this.#hooks.onResponse, {
|
|
830
|
+
method,
|
|
831
|
+
url: safeUrl,
|
|
832
|
+
status: res.status,
|
|
833
|
+
durationMs,
|
|
834
|
+
attempt,
|
|
835
|
+
...requestId === void 0 ? {} : { requestId }
|
|
836
|
+
});
|
|
837
|
+
this.#logger.debug("http response", {
|
|
838
|
+
method,
|
|
839
|
+
url: safeUrl,
|
|
840
|
+
status: res.status,
|
|
841
|
+
durationMs,
|
|
842
|
+
attempt
|
|
843
|
+
});
|
|
844
|
+
if (res.status < 400 || options.allowStatus?.includes(res.status) === true) {
|
|
845
|
+
return {
|
|
846
|
+
status: res.status,
|
|
847
|
+
headers: res.headers,
|
|
848
|
+
data: res.data,
|
|
849
|
+
...requestId === void 0 ? {} : { requestId },
|
|
850
|
+
durationMs: this.#now() - start,
|
|
851
|
+
attempts: attempt,
|
|
852
|
+
...res.status >= 400 ? { text: res.text } : {}
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
const retryAfter = res.status === 429 || res.status === 503 ? parseRetryAfter(res.headers.get("retry-after"), this.#now()) : void 0;
|
|
856
|
+
const reason = this.vendorText(res.text);
|
|
857
|
+
const defaultError = chunkVGAJJR3M_cjs.errorForStatus(operation, res.status, {
|
|
858
|
+
...reason === void 0 ? {} : { reason },
|
|
859
|
+
...requestId === void 0 ? {} : { requestId },
|
|
860
|
+
...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
|
|
861
|
+
});
|
|
862
|
+
const classified = this.#classifyResponse(options.classifyError, {
|
|
863
|
+
operation,
|
|
864
|
+
method,
|
|
865
|
+
status: res.status,
|
|
866
|
+
headers: res.headers,
|
|
867
|
+
body: res.text,
|
|
868
|
+
...reason === void 0 ? {} : { reason },
|
|
869
|
+
...requestId === void 0 ? {} : { requestId },
|
|
870
|
+
...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter },
|
|
871
|
+
attempt,
|
|
872
|
+
defaultError
|
|
873
|
+
});
|
|
874
|
+
failure = classified ?? defaultError;
|
|
875
|
+
if (isRetryableStatus(res.status, idempotent) && (classified === void 0 || classified.retryable) && attempt <= policy.maxRetries) {
|
|
876
|
+
const backoff = policy.backoffMs(attempt - 1);
|
|
877
|
+
if (retryAfter !== void 0) {
|
|
878
|
+
if (retryAfter > policy.maxRetryAfterMs || retryAfter >= deadline - this.#now()) {
|
|
879
|
+
willRetry = false;
|
|
880
|
+
} else {
|
|
881
|
+
willRetry = true;
|
|
882
|
+
waitMs = Math.max(retryAfter, backoff);
|
|
883
|
+
}
|
|
884
|
+
} else {
|
|
885
|
+
willRetry = true;
|
|
886
|
+
waitMs = backoff;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
} catch (err) {
|
|
890
|
+
failure = this.#classify(err, operation, attemptTimeout, isTotal, totalTimeout);
|
|
891
|
+
const preSend = PRE_SEND_CODES.has(errorCode(err) ?? "");
|
|
892
|
+
willRetry = failure.retryable && !(failure.code === "TIMEOUT" && isTotal) && (idempotent || preSend) && attempt <= policy.maxRetries;
|
|
893
|
+
waitMs = willRetry ? policy.backoffMs(attempt - 1) : 0;
|
|
894
|
+
}
|
|
895
|
+
if (willRetry && waitMs >= deadline - this.#now()) {
|
|
896
|
+
safeCall(this.#hooks.onError, {
|
|
897
|
+
method,
|
|
898
|
+
url: safeUrl,
|
|
899
|
+
error: failure,
|
|
900
|
+
attempt,
|
|
901
|
+
willRetry: false
|
|
902
|
+
});
|
|
903
|
+
throw new chunkVGAJJR3M_cjs.TimeoutError(
|
|
904
|
+
`${operation}: total timeout of ${totalTimeout} ms exceeded after ${attempt} attempts`,
|
|
905
|
+
{
|
|
906
|
+
cause: failure,
|
|
907
|
+
...failure.httpStatus === void 0 ? {} : { httpStatus: failure.httpStatus },
|
|
908
|
+
...failure.requestId === void 0 ? {} : { requestId: failure.requestId }
|
|
909
|
+
}
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
safeCall(this.#hooks.onError, { method, url: safeUrl, error: failure, attempt, willRetry });
|
|
913
|
+
if (!willRetry) {
|
|
914
|
+
this.#logger.debug("http call failed", {
|
|
915
|
+
method,
|
|
916
|
+
url: safeUrl,
|
|
917
|
+
attempt,
|
|
918
|
+
code: failure.code
|
|
919
|
+
});
|
|
920
|
+
throw failure;
|
|
921
|
+
}
|
|
922
|
+
this.#logger.warn("http call failed, retrying", {
|
|
923
|
+
method,
|
|
924
|
+
url: safeUrl,
|
|
925
|
+
attempt,
|
|
926
|
+
code: failure.code,
|
|
927
|
+
waitMs: Math.round(waitMs)
|
|
928
|
+
});
|
|
929
|
+
await this.#sleep(waitMs, signal).catch((err) => {
|
|
930
|
+
throw err instanceof chunkVGAJJR3M_cjs.LokiError ? err : new chunkVGAJJR3M_cjs.CancelledError(`${operation}: cancelled`);
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
#buildHeaders(options) {
|
|
935
|
+
const headers = {
|
|
936
|
+
accept: "application/json",
|
|
937
|
+
"user-agent": this.userAgent
|
|
938
|
+
};
|
|
939
|
+
const layers = [
|
|
940
|
+
this.#config.headers,
|
|
941
|
+
this.#options.defaultHeaders?.() ?? {},
|
|
942
|
+
options.headers ?? {}
|
|
943
|
+
];
|
|
944
|
+
for (const layer of layers) {
|
|
945
|
+
for (const [k, v] of Object.entries(layer)) headers[k.toLowerCase()] = v;
|
|
946
|
+
}
|
|
947
|
+
if (options.json !== void 0 && headers["content-type"] === void 0) {
|
|
948
|
+
headers["content-type"] = "application/json";
|
|
949
|
+
}
|
|
950
|
+
return headers;
|
|
951
|
+
}
|
|
952
|
+
async #attempt(url, method, headers, body, timeoutMs, signal, responseType, allowStatus) {
|
|
953
|
+
const controller = new AbortController();
|
|
954
|
+
const timer = setTimeout(() => {
|
|
955
|
+
controller.abort(ATTEMPT_TIMEOUT);
|
|
956
|
+
}, timeoutMs);
|
|
957
|
+
timer.unref();
|
|
958
|
+
const onAbort = () => {
|
|
959
|
+
controller.abort(CANCEL);
|
|
960
|
+
};
|
|
961
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
962
|
+
try {
|
|
963
|
+
const init = {
|
|
964
|
+
method,
|
|
965
|
+
headers,
|
|
966
|
+
signal: controller.signal,
|
|
967
|
+
dispatcher: this.#getDispatcher(),
|
|
968
|
+
redirect: "follow"
|
|
969
|
+
};
|
|
970
|
+
if (body !== void 0) init.body = body;
|
|
971
|
+
const res = await this.#fetch(url, init);
|
|
972
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
973
|
+
const isError = res.status >= 400;
|
|
974
|
+
const allowed = isError && allowStatus.includes(res.status);
|
|
975
|
+
const text = isError || responseType === "json" || responseType === "text" ? new TextDecoder().decode(bytes) : "";
|
|
976
|
+
let data;
|
|
977
|
+
if (isError && !allowed || responseType === "none") {
|
|
978
|
+
data = void 0;
|
|
979
|
+
} else if (responseType === "bytes") {
|
|
980
|
+
data = bytes;
|
|
981
|
+
} else if (responseType === "text") {
|
|
982
|
+
data = text;
|
|
983
|
+
} else if (allowed) {
|
|
984
|
+
data = parseJsonOrUndefined(text);
|
|
985
|
+
} else {
|
|
986
|
+
data = this.#parseJson(text, res.status);
|
|
987
|
+
}
|
|
988
|
+
return { status: res.status, headers: res.headers, data, text };
|
|
989
|
+
} catch (err) {
|
|
990
|
+
const reason = controller.signal.reason;
|
|
991
|
+
if (controller.signal.aborted && (reason === CANCEL || reason === ATTEMPT_TIMEOUT)) {
|
|
992
|
+
throw new AbortedAttempt(reason);
|
|
993
|
+
}
|
|
994
|
+
throw err;
|
|
995
|
+
} finally {
|
|
996
|
+
clearTimeout(timer);
|
|
997
|
+
signal?.removeEventListener("abort", onAbort);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
#parseJson(text, status) {
|
|
1001
|
+
if (text.trim() === "") return void 0;
|
|
1002
|
+
try {
|
|
1003
|
+
return JSON.parse(text);
|
|
1004
|
+
} catch {
|
|
1005
|
+
throw new chunkVGAJJR3M_cjs.UnavailableError(`invalid JSON in response (HTTP ${status})`, {
|
|
1006
|
+
retryable: false,
|
|
1007
|
+
httpStatus: status
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
#classify(err, operation, timeoutMs, isTotal, totalTimeout) {
|
|
1012
|
+
if (err instanceof chunkVGAJJR3M_cjs.LokiError) return err;
|
|
1013
|
+
if (err instanceof AbortedAttempt) {
|
|
1014
|
+
if (err.kind === CANCEL) return new chunkVGAJJR3M_cjs.CancelledError(`${operation}: cancelled`);
|
|
1015
|
+
return isTotal ? new chunkVGAJJR3M_cjs.TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`) : new chunkVGAJJR3M_cjs.TimeoutError(`${operation}: request timed out after ${timeoutMs} ms`);
|
|
1016
|
+
}
|
|
1017
|
+
const cause = redactError(err, this.#knownSecrets());
|
|
1018
|
+
const code = errorCode(err);
|
|
1019
|
+
if (code === "UND_ERR_CONNECT_TIMEOUT") {
|
|
1020
|
+
return new chunkVGAJJR3M_cjs.TimeoutError(
|
|
1021
|
+
`${operation}: connect timeout after ${this.#config.connectTimeoutMs} ms`,
|
|
1022
|
+
{ cause }
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
if (code !== void 0 && TLS_CODE.test(code)) {
|
|
1026
|
+
return new chunkVGAJJR3M_cjs.UnavailableError(`${operation}: TLS error (${code})`, { cause, retryable: false });
|
|
1027
|
+
}
|
|
1028
|
+
return new chunkVGAJJR3M_cjs.UnavailableError(
|
|
1029
|
+
`${operation}: network error${code === void 0 ? "" : ` (${code})`}`,
|
|
1030
|
+
{ cause }
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
#classifyResponse(perRequest, response) {
|
|
1034
|
+
for (const classify of [perRequest, this.#options.classifyError]) {
|
|
1035
|
+
if (classify === void 0) continue;
|
|
1036
|
+
let mapped;
|
|
1037
|
+
try {
|
|
1038
|
+
mapped = classify(response);
|
|
1039
|
+
} catch (err) {
|
|
1040
|
+
mapped = err instanceof chunkVGAJJR3M_cjs.LokiError ? err : void 0;
|
|
1041
|
+
}
|
|
1042
|
+
if (mapped instanceof chunkVGAJJR3M_cjs.LokiError) return mapped;
|
|
1043
|
+
}
|
|
1044
|
+
return void 0;
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
|
|
1048
|
+
* text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
|
|
1049
|
+
* {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
|
|
1050
|
+
*/
|
|
1051
|
+
vendorText(text) {
|
|
1052
|
+
const trimmed = text.trim();
|
|
1053
|
+
if (trimmed === "") return void 0;
|
|
1054
|
+
let extracted;
|
|
1055
|
+
try {
|
|
1056
|
+
extracted = extractMessage(JSON.parse(trimmed));
|
|
1057
|
+
} catch {
|
|
1058
|
+
extracted = /^\s*</.test(trimmed) ? void 0 : trimmed;
|
|
1059
|
+
}
|
|
1060
|
+
const collapsed = extracted?.replace(/\s+/g, " ").trim();
|
|
1061
|
+
if (collapsed === void 0 || collapsed === "") return void 0;
|
|
1062
|
+
const redacted = redactSecretsInText(this.redact(collapsed));
|
|
1063
|
+
return redacted.length > MAX_VENDOR_TEXT ? redacted.slice(0, MAX_VENDOR_TEXT - 1).trimEnd() + "\u2026" : redacted;
|
|
1064
|
+
}
|
|
1065
|
+
#requestId(headers) {
|
|
1066
|
+
for (const name of this.#requestIdHeaders) {
|
|
1067
|
+
const v = headers.get(name);
|
|
1068
|
+
if (v !== null && v !== "") return v;
|
|
1069
|
+
}
|
|
1070
|
+
return void 0;
|
|
1071
|
+
}
|
|
1072
|
+
/** Releases connections. Idempotent. */
|
|
1073
|
+
async close() {
|
|
1074
|
+
if (this.#closed) return;
|
|
1075
|
+
this.#closed = true;
|
|
1076
|
+
const dispatcher = this.#dispatcher;
|
|
1077
|
+
this.#dispatcher = void 0;
|
|
1078
|
+
if (dispatcher !== void 0 && this.#options.dispatcher === void 0) {
|
|
1079
|
+
await dispatcher.close().catch(() => void 0);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
function parseJsonOrUndefined(text) {
|
|
1084
|
+
if (text.trim() === "") return void 0;
|
|
1085
|
+
try {
|
|
1086
|
+
return JSON.parse(text);
|
|
1087
|
+
} catch {
|
|
1088
|
+
return void 0;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
function extractMessage(body) {
|
|
1092
|
+
if (typeof body === "string") return body;
|
|
1093
|
+
if (body === null || typeof body !== "object") return void 0;
|
|
1094
|
+
if (Array.isArray(body)) return body.length > 0 ? extractMessage(body[0]) : void 0;
|
|
1095
|
+
const obj = body;
|
|
1096
|
+
for (const key of [
|
|
1097
|
+
"message",
|
|
1098
|
+
"error_description",
|
|
1099
|
+
"error",
|
|
1100
|
+
"errors",
|
|
1101
|
+
"detail",
|
|
1102
|
+
"msg",
|
|
1103
|
+
"title",
|
|
1104
|
+
"reason"
|
|
1105
|
+
]) {
|
|
1106
|
+
const found = extractMessage(obj[key]);
|
|
1107
|
+
if (found !== void 0 && found !== "") return found;
|
|
1108
|
+
}
|
|
1109
|
+
return void 0;
|
|
1110
|
+
}
|
|
1111
|
+
var SECRET_ASSIGNMENT = /((?:password|passwd|secret|token|authorization|api[_-]?key|access[_-]?key|private[_-]?key|credential|session|signature)["']?\s*[:=]\s*["']?)([^"'\s,;&}]+)/gi;
|
|
1112
|
+
var BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi;
|
|
1113
|
+
function redactSecretsInText(text) {
|
|
1114
|
+
return text.replace(BEARER, "$1 [REDACTED]").replace(SECRET_ASSIGNMENT, "$1[REDACTED]");
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// src/config.ts
|
|
1118
|
+
var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
1119
|
+
var CATALOG_PORT = "3100";
|
|
1120
|
+
var MAX_TENANT_ID_LENGTH = 150;
|
|
1121
|
+
var TENANT_CHARS = /^[A-Za-z0-9!\-_.*'()]+$/;
|
|
1122
|
+
var LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
1123
|
+
function tenantIdProblem(id, multiTenantQueries = false) {
|
|
1124
|
+
if (id.includes("|")) {
|
|
1125
|
+
if (!multiTenantQueries) {
|
|
1126
|
+
return "tenant id must not contain '|' (multi-tenant queries are not enabled)";
|
|
1127
|
+
}
|
|
1128
|
+
for (const part of id.split("|")) {
|
|
1129
|
+
const problem = tenantIdProblem(part, false);
|
|
1130
|
+
if (problem !== void 0) return problem;
|
|
1131
|
+
}
|
|
1132
|
+
return void 0;
|
|
1133
|
+
}
|
|
1134
|
+
if (id === "") return "tenant id must not be empty";
|
|
1135
|
+
if (new TextEncoder().encode(id).length > MAX_TENANT_ID_LENGTH) {
|
|
1136
|
+
return `tenant id is too long (max ${MAX_TENANT_ID_LENGTH} bytes)`;
|
|
1137
|
+
}
|
|
1138
|
+
if (id === "." || id === "..") return "tenant id must not be '.' or '..'";
|
|
1139
|
+
if (!TENANT_CHARS.test(id)) {
|
|
1140
|
+
return "tenant id may only contain letters, digits and !-_.*'()";
|
|
1141
|
+
}
|
|
1142
|
+
return void 0;
|
|
1143
|
+
}
|
|
1144
|
+
var VENDOR_ENV = {
|
|
1145
|
+
url: ["LOKI_URL"],
|
|
1146
|
+
tenantId: ["LOKI_TENANT_ID"],
|
|
1147
|
+
username: ["LOKI_USERNAME", "LOKI_BASIC_AUTH_USER"],
|
|
1148
|
+
password: ["LOKI_PASSWORD", "LOKI_BASIC_AUTH_PASSWORD"],
|
|
1149
|
+
bearerToken: ["LOKI_BEARER_TOKEN"]
|
|
1150
|
+
};
|
|
1151
|
+
var LokiConfig = class _LokiConfig {
|
|
1152
|
+
/** Default endpoint. */
|
|
1153
|
+
static DEFAULT_URL = `http://127.0.0.1:${/\d+/.exec(CATALOG_PORT)?.[0] ?? "8080"}`;
|
|
1154
|
+
/** Prefix of every environment variable. */
|
|
1155
|
+
static ENV_PREFIX = "GROW_GRAFANA_LOKI_";
|
|
1156
|
+
url;
|
|
1157
|
+
connectTimeoutMs;
|
|
1158
|
+
requestTimeoutMs;
|
|
1159
|
+
totalTimeoutMs;
|
|
1160
|
+
retry;
|
|
1161
|
+
tls;
|
|
1162
|
+
proxy;
|
|
1163
|
+
headers;
|
|
1164
|
+
userAgentSuffix;
|
|
1165
|
+
hooks;
|
|
1166
|
+
logger;
|
|
1167
|
+
/** Tenant (`X-Scope-OrgID`); not sent when unset. */
|
|
1168
|
+
tenantId;
|
|
1169
|
+
/** Basic-auth user. */
|
|
1170
|
+
username;
|
|
1171
|
+
/** Basic-auth password. */
|
|
1172
|
+
password;
|
|
1173
|
+
/** Bearer token. */
|
|
1174
|
+
bearerToken;
|
|
1175
|
+
/** Whether tenant ids joined with `|` are allowed. */
|
|
1176
|
+
multiTenantQueries;
|
|
1177
|
+
/** Configured cardinality guard allowlist (`undefined` = `DEFAULT_ALLOWED_LABELS`). */
|
|
1178
|
+
allowedLabels;
|
|
1179
|
+
/** Whether `push` skips the cardinality guard. */
|
|
1180
|
+
disableLabelGuard;
|
|
1181
|
+
/** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
|
|
1182
|
+
constructor(options = {}) {
|
|
1183
|
+
const common = resolveCommonConfig(options, _LokiConfig.DEFAULT_URL);
|
|
1184
|
+
this.url = common.url;
|
|
1185
|
+
this.connectTimeoutMs = common.connectTimeoutMs;
|
|
1186
|
+
this.requestTimeoutMs = common.requestTimeoutMs;
|
|
1187
|
+
this.totalTimeoutMs = common.totalTimeoutMs;
|
|
1188
|
+
this.retry = common.retry;
|
|
1189
|
+
this.tls = common.tls;
|
|
1190
|
+
this.headers = common.headers;
|
|
1191
|
+
if (common.proxy !== void 0) this.proxy = common.proxy;
|
|
1192
|
+
if (common.userAgentSuffix !== void 0) this.userAgentSuffix = common.userAgentSuffix;
|
|
1193
|
+
if (common.hooks !== void 0) this.hooks = common.hooks;
|
|
1194
|
+
if (common.logger !== void 0) this.logger = common.logger;
|
|
1195
|
+
if (options.tenantId !== void 0 && options.tenantId !== "") this.tenantId = options.tenantId;
|
|
1196
|
+
if (options.username !== void 0 && options.username !== "") this.username = options.username;
|
|
1197
|
+
const password = Secret.from(options.password);
|
|
1198
|
+
if (password !== void 0) this.password = password;
|
|
1199
|
+
const bearer = Secret.from(options.bearerToken);
|
|
1200
|
+
if (bearer !== void 0) this.bearerToken = bearer;
|
|
1201
|
+
this.multiTenantQueries = options.multiTenantQueries ?? false;
|
|
1202
|
+
if (options.allowedLabels !== void 0) {
|
|
1203
|
+
this.allowedLabels = Object.freeze([...options.allowedLabels]);
|
|
1204
|
+
}
|
|
1205
|
+
this.disableLabelGuard = options.disableLabelGuard ?? false;
|
|
1206
|
+
this.validate();
|
|
1207
|
+
Object.freeze(this);
|
|
1208
|
+
}
|
|
1209
|
+
/** Returns `options` when it already is a config, otherwise builds one. */
|
|
1210
|
+
static from(options = {}) {
|
|
1211
|
+
if (options instanceof _LokiConfig) return options;
|
|
1212
|
+
return new _LokiConfig(options);
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Builds a config from the environment. Precedence: explicit `overrides` >
|
|
1216
|
+
* `GROW_GRAFANA_LOKI_<NAME>` > vendor variables ({@link VENDOR_ENV}) > defaults.
|
|
1217
|
+
*/
|
|
1218
|
+
static fromEnv(overrides = {}, env = process.env) {
|
|
1219
|
+
const reader = new EnvReader(_LokiConfig.ENV_PREFIX, env);
|
|
1220
|
+
const fromEnv = readCommonEnv(reader, VENDOR_ENV);
|
|
1221
|
+
const tenantId = reader.string("TENANT_ID", VENDOR_ENV.tenantId);
|
|
1222
|
+
if (tenantId !== void 0) fromEnv.tenantId = tenantId;
|
|
1223
|
+
const username = reader.string("USERNAME", VENDOR_ENV.username);
|
|
1224
|
+
if (username !== void 0) fromEnv.username = username;
|
|
1225
|
+
const password = reader.secret("PASSWORD", VENDOR_ENV.password);
|
|
1226
|
+
if (password !== void 0) fromEnv.password = password;
|
|
1227
|
+
const bearer = reader.secret("BEARER_TOKEN", VENDOR_ENV.bearerToken);
|
|
1228
|
+
if (bearer !== void 0) fromEnv.bearerToken = bearer;
|
|
1229
|
+
const merged = mergeOptions(fromEnv, overrides);
|
|
1230
|
+
return new _LokiConfig(merged);
|
|
1231
|
+
}
|
|
1232
|
+
/** A copy of this config with some fields replaced (validated again). */
|
|
1233
|
+
with(overrides) {
|
|
1234
|
+
const current = {
|
|
1235
|
+
url: this.url,
|
|
1236
|
+
connectTimeoutMs: this.connectTimeoutMs,
|
|
1237
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
1238
|
+
totalTimeoutMs: this.totalTimeoutMs,
|
|
1239
|
+
retry: this.retry,
|
|
1240
|
+
tls: { ...this.tls },
|
|
1241
|
+
headers: { ...this.headers },
|
|
1242
|
+
...this.proxy === void 0 ? {} : { proxy: this.proxy },
|
|
1243
|
+
...this.userAgentSuffix === void 0 ? {} : { userAgentSuffix: this.userAgentSuffix },
|
|
1244
|
+
...this.hooks === void 0 ? {} : { hooks: this.hooks },
|
|
1245
|
+
...this.logger === void 0 ? {} : { logger: this.logger },
|
|
1246
|
+
...this.tenantId === void 0 ? {} : { tenantId: this.tenantId },
|
|
1247
|
+
...this.username === void 0 ? {} : { username: this.username },
|
|
1248
|
+
...this.password === void 0 ? {} : { password: this.password },
|
|
1249
|
+
...this.bearerToken === void 0 ? {} : { bearerToken: this.bearerToken },
|
|
1250
|
+
multiTenantQueries: this.multiTenantQueries,
|
|
1251
|
+
...this.allowedLabels === void 0 ? {} : { allowedLabels: this.allowedLabels },
|
|
1252
|
+
disableLabelGuard: this.disableLabelGuard
|
|
1253
|
+
};
|
|
1254
|
+
return new _LokiConfig({ ...current, ...overrides });
|
|
1255
|
+
}
|
|
1256
|
+
/** Throws {@link ConfigError} when a setting is invalid. */
|
|
1257
|
+
validate() {
|
|
1258
|
+
validateCommonConfig(this);
|
|
1259
|
+
const problems = [];
|
|
1260
|
+
if (this.tenantId !== void 0) {
|
|
1261
|
+
const problem = tenantIdProblem(this.tenantId, this.multiTenantQueries);
|
|
1262
|
+
if (problem !== void 0) problems.push(problem);
|
|
1263
|
+
}
|
|
1264
|
+
for (const name of this.allowedLabels ?? []) {
|
|
1265
|
+
if (!LABEL_NAME.test(name) || name.startsWith("__")) {
|
|
1266
|
+
problems.push(`allowedLabels contains an invalid label name ${JSON.stringify(name)}`);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
if (this.username === void 0 !== (this.password === void 0)) {
|
|
1270
|
+
problems.push("username and password must be given together");
|
|
1271
|
+
}
|
|
1272
|
+
if (this.password !== void 0 && this.bearerToken !== void 0) {
|
|
1273
|
+
problems.push("basic auth (username/password) and bearerToken are mutually exclusive");
|
|
1274
|
+
}
|
|
1275
|
+
if (this.bearerToken?.reveal().trim() === "") problems.push("bearerToken must not be blank");
|
|
1276
|
+
if (problems.length > 0) {
|
|
1277
|
+
throw new chunkVGAJJR3M_cjs.ConfigError(`invalid configuration: ${problems.join("; ")}`);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
/** The `Authorization` header value, when credentials are configured. */
|
|
1281
|
+
authorizationHeader() {
|
|
1282
|
+
if (this.bearerToken !== void 0) return `Bearer ${this.bearerToken.reveal()}`;
|
|
1283
|
+
if (this.username !== void 0 && this.password !== void 0) {
|
|
1284
|
+
return `Basic ${basicCredentials(this.username, this.password.reveal())}`;
|
|
1285
|
+
}
|
|
1286
|
+
return void 0;
|
|
1287
|
+
}
|
|
1288
|
+
/** Credential values to redact from error messages and logs. */
|
|
1289
|
+
knownSecrets() {
|
|
1290
|
+
const out = secretValues(this.password, this.bearerToken);
|
|
1291
|
+
if (this.username !== void 0 && this.password !== void 0) {
|
|
1292
|
+
out.push(basicCredentials(this.username, this.password.reveal()));
|
|
1293
|
+
}
|
|
1294
|
+
return out;
|
|
1295
|
+
}
|
|
1296
|
+
/** Debug form with every credential redacted. */
|
|
1297
|
+
toJSON() {
|
|
1298
|
+
return {
|
|
1299
|
+
...describeCommonConfig(this),
|
|
1300
|
+
tenantId: this.tenantId ?? null,
|
|
1301
|
+
username: this.username ?? null,
|
|
1302
|
+
password: this.password === void 0 ? null : REDACTED,
|
|
1303
|
+
bearerToken: this.bearerToken === void 0 ? null : REDACTED,
|
|
1304
|
+
multiTenantQueries: this.multiTenantQueries,
|
|
1305
|
+
allowedLabels: this.allowedLabels ?? null,
|
|
1306
|
+
disableLabelGuard: this.disableLabelGuard
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
toString() {
|
|
1310
|
+
return `LokiConfig(${JSON.stringify(this.toJSON())})`;
|
|
1311
|
+
}
|
|
1312
|
+
[INSPECT2]() {
|
|
1313
|
+
return this.toString();
|
|
1314
|
+
}
|
|
1315
|
+
};
|
|
1316
|
+
function basicCredentials(username, password) {
|
|
1317
|
+
return Buffer.from(`${username}:${password}`, "utf8").toString("base64");
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// src/logging/redaction.ts
|
|
1321
|
+
var DEFAULT_REDACT_KEYS = Object.freeze([
|
|
1322
|
+
"password",
|
|
1323
|
+
"passwd",
|
|
1324
|
+
"token",
|
|
1325
|
+
"authorization",
|
|
1326
|
+
"secret",
|
|
1327
|
+
"cookie",
|
|
1328
|
+
"api_key",
|
|
1329
|
+
"apikey",
|
|
1330
|
+
"access_key",
|
|
1331
|
+
"private_key"
|
|
1332
|
+
]);
|
|
1333
|
+
var RedactionProcessor = class {
|
|
1334
|
+
#keys;
|
|
1335
|
+
#patterns;
|
|
1336
|
+
#replacement;
|
|
1337
|
+
constructor(options = {}) {
|
|
1338
|
+
this.#keys = (options.keys ?? DEFAULT_REDACT_KEYS).map((k) => k.toLowerCase()).filter((k) => k !== "");
|
|
1339
|
+
this.#patterns = (options.patterns ?? []).map(
|
|
1340
|
+
(p) => p.flags.includes("g") ? new RegExp(p.source, p.flags) : new RegExp(p.source, `${p.flags}g`)
|
|
1341
|
+
);
|
|
1342
|
+
this.#replacement = options.replacement ?? "[REDACTED]";
|
|
1343
|
+
}
|
|
1344
|
+
/** Returns a redacted copy of `record`; the input is not modified. */
|
|
1345
|
+
process(record) {
|
|
1346
|
+
return {
|
|
1347
|
+
...record,
|
|
1348
|
+
body: this.redactText(record.body),
|
|
1349
|
+
attributes: this.redactAttributes(record.attributes)
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
/** Whether an attribute name is sensitive. */
|
|
1353
|
+
isSensitiveKey(key) {
|
|
1354
|
+
const lower = key.toLowerCase();
|
|
1355
|
+
return this.#keys.some((k) => lower.includes(k));
|
|
1356
|
+
}
|
|
1357
|
+
/** Applies the patterns to `text`. */
|
|
1358
|
+
redactText(text) {
|
|
1359
|
+
let out = text;
|
|
1360
|
+
for (const pattern of this.#patterns) {
|
|
1361
|
+
pattern.lastIndex = 0;
|
|
1362
|
+
out = out.replace(pattern, this.#replacement);
|
|
1363
|
+
}
|
|
1364
|
+
return out;
|
|
1365
|
+
}
|
|
1366
|
+
/** Redacts an attribute map recursively. */
|
|
1367
|
+
redactAttributes(attributes) {
|
|
1368
|
+
const out = {};
|
|
1369
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
1370
|
+
out[key] = this.isSensitiveKey(key) ? this.#replacement : this.#redactValue(value);
|
|
1371
|
+
}
|
|
1372
|
+
return out;
|
|
1373
|
+
}
|
|
1374
|
+
#redactValue(value) {
|
|
1375
|
+
if (typeof value === "string") return this.redactText(value);
|
|
1376
|
+
if (Array.isArray(value)) return value.map((v) => this.#redactValue(v));
|
|
1377
|
+
if (typeof value === "object") return this.redactAttributes(value);
|
|
1378
|
+
return value;
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
// src/logging/batch.ts
|
|
1383
|
+
var DEFAULT_BATCH_OPTIONS = Object.freeze({
|
|
1384
|
+
maxQueueSize: 2048,
|
|
1385
|
+
maxBatchSize: 512,
|
|
1386
|
+
maxBatchBytes: 1048576,
|
|
1387
|
+
flushIntervalMs: 1e3,
|
|
1388
|
+
exportTimeoutMs: 3e4,
|
|
1389
|
+
dropPolicy: "drop_newest",
|
|
1390
|
+
gzip: true,
|
|
1391
|
+
maxExportRetries: 2,
|
|
1392
|
+
retryBackoffMs: 200
|
|
1393
|
+
});
|
|
1394
|
+
var POSITIVE = [
|
|
1395
|
+
"maxQueueSize",
|
|
1396
|
+
"maxBatchSize",
|
|
1397
|
+
"maxBatchBytes",
|
|
1398
|
+
"flushIntervalMs",
|
|
1399
|
+
"exportTimeoutMs"
|
|
1400
|
+
];
|
|
1401
|
+
var NON_NEGATIVE = ["maxExportRetries", "retryBackoffMs"];
|
|
1402
|
+
function resolveBatchOptions(options = {}) {
|
|
1403
|
+
const defined = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
|
|
1404
|
+
const resolved = { ...DEFAULT_BATCH_OPTIONS, ...defined };
|
|
1405
|
+
for (const key of POSITIVE) {
|
|
1406
|
+
const v = resolved[key];
|
|
1407
|
+
if (!Number.isFinite(v) || v <= 0)
|
|
1408
|
+
throw new chunkVGAJJR3M_cjs.ConfigError(`logging.batch: ${key} must be a positive number`);
|
|
1409
|
+
}
|
|
1410
|
+
for (const key of NON_NEGATIVE) {
|
|
1411
|
+
const v = resolved[key];
|
|
1412
|
+
if (!Number.isFinite(v) || v < 0) throw new chunkVGAJJR3M_cjs.ConfigError(`logging.batch: ${key} must be >= 0`);
|
|
1413
|
+
}
|
|
1414
|
+
if (!["drop_newest", "drop_oldest", "block"].includes(resolved.dropPolicy)) {
|
|
1415
|
+
throw new chunkVGAJJR3M_cjs.ConfigError("logging.batch: dropPolicy must be drop_newest, drop_oldest or block");
|
|
1416
|
+
}
|
|
1417
|
+
return resolved;
|
|
1418
|
+
}
|
|
1419
|
+
function isRetryable(error) {
|
|
1420
|
+
return typeof error === "object" && error !== null && error.retryable === true;
|
|
1421
|
+
}
|
|
1422
|
+
var BatchProcessor = class {
|
|
1423
|
+
#exporter;
|
|
1424
|
+
#opts;
|
|
1425
|
+
#queue = [];
|
|
1426
|
+
#stop = new AbortController();
|
|
1427
|
+
#queuedBytes = 0;
|
|
1428
|
+
#inflight = 0;
|
|
1429
|
+
#enqueued = 0;
|
|
1430
|
+
#dequeued = 0;
|
|
1431
|
+
#forceUntil = 0;
|
|
1432
|
+
#sent = 0;
|
|
1433
|
+
#dropped = 0;
|
|
1434
|
+
#failed = 0;
|
|
1435
|
+
#retries = 0;
|
|
1436
|
+
#closed = false;
|
|
1437
|
+
#kickScheduled = false;
|
|
1438
|
+
#draining = null;
|
|
1439
|
+
#shutdown = null;
|
|
1440
|
+
#capacityWaiters = [];
|
|
1441
|
+
#timer;
|
|
1442
|
+
constructor(exporter, options = {}) {
|
|
1443
|
+
this.#exporter = exporter;
|
|
1444
|
+
this.#opts = resolveBatchOptions(options);
|
|
1445
|
+
this.#timer = setInterval(() => {
|
|
1446
|
+
this.#onTick();
|
|
1447
|
+
}, this.#opts.flushIntervalMs);
|
|
1448
|
+
this.#timer.unref();
|
|
1449
|
+
}
|
|
1450
|
+
/** The resolved options. */
|
|
1451
|
+
get options() {
|
|
1452
|
+
return this.#opts;
|
|
1453
|
+
}
|
|
1454
|
+
/** Enqueues a record. Returns false when it was dropped. Never blocks (see `dropPolicy`). */
|
|
1455
|
+
add(record) {
|
|
1456
|
+
if (this.#closed) {
|
|
1457
|
+
this.#drop([record], "shutdown");
|
|
1458
|
+
return false;
|
|
1459
|
+
}
|
|
1460
|
+
if (this.#queue.length >= this.#opts.maxQueueSize) {
|
|
1461
|
+
if (this.#opts.dropPolicy === "drop_newest") {
|
|
1462
|
+
this.#drop([record], "queue_full");
|
|
1463
|
+
return false;
|
|
1464
|
+
}
|
|
1465
|
+
if (this.#opts.dropPolicy === "drop_oldest") {
|
|
1466
|
+
const oldest = this.#queue.shift();
|
|
1467
|
+
this.#queuedBytes -= oldest.bytes;
|
|
1468
|
+
this.#dequeued += 1;
|
|
1469
|
+
this.#drop([oldest.record], "queue_full");
|
|
1470
|
+
} else {
|
|
1471
|
+
this.#forceUntil = Math.max(this.#forceUntil, this.#enqueued + 1);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
const bytes = chunkVGAJJR3M_cjs.logRecordByteSize(record);
|
|
1475
|
+
this.#queue.push({ record, bytes });
|
|
1476
|
+
this.#queuedBytes += bytes;
|
|
1477
|
+
this.#enqueued += 1;
|
|
1478
|
+
if (this.#queue.length >= this.#opts.maxBatchSize || this.#queuedBytes >= this.#opts.maxBatchBytes || this.#forceUntil > this.#dequeued) {
|
|
1479
|
+
this.#scheduleKick();
|
|
1480
|
+
}
|
|
1481
|
+
return true;
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* Like {@link add}, but with `dropPolicy: "block"` waits until the queue has room first.
|
|
1485
|
+
* Resolves false when the record was dropped (for example because the processor shut down).
|
|
1486
|
+
*/
|
|
1487
|
+
async addAsync(record) {
|
|
1488
|
+
while (this.#opts.dropPolicy === "block" && !this.#closed && this.#queue.length >= this.#opts.maxQueueSize) {
|
|
1489
|
+
this.#forceUntil = Math.max(this.#forceUntil, this.#enqueued);
|
|
1490
|
+
this.#scheduleKick();
|
|
1491
|
+
await new Promise((resolve) => this.#capacityWaiters.push(resolve));
|
|
1492
|
+
}
|
|
1493
|
+
return this.add(record);
|
|
1494
|
+
}
|
|
1495
|
+
/** Exports everything queued at the time of the call. Rejects with `TimeoutError` after `timeoutMs`. */
|
|
1496
|
+
async flush(timeoutMs = this.#opts.exportTimeoutMs) {
|
|
1497
|
+
if (this.#shutdown !== null) return this.#shutdown;
|
|
1498
|
+
await this.#withTimeout(this.#drainTo(this.#enqueued), timeoutMs, "logging.flush");
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* Drains the queue (bounded by `timeoutMs`), drops what is left with reason `shutdown`, then shuts
|
|
1502
|
+
* the exporter down. Idempotent; later {@link add} calls drop with reason `shutdown`.
|
|
1503
|
+
*/
|
|
1504
|
+
shutdown(timeoutMs = this.#opts.exportTimeoutMs) {
|
|
1505
|
+
this.#shutdown ??= this.#doShutdown(timeoutMs);
|
|
1506
|
+
return this.#shutdown;
|
|
1507
|
+
}
|
|
1508
|
+
/** Current counters. */
|
|
1509
|
+
stats() {
|
|
1510
|
+
return {
|
|
1511
|
+
queued: this.#queue.length + this.#inflight,
|
|
1512
|
+
sent: this.#sent,
|
|
1513
|
+
dropped: this.#dropped,
|
|
1514
|
+
failed: this.#failed,
|
|
1515
|
+
retries: this.#retries
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
async #doShutdown(timeoutMs) {
|
|
1519
|
+
this.#closed = true;
|
|
1520
|
+
clearInterval(this.#timer);
|
|
1521
|
+
this.#releaseWaiters();
|
|
1522
|
+
try {
|
|
1523
|
+
await this.#withTimeout(this.#drainTo(this.#enqueued), timeoutMs, "logging.shutdown");
|
|
1524
|
+
} catch {
|
|
1525
|
+
this.#stop.abort();
|
|
1526
|
+
}
|
|
1527
|
+
if (this.#queue.length > 0) {
|
|
1528
|
+
const rest = this.#queue.splice(0, this.#queue.length).map((e) => e.record);
|
|
1529
|
+
this.#dequeued += rest.length;
|
|
1530
|
+
this.#queuedBytes = 0;
|
|
1531
|
+
this.#drop(rest, "shutdown");
|
|
1532
|
+
}
|
|
1533
|
+
try {
|
|
1534
|
+
await this.#exporter.shutdown();
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
this.#notifyError(error, []);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
#onTick() {
|
|
1540
|
+
if (this.#queue.length === 0) return;
|
|
1541
|
+
this.#forceUntil = Math.max(this.#forceUntil, this.#enqueued);
|
|
1542
|
+
void this.#kick();
|
|
1543
|
+
}
|
|
1544
|
+
#scheduleKick() {
|
|
1545
|
+
if (this.#kickScheduled) return;
|
|
1546
|
+
this.#kickScheduled = true;
|
|
1547
|
+
queueMicrotask(() => {
|
|
1548
|
+
this.#kickScheduled = false;
|
|
1549
|
+
void this.#kick();
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
async #drainTo(target) {
|
|
1553
|
+
this.#forceUntil = Math.max(this.#forceUntil, target);
|
|
1554
|
+
while (!this.#stop.signal.aborted && (this.#dequeued < target && this.#queue.length > 0 || this.#inflight > 0)) {
|
|
1555
|
+
await this.#kick();
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
#kick() {
|
|
1559
|
+
this.#draining ??= this.#drainLoop().finally(() => {
|
|
1560
|
+
this.#draining = null;
|
|
1561
|
+
});
|
|
1562
|
+
return this.#draining;
|
|
1563
|
+
}
|
|
1564
|
+
async #drainLoop() {
|
|
1565
|
+
while (this.#queue.length > 0 && !this.#stop.signal.aborted) {
|
|
1566
|
+
const full = this.#queue.length >= this.#opts.maxBatchSize || this.#queuedBytes >= this.#opts.maxBatchBytes;
|
|
1567
|
+
if (!full && this.#forceUntil <= this.#dequeued) break;
|
|
1568
|
+
await this.#exportBatch(this.#takeBatch());
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
#takeBatch() {
|
|
1572
|
+
let count = 0;
|
|
1573
|
+
let bytes = 2;
|
|
1574
|
+
for (const entry of this.#queue) {
|
|
1575
|
+
if (count >= this.#opts.maxBatchSize) break;
|
|
1576
|
+
const next = bytes + entry.bytes + (count > 0 ? 1 : 0);
|
|
1577
|
+
if (count > 0 && next > this.#opts.maxBatchBytes) break;
|
|
1578
|
+
bytes = next;
|
|
1579
|
+
count += 1;
|
|
1580
|
+
}
|
|
1581
|
+
const taken = this.#queue.splice(0, count);
|
|
1582
|
+
for (const e of taken) this.#queuedBytes -= e.bytes;
|
|
1583
|
+
this.#dequeued += count;
|
|
1584
|
+
this.#inflight += count;
|
|
1585
|
+
this.#releaseWaiters();
|
|
1586
|
+
return taken.map((e) => e.record);
|
|
1587
|
+
}
|
|
1588
|
+
async #exportBatch(records) {
|
|
1589
|
+
try {
|
|
1590
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1591
|
+
let result;
|
|
1592
|
+
try {
|
|
1593
|
+
result = await this.#exportOnce(records);
|
|
1594
|
+
} catch (error) {
|
|
1595
|
+
if (await this.#shouldRetry(error, attempt)) continue;
|
|
1596
|
+
this.#fail(records, error);
|
|
1597
|
+
return;
|
|
1598
|
+
}
|
|
1599
|
+
const accepted = Math.min(records.length, Math.max(0, Math.trunc(result.accepted)));
|
|
1600
|
+
if (accepted === 0 && result.error !== void 0 && await this.#shouldRetry(result.error, attempt)) {
|
|
1601
|
+
continue;
|
|
1602
|
+
}
|
|
1603
|
+
this.#sent += accepted;
|
|
1604
|
+
const failed = records.length - accepted;
|
|
1605
|
+
if (accepted === 0) {
|
|
1606
|
+
this.#fail(
|
|
1607
|
+
records,
|
|
1608
|
+
result.error ?? new Error("logging.export: the service accepted no records")
|
|
1609
|
+
);
|
|
1610
|
+
} else if (failed > 0) {
|
|
1611
|
+
this.#failed += failed;
|
|
1612
|
+
this.#notifyError(
|
|
1613
|
+
result.error ?? new Error(`logging.export: ${failed} records rejected`),
|
|
1614
|
+
records
|
|
1615
|
+
);
|
|
1616
|
+
}
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
} finally {
|
|
1620
|
+
this.#inflight -= records.length;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
async #shouldRetry(error, attempt) {
|
|
1624
|
+
if (!isRetryable(error) || attempt >= this.#opts.maxExportRetries || this.#stop.signal.aborted)
|
|
1625
|
+
return false;
|
|
1626
|
+
this.#retries += 1;
|
|
1627
|
+
await this.#sleep(this.#opts.retryBackoffMs * 2 ** attempt);
|
|
1628
|
+
return !this.#stop.signal.aborted;
|
|
1629
|
+
}
|
|
1630
|
+
#exportOnce(records) {
|
|
1631
|
+
const timeoutMs = this.#opts.exportTimeoutMs;
|
|
1632
|
+
const controller = new AbortController();
|
|
1633
|
+
const onStop = () => {
|
|
1634
|
+
controller.abort(this.#stop.signal.reason);
|
|
1635
|
+
};
|
|
1636
|
+
this.#stop.signal.addEventListener("abort", onStop, { once: true });
|
|
1637
|
+
let timer;
|
|
1638
|
+
const timeout = new Promise((_, reject) => {
|
|
1639
|
+
timer = setTimeout(() => {
|
|
1640
|
+
const error = new chunkVGAJJR3M_cjs.TimeoutError(`logging.export: timed out after ${timeoutMs} ms`);
|
|
1641
|
+
controller.abort(error);
|
|
1642
|
+
reject(error);
|
|
1643
|
+
}, timeoutMs);
|
|
1644
|
+
timer.unref();
|
|
1645
|
+
});
|
|
1646
|
+
const run = Promise.resolve().then(
|
|
1647
|
+
() => this.#exporter.export(records, { signal: controller.signal, gzip: this.#opts.gzip })
|
|
1648
|
+
);
|
|
1649
|
+
return Promise.race([run, timeout]).finally(() => {
|
|
1650
|
+
clearTimeout(timer);
|
|
1651
|
+
this.#stop.signal.removeEventListener("abort", onStop);
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
#sleep(ms) {
|
|
1655
|
+
return new Promise((resolve) => {
|
|
1656
|
+
const done = () => {
|
|
1657
|
+
clearTimeout(timer);
|
|
1658
|
+
this.#stop.signal.removeEventListener("abort", done);
|
|
1659
|
+
resolve();
|
|
1660
|
+
};
|
|
1661
|
+
const timer = setTimeout(done, ms);
|
|
1662
|
+
timer.unref();
|
|
1663
|
+
this.#stop.signal.addEventListener("abort", done, { once: true });
|
|
1664
|
+
});
|
|
1665
|
+
}
|
|
1666
|
+
async #withTimeout(work, timeoutMs, operation) {
|
|
1667
|
+
let timer;
|
|
1668
|
+
const timeout = new Promise((_, reject) => {
|
|
1669
|
+
timer = setTimeout(() => {
|
|
1670
|
+
reject(new chunkVGAJJR3M_cjs.TimeoutError(`${operation}: timed out after ${timeoutMs} ms`));
|
|
1671
|
+
}, timeoutMs);
|
|
1672
|
+
timer.unref();
|
|
1673
|
+
});
|
|
1674
|
+
try {
|
|
1675
|
+
await Promise.race([work, timeout]);
|
|
1676
|
+
} finally {
|
|
1677
|
+
clearTimeout(timer);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
#releaseWaiters() {
|
|
1681
|
+
if (this.#capacityWaiters.length === 0) return;
|
|
1682
|
+
if (!this.#closed && this.#queue.length >= this.#opts.maxQueueSize) return;
|
|
1683
|
+
const waiters = this.#capacityWaiters;
|
|
1684
|
+
this.#capacityWaiters = [];
|
|
1685
|
+
for (const resolve of waiters) resolve();
|
|
1686
|
+
}
|
|
1687
|
+
#fail(records, error) {
|
|
1688
|
+
this.#failed += records.length;
|
|
1689
|
+
this.#notifyError(error, records);
|
|
1690
|
+
this.#notifyDrop(records, "export_failed");
|
|
1691
|
+
}
|
|
1692
|
+
#drop(records, reason) {
|
|
1693
|
+
this.#dropped += records.length;
|
|
1694
|
+
this.#notifyDrop(records, reason);
|
|
1695
|
+
}
|
|
1696
|
+
#notifyDrop(records, reason) {
|
|
1697
|
+
try {
|
|
1698
|
+
this.#opts.onDrop?.(records, reason);
|
|
1699
|
+
} catch {
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
#notifyError(error, records) {
|
|
1703
|
+
try {
|
|
1704
|
+
this.#opts.onError?.(error, records);
|
|
1705
|
+
} catch {
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
};
|
|
1709
|
+
var Logger = class _Logger {
|
|
1710
|
+
#sink;
|
|
1711
|
+
#attributes;
|
|
1712
|
+
#minSeverity;
|
|
1713
|
+
#name;
|
|
1714
|
+
constructor(sink, options = {}) {
|
|
1715
|
+
this.#sink = sink;
|
|
1716
|
+
this.#name = options.name;
|
|
1717
|
+
this.#minSeverity = options.minSeverity ?? 9 /* Info */;
|
|
1718
|
+
this.#attributes = {
|
|
1719
|
+
...options.name !== void 0 ? { "logger.name": options.name } : {},
|
|
1720
|
+
...options.attributes
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
/** The logger name, when set. */
|
|
1724
|
+
get name() {
|
|
1725
|
+
return this.#name;
|
|
1726
|
+
}
|
|
1727
|
+
/** The minimum severity this logger sends. */
|
|
1728
|
+
get minSeverity() {
|
|
1729
|
+
return this.#minSeverity;
|
|
1730
|
+
}
|
|
1731
|
+
/** Whether a record of `severity` would be sent. */
|
|
1732
|
+
isEnabled(severity) {
|
|
1733
|
+
return severity >= this.#minSeverity;
|
|
1734
|
+
}
|
|
1735
|
+
trace(message, attributes) {
|
|
1736
|
+
this.log(1 /* Trace */, message, attributes);
|
|
1737
|
+
}
|
|
1738
|
+
debug(message, attributes) {
|
|
1739
|
+
this.log(5 /* Debug */, message, attributes);
|
|
1740
|
+
}
|
|
1741
|
+
info(message, attributes) {
|
|
1742
|
+
this.log(9 /* Info */, message, attributes);
|
|
1743
|
+
}
|
|
1744
|
+
warn(message, attributes) {
|
|
1745
|
+
this.log(13 /* Warn */, message, attributes);
|
|
1746
|
+
}
|
|
1747
|
+
error(message, attributes) {
|
|
1748
|
+
this.log(17 /* Error */, message, attributes);
|
|
1749
|
+
}
|
|
1750
|
+
fatal(message, attributes) {
|
|
1751
|
+
this.log(21 /* Fatal */, message, attributes);
|
|
1752
|
+
}
|
|
1753
|
+
/** Sends one record at `severity` (if enabled). */
|
|
1754
|
+
log(severity, message, attributes) {
|
|
1755
|
+
if (!this.isEnabled(severity)) return;
|
|
1756
|
+
const input = {
|
|
1757
|
+
message,
|
|
1758
|
+
severity,
|
|
1759
|
+
attributes: { ...this.#attributes, ...attributes }
|
|
1760
|
+
};
|
|
1761
|
+
const span = api.trace.getSpan(api.context.active());
|
|
1762
|
+
if (span !== void 0) {
|
|
1763
|
+
const ctx = span.spanContext();
|
|
1764
|
+
if (api.isSpanContextValid(ctx)) {
|
|
1765
|
+
input.traceId = ctx.traceId;
|
|
1766
|
+
input.spanId = ctx.spanId;
|
|
1767
|
+
input.traceFlags = ctx.traceFlags;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
this.#sink.send(input);
|
|
1771
|
+
}
|
|
1772
|
+
/** A logger with extra attributes (same sink, name and minimum severity). */
|
|
1773
|
+
child(attributes) {
|
|
1774
|
+
const options = {
|
|
1775
|
+
minSeverity: this.#minSeverity,
|
|
1776
|
+
attributes: { ...this.#attributes, ...attributes }
|
|
1777
|
+
};
|
|
1778
|
+
if (this.#name !== void 0) options.name = this.#name;
|
|
1779
|
+
return new _Logger(this.#sink, options);
|
|
1780
|
+
}
|
|
1781
|
+
};
|
|
1782
|
+
|
|
1783
|
+
// src/logging/client.ts
|
|
1784
|
+
function isLogRecord(input) {
|
|
1785
|
+
return "body" in input && typeof input.body === "string";
|
|
1786
|
+
}
|
|
1787
|
+
var BatchingLogClient = class {
|
|
1788
|
+
#processor;
|
|
1789
|
+
#resource;
|
|
1790
|
+
#redaction;
|
|
1791
|
+
#minSeverity;
|
|
1792
|
+
#now;
|
|
1793
|
+
#closing = null;
|
|
1794
|
+
constructor(exporter, options = {}) {
|
|
1795
|
+
this.#processor = new BatchProcessor(exporter, options.batch);
|
|
1796
|
+
this.#resource = chunkVGAJJR3M_cjs.toAttributes(options.resource ?? {});
|
|
1797
|
+
const redaction = options.redaction ?? {};
|
|
1798
|
+
this.#redaction = redaction === false ? null : redaction instanceof RedactionProcessor ? redaction : new RedactionProcessor(redaction);
|
|
1799
|
+
this.#minSeverity = options.minSeverity ?? 9 /* Info */;
|
|
1800
|
+
this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
1801
|
+
}
|
|
1802
|
+
/** The underlying processor. */
|
|
1803
|
+
get processor() {
|
|
1804
|
+
return this.#processor;
|
|
1805
|
+
}
|
|
1806
|
+
/** The resource attributes added to every record. */
|
|
1807
|
+
get resource() {
|
|
1808
|
+
return this.#resource;
|
|
1809
|
+
}
|
|
1810
|
+
send(record) {
|
|
1811
|
+
try {
|
|
1812
|
+
this.#processor.add(this.#prepare(record));
|
|
1813
|
+
} catch {
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
sendBatch(records) {
|
|
1817
|
+
for (const record of records) this.send(record);
|
|
1818
|
+
}
|
|
1819
|
+
flush(timeoutMs) {
|
|
1820
|
+
return this.#processor.flush(timeoutMs);
|
|
1821
|
+
}
|
|
1822
|
+
close() {
|
|
1823
|
+
this.#closing ??= this.#processor.shutdown();
|
|
1824
|
+
return this.#closing;
|
|
1825
|
+
}
|
|
1826
|
+
stats() {
|
|
1827
|
+
return this.#processor.stats();
|
|
1828
|
+
}
|
|
1829
|
+
logger(name, attributes) {
|
|
1830
|
+
const options = { minSeverity: this.#minSeverity };
|
|
1831
|
+
if (name !== void 0) options.name = name;
|
|
1832
|
+
if (attributes !== void 0) options.attributes = attributes;
|
|
1833
|
+
return new Logger(this, options);
|
|
1834
|
+
}
|
|
1835
|
+
/** Applies defaults, resource, id normalization and redaction. */
|
|
1836
|
+
#prepare(input) {
|
|
1837
|
+
const now = this.#now();
|
|
1838
|
+
let record;
|
|
1839
|
+
if (isLogRecord(input)) {
|
|
1840
|
+
record = {
|
|
1841
|
+
...input,
|
|
1842
|
+
attributes: chunkVGAJJR3M_cjs.toAttributes(input.attributes),
|
|
1843
|
+
resource: { ...this.#resource, ...chunkVGAJJR3M_cjs.toAttributes(input.resource) }
|
|
1844
|
+
};
|
|
1845
|
+
record.observedTimestamp ??= now;
|
|
1846
|
+
} else {
|
|
1847
|
+
const severity = input.severity ?? 9 /* Info */;
|
|
1848
|
+
record = {
|
|
1849
|
+
timestamp: input.timestamp ?? now,
|
|
1850
|
+
observedTimestamp: now,
|
|
1851
|
+
severity,
|
|
1852
|
+
severityText: chunkVGAJJR3M_cjs.severityText(severity),
|
|
1853
|
+
body: input.message,
|
|
1854
|
+
attributes: chunkVGAJJR3M_cjs.toAttributes(input.attributes ?? {}),
|
|
1855
|
+
resource: { ...this.#resource }
|
|
1856
|
+
};
|
|
1857
|
+
if (input.traceId !== void 0) record.traceId = input.traceId;
|
|
1858
|
+
if (input.spanId !== void 0) record.spanId = input.spanId;
|
|
1859
|
+
if (input.traceFlags !== void 0) record.traceFlags = input.traceFlags;
|
|
1860
|
+
}
|
|
1861
|
+
const traceId = chunkVGAJJR3M_cjs.normalizeHexId(record.traceId, 32);
|
|
1862
|
+
const spanId = traceId === void 0 ? void 0 : chunkVGAJJR3M_cjs.normalizeHexId(record.spanId, 16);
|
|
1863
|
+
delete record.traceId;
|
|
1864
|
+
delete record.spanId;
|
|
1865
|
+
if (traceId === void 0) delete record.traceFlags;
|
|
1866
|
+
else record.traceId = traceId;
|
|
1867
|
+
if (spanId !== void 0) record.spanId = spanId;
|
|
1868
|
+
return this.#redaction === null ? record : this.#redaction.process(record);
|
|
1869
|
+
}
|
|
1870
|
+
};
|
|
1871
|
+
function pinoLevelToSeverity(level) {
|
|
1872
|
+
if (typeof level === "number") {
|
|
1873
|
+
if (level < 20) return 1 /* Trace */;
|
|
1874
|
+
if (level < 30) return 5 /* Debug */;
|
|
1875
|
+
if (level < 40) return 9 /* Info */;
|
|
1876
|
+
if (level < 50) return 13 /* Warn */;
|
|
1877
|
+
if (level < 60) return 17 /* Error */;
|
|
1878
|
+
return 21 /* Fatal */;
|
|
1879
|
+
}
|
|
1880
|
+
return typeof level === "string" ? chunkVGAJJR3M_cjs.parseSeverity(level) ?? 9 /* Info */ : 9 /* Info */;
|
|
1881
|
+
}
|
|
1882
|
+
function pinoLineToRecord(line, opts = {}) {
|
|
1883
|
+
const consumed = /* @__PURE__ */ new Set();
|
|
1884
|
+
const pick = (...keys) => {
|
|
1885
|
+
for (const key of keys) {
|
|
1886
|
+
if (key in line) {
|
|
1887
|
+
consumed.add(key);
|
|
1888
|
+
return line[key];
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
return void 0;
|
|
1892
|
+
};
|
|
1893
|
+
const level = pick("level");
|
|
1894
|
+
const time = pick("time");
|
|
1895
|
+
const message = pick(opts.messageKey ?? "msg");
|
|
1896
|
+
const hostname = pick("hostname");
|
|
1897
|
+
const pid = pick("pid");
|
|
1898
|
+
const traceId = pick("trace_id", "traceId");
|
|
1899
|
+
const spanId = pick("span_id", "spanId");
|
|
1900
|
+
const traceFlags = pick("trace_flags", "traceFlags");
|
|
1901
|
+
const rest = Object.fromEntries(Object.entries(line).filter(([k]) => !consumed.has(k)));
|
|
1902
|
+
const severity = pinoLevelToSeverity(level);
|
|
1903
|
+
const timestamp = typeof time === "number" || typeof time === "string" ? new Date(time) : /* @__PURE__ */ new Date();
|
|
1904
|
+
const resource = {};
|
|
1905
|
+
if (typeof hostname === "string") resource["host.name"] = hostname;
|
|
1906
|
+
if (typeof pid === "number") resource["process.pid"] = pid;
|
|
1907
|
+
const record = {
|
|
1908
|
+
timestamp: Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp,
|
|
1909
|
+
severity,
|
|
1910
|
+
severityText: typeof level === "string" ? level.toUpperCase() : chunkVGAJJR3M_cjs.severityText(severity),
|
|
1911
|
+
body: typeof message === "string" ? message : message === void 0 ? "" : JSON.stringify(message),
|
|
1912
|
+
attributes: { ...opts.attributes, ...chunkVGAJJR3M_cjs.toAttributes(rest) },
|
|
1913
|
+
resource
|
|
1914
|
+
};
|
|
1915
|
+
if (typeof traceId === "string") record.traceId = traceId;
|
|
1916
|
+
if (typeof spanId === "string") record.spanId = spanId;
|
|
1917
|
+
if (typeof traceFlags === "number") record.traceFlags = traceFlags;
|
|
1918
|
+
else if (typeof traceFlags === "string" && /^[0-9a-f]{1,2}$/i.test(traceFlags)) {
|
|
1919
|
+
record.traceFlags = parseInt(traceFlags, 16);
|
|
1920
|
+
}
|
|
1921
|
+
return record;
|
|
1922
|
+
}
|
|
1923
|
+
function createPinoTransport(client, opts = {}) {
|
|
1924
|
+
let pending = "";
|
|
1925
|
+
const handleLine = (line) => {
|
|
1926
|
+
if (line.trim() === "") return;
|
|
1927
|
+
let parsed;
|
|
1928
|
+
try {
|
|
1929
|
+
parsed = JSON.parse(line);
|
|
1930
|
+
} catch {
|
|
1931
|
+
parsed = void 0;
|
|
1932
|
+
}
|
|
1933
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
1934
|
+
client.send(pinoLineToRecord(parsed, opts));
|
|
1935
|
+
} else {
|
|
1936
|
+
client.send({ message: line, severity: 9 /* Info */, attributes: { ...opts.attributes } });
|
|
1937
|
+
}
|
|
1938
|
+
};
|
|
1939
|
+
return new stream.Writable({
|
|
1940
|
+
decodeStrings: false,
|
|
1941
|
+
write(chunk, _encoding, callback) {
|
|
1942
|
+
pending += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
|
|
1943
|
+
let index = pending.indexOf("\n");
|
|
1944
|
+
while (index >= 0) {
|
|
1945
|
+
handleLine(pending.slice(0, index));
|
|
1946
|
+
pending = pending.slice(index + 1);
|
|
1947
|
+
index = pending.indexOf("\n");
|
|
1948
|
+
}
|
|
1949
|
+
callback();
|
|
1950
|
+
},
|
|
1951
|
+
final(callback) {
|
|
1952
|
+
handleLine(pending);
|
|
1953
|
+
pending = "";
|
|
1954
|
+
if (opts.flushOnEnd === false) {
|
|
1955
|
+
callback();
|
|
1956
|
+
return;
|
|
1957
|
+
}
|
|
1958
|
+
client.flush().then(
|
|
1959
|
+
() => {
|
|
1960
|
+
callback();
|
|
1961
|
+
},
|
|
1962
|
+
() => {
|
|
1963
|
+
callback();
|
|
1964
|
+
}
|
|
1965
|
+
);
|
|
1966
|
+
}
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
var LEVEL = /* @__PURE__ */ Symbol.for("level");
|
|
1970
|
+
var WINSTON_LEVELS = {
|
|
1971
|
+
silly: 1 /* Trace */,
|
|
1972
|
+
verbose: 5 /* Debug */,
|
|
1973
|
+
http: 9 /* Info */,
|
|
1974
|
+
emerg: 21 /* Fatal */,
|
|
1975
|
+
alert: 21 /* Fatal */,
|
|
1976
|
+
crit: 21 /* Fatal */
|
|
1977
|
+
};
|
|
1978
|
+
function winstonLevelToSeverity(level) {
|
|
1979
|
+
const lower = level.toLowerCase();
|
|
1980
|
+
return WINSTON_LEVELS[lower] ?? chunkVGAJJR3M_cjs.parseSeverity(lower) ?? 9 /* Info */;
|
|
1981
|
+
}
|
|
1982
|
+
var WinstonTransport = class extends stream.Writable {
|
|
1983
|
+
#client;
|
|
1984
|
+
#attributes;
|
|
1985
|
+
/** Level filter (same meaning as winston-transport's `level`). */
|
|
1986
|
+
level;
|
|
1987
|
+
/** Level table, set by winston when the logger pipes into this transport. */
|
|
1988
|
+
levels;
|
|
1989
|
+
constructor(client, opts = {}) {
|
|
1990
|
+
super({ objectMode: true });
|
|
1991
|
+
this.#client = client;
|
|
1992
|
+
this.#attributes = opts.attributes ?? {};
|
|
1993
|
+
this.level = opts.level;
|
|
1994
|
+
this.on("pipe", (source) => {
|
|
1995
|
+
this.levels ??= source.levels;
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
/** Converts a winston info object into a {@link LogRecord}. */
|
|
1999
|
+
toRecord(info) {
|
|
2000
|
+
const rawLevel = typeof info[LEVEL] === "string" ? info[LEVEL] : info.level;
|
|
2001
|
+
const severity = winstonLevelToSeverity(rawLevel);
|
|
2002
|
+
const { level: _level, message, timestamp, ...rest } = info;
|
|
2003
|
+
const time = typeof timestamp === "string" || typeof timestamp === "number" ? new Date(timestamp) : /* @__PURE__ */ new Date();
|
|
2004
|
+
return {
|
|
2005
|
+
timestamp: Number.isNaN(time.getTime()) ? /* @__PURE__ */ new Date() : time,
|
|
2006
|
+
severity,
|
|
2007
|
+
severityText: rawLevel.toUpperCase(),
|
|
2008
|
+
body: typeof message === "string" ? message : message === void 0 ? "" : JSON.stringify(message),
|
|
2009
|
+
attributes: { ...this.#attributes, ...chunkVGAJJR3M_cjs.toAttributes(rest) },
|
|
2010
|
+
resource: {}
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
/** Winston-compatible entry point. */
|
|
2014
|
+
log(info, callback) {
|
|
2015
|
+
if (this.#accepts(info)) this.#client.send(this.toRecord(info));
|
|
2016
|
+
callback?.();
|
|
2017
|
+
}
|
|
2018
|
+
_write(info, _encoding, callback) {
|
|
2019
|
+
this.log(info, () => {
|
|
2020
|
+
callback();
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
_final(callback) {
|
|
2024
|
+
this.#client.flush().then(
|
|
2025
|
+
() => {
|
|
2026
|
+
callback();
|
|
2027
|
+
},
|
|
2028
|
+
() => {
|
|
2029
|
+
callback();
|
|
2030
|
+
}
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
2033
|
+
/** Called by winston when the transport is removed or the logger closes. */
|
|
2034
|
+
close() {
|
|
2035
|
+
void this.#client.flush().catch(() => void 0);
|
|
2036
|
+
}
|
|
2037
|
+
#accepts(info) {
|
|
2038
|
+
if (this.level === void 0 || this.levels === void 0) return true;
|
|
2039
|
+
const max = this.levels[this.level];
|
|
2040
|
+
const current = this.levels[info.level];
|
|
2041
|
+
return max === void 0 || current === void 0 || current <= max;
|
|
2042
|
+
}
|
|
2043
|
+
};
|
|
2044
|
+
|
|
2045
|
+
// src/time.ts
|
|
2046
|
+
var NS_PER_MS = 1000000n;
|
|
2047
|
+
var DIGITS = /^\d+$/;
|
|
2048
|
+
function dateToNanos(date) {
|
|
2049
|
+
const ms = date.getTime();
|
|
2050
|
+
if (!Number.isFinite(ms)) throw new chunkVGAJJR3M_cjs.ValidationError("invalid date");
|
|
2051
|
+
return (BigInt(ms) * NS_PER_MS).toString();
|
|
2052
|
+
}
|
|
2053
|
+
function nanosToDate(ns) {
|
|
2054
|
+
const value = typeof ns === "bigint" ? ns : BigInt(ns);
|
|
2055
|
+
return new Date(Number(value / NS_PER_MS));
|
|
2056
|
+
}
|
|
2057
|
+
function toNanos(value, field = "time") {
|
|
2058
|
+
if (value instanceof Date) {
|
|
2059
|
+
if (Number.isNaN(value.getTime())) throw new chunkVGAJJR3M_cjs.ValidationError(`${field}: invalid date`);
|
|
2060
|
+
return dateToNanos(value);
|
|
2061
|
+
}
|
|
2062
|
+
if (typeof value === "bigint") {
|
|
2063
|
+
if (value < 0n) throw new chunkVGAJJR3M_cjs.ValidationError(`${field}: must not be negative`);
|
|
2064
|
+
return value.toString();
|
|
2065
|
+
}
|
|
2066
|
+
const text = value.trim();
|
|
2067
|
+
if (DIGITS.test(text)) return text;
|
|
2068
|
+
const parsed = Date.parse(text);
|
|
2069
|
+
if (text === "" || Number.isNaN(parsed)) {
|
|
2070
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${field}: expected a Date, bigint nanoseconds or RFC 3339 text`);
|
|
2071
|
+
}
|
|
2072
|
+
return dateToNanos(new Date(parsed));
|
|
2073
|
+
}
|
|
2074
|
+
function optionalNanos(value, field) {
|
|
2075
|
+
return value === void 0 ? void 0 : toNanos(value, field);
|
|
2076
|
+
}
|
|
2077
|
+
function secondsToDate(seconds) {
|
|
2078
|
+
return new Date(Math.round(seconds * 1e3));
|
|
2079
|
+
}
|
|
2080
|
+
function msToDuration(ms, field) {
|
|
2081
|
+
if (!Number.isFinite(ms) || ms <= 0) {
|
|
2082
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${field}: must be a positive number of milliseconds`);
|
|
2083
|
+
}
|
|
2084
|
+
return `${Math.round(ms)}ms`;
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
// src/labels.ts
|
|
2088
|
+
var LABEL_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
2089
|
+
var DEFAULT_ALLOWED_LABELS = Object.freeze([
|
|
2090
|
+
"service_name",
|
|
2091
|
+
"service_namespace",
|
|
2092
|
+
"deployment_environment",
|
|
2093
|
+
"host_name",
|
|
2094
|
+
"level",
|
|
2095
|
+
"job",
|
|
2096
|
+
"instance",
|
|
2097
|
+
"namespace",
|
|
2098
|
+
"pod",
|
|
2099
|
+
"container"
|
|
2100
|
+
]);
|
|
2101
|
+
var RESERVED_METADATA_KEYS = Object.freeze([
|
|
2102
|
+
"severity_text",
|
|
2103
|
+
"severity_number",
|
|
2104
|
+
"trace_id",
|
|
2105
|
+
"span_id",
|
|
2106
|
+
"trace_flags"
|
|
2107
|
+
]);
|
|
2108
|
+
function isValidLabelName(name) {
|
|
2109
|
+
return LABEL_NAME_PATTERN.test(name) && !name.startsWith("__");
|
|
2110
|
+
}
|
|
2111
|
+
function validateLabelName(name, what = "label name") {
|
|
2112
|
+
if (!LABEL_NAME_PATTERN.test(name)) {
|
|
2113
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(
|
|
2114
|
+
`invalid ${what} ${JSON.stringify(name)}: must match [a-zA-Z_][a-zA-Z0-9_]*`
|
|
2115
|
+
);
|
|
2116
|
+
}
|
|
2117
|
+
if (name.startsWith("__")) {
|
|
2118
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`invalid ${what} ${JSON.stringify(name)}: "__" names are reserved`);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
function validateLabels(labels) {
|
|
2122
|
+
for (const [name, value] of Object.entries(labels)) {
|
|
2123
|
+
validateLabelName(name);
|
|
2124
|
+
if (typeof value !== "string" || value === "") {
|
|
2125
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`label ${name}: value must be a non-empty string`);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
function normalizeLabelName(key) {
|
|
2130
|
+
const replaced = key.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
2131
|
+
if (replaced === "") return "_";
|
|
2132
|
+
return /^[0-9]/.test(replaced) ? `_${replaced}` : replaced;
|
|
2133
|
+
}
|
|
2134
|
+
function formatLabelSet(labels) {
|
|
2135
|
+
const parts = Object.keys(labels).sort().map((k) => `${k}=${JSON.stringify(labels[k])}`);
|
|
2136
|
+
return `{${parts.join(", ")}}`;
|
|
2137
|
+
}
|
|
2138
|
+
function attrToString(value) {
|
|
2139
|
+
if (typeof value === "string") return value;
|
|
2140
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
2141
|
+
return JSON.stringify(value);
|
|
2142
|
+
}
|
|
2143
|
+
var CardinalityGuard = class {
|
|
2144
|
+
#allowed;
|
|
2145
|
+
/** A guard for `allowed` (default {@link DEFAULT_ALLOWED_LABELS}). */
|
|
2146
|
+
constructor(allowed = DEFAULT_ALLOWED_LABELS) {
|
|
2147
|
+
this.#allowed = new Set(allowed);
|
|
2148
|
+
}
|
|
2149
|
+
/** The allowlist, sorted. */
|
|
2150
|
+
get allowed() {
|
|
2151
|
+
return [...this.#allowed].sort();
|
|
2152
|
+
}
|
|
2153
|
+
/** Whether `name` may be an index label. */
|
|
2154
|
+
isAllowed(name) {
|
|
2155
|
+
return this.#allowed.has(name);
|
|
2156
|
+
}
|
|
2157
|
+
/** A copy of `stream` whose labels outside the allowlist are moved to every entry's metadata. */
|
|
2158
|
+
apply(stream) {
|
|
2159
|
+
const labels = {};
|
|
2160
|
+
const moved = {};
|
|
2161
|
+
for (const [k, v] of Object.entries(stream.labels)) {
|
|
2162
|
+
if (this.#allowed.has(k)) labels[k] = v;
|
|
2163
|
+
else moved[k] = v;
|
|
2164
|
+
}
|
|
2165
|
+
if (Object.keys(moved).length === 0) return { labels, entries: stream.entries };
|
|
2166
|
+
return {
|
|
2167
|
+
labels,
|
|
2168
|
+
entries: stream.entries.map((e) => ({
|
|
2169
|
+
...e,
|
|
2170
|
+
structuredMetadata: { ...moved, ...e.structuredMetadata ?? {} }
|
|
2171
|
+
}))
|
|
2172
|
+
};
|
|
2173
|
+
}
|
|
2174
|
+
};
|
|
2175
|
+
function isScalar(value) {
|
|
2176
|
+
return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
2177
|
+
}
|
|
2178
|
+
function recordsToStreams(records, options = {}) {
|
|
2179
|
+
const allowed = new Set(options.allowedLabels ?? DEFAULT_ALLOWED_LABELS);
|
|
2180
|
+
const streams = /* @__PURE__ */ new Map();
|
|
2181
|
+
for (const record of records) {
|
|
2182
|
+
const labels = {};
|
|
2183
|
+
const metadata = {};
|
|
2184
|
+
const place = (key2, value) => {
|
|
2185
|
+
const name = normalizeLabelName(key2);
|
|
2186
|
+
if (allowed.has(name) && isValidLabelName(name) && isScalar(value) && String(value) !== "") {
|
|
2187
|
+
labels[name] = String(value);
|
|
2188
|
+
} else {
|
|
2189
|
+
metadata[name] = attrToString(value);
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
for (const [k, v] of Object.entries(record.resource)) place(k, v);
|
|
2193
|
+
for (const [k, v] of Object.entries(record.attributes)) place(k, v);
|
|
2194
|
+
const text = record.severityText !== "" ? record.severityText : chunkVGAJJR3M_cjs.severityText(record.severity);
|
|
2195
|
+
if (allowed.has("level") && labels.level === void 0) labels.level = text.toLowerCase();
|
|
2196
|
+
metadata.severity_text = text;
|
|
2197
|
+
metadata.severity_number = String(record.severity);
|
|
2198
|
+
if (record.traceId !== void 0) {
|
|
2199
|
+
metadata.trace_id = record.traceId;
|
|
2200
|
+
if (record.spanId !== void 0) metadata.span_id = record.spanId;
|
|
2201
|
+
if (record.traceFlags !== void 0) metadata.trace_flags = String(record.traceFlags);
|
|
2202
|
+
}
|
|
2203
|
+
const key = formatLabelSet(labels);
|
|
2204
|
+
let stream = streams.get(key);
|
|
2205
|
+
if (stream === void 0) {
|
|
2206
|
+
stream = { labels, entries: [] };
|
|
2207
|
+
streams.set(key, stream);
|
|
2208
|
+
}
|
|
2209
|
+
stream.entries.push({
|
|
2210
|
+
timestamp: dateToNanos(record.timestamp),
|
|
2211
|
+
line: record.body,
|
|
2212
|
+
structuredMetadata: metadata
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
return [...streams.values()];
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
// src/exporter.ts
|
|
2219
|
+
var SKIP_LABEL_GUARD = /* @__PURE__ */ Symbol("grow.loki.skipLabelGuard");
|
|
2220
|
+
async function exportWith(records, send) {
|
|
2221
|
+
if (records.length === 0) return { accepted: 0, rejected: 0 };
|
|
2222
|
+
try {
|
|
2223
|
+
await send();
|
|
2224
|
+
return { accepted: records.length, rejected: 0 };
|
|
2225
|
+
} catch (error) {
|
|
2226
|
+
if (error instanceof chunkVGAJJR3M_cjs.LokiError) return { accepted: 0, rejected: records.length, error };
|
|
2227
|
+
throw error;
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
var LokiLogExporter = class {
|
|
2231
|
+
#pusher;
|
|
2232
|
+
#options;
|
|
2233
|
+
constructor(pusher, options = {}) {
|
|
2234
|
+
this.#pusher = pusher;
|
|
2235
|
+
this.#options = options;
|
|
2236
|
+
}
|
|
2237
|
+
export(records, opts) {
|
|
2238
|
+
return exportWith(
|
|
2239
|
+
records,
|
|
2240
|
+
() => this.#pusher.push(recordsToStreams(records, this.#options), {
|
|
2241
|
+
format: this.#options.format ?? "json",
|
|
2242
|
+
gzip: opts.gzip,
|
|
2243
|
+
[SKIP_LABEL_GUARD]: true,
|
|
2244
|
+
...opts.signal === void 0 ? {} : { signal: opts.signal }
|
|
2245
|
+
})
|
|
2246
|
+
);
|
|
2247
|
+
}
|
|
2248
|
+
shutdown() {
|
|
2249
|
+
return Promise.resolve();
|
|
2250
|
+
}
|
|
2251
|
+
};
|
|
2252
|
+
var LokiOtlpExporter = class {
|
|
2253
|
+
#pusher;
|
|
2254
|
+
constructor(pusher) {
|
|
2255
|
+
this.#pusher = pusher;
|
|
2256
|
+
}
|
|
2257
|
+
export(records, opts) {
|
|
2258
|
+
return exportWith(
|
|
2259
|
+
records,
|
|
2260
|
+
() => this.#pusher.pushOtlp(records, {
|
|
2261
|
+
gzip: opts.gzip,
|
|
2262
|
+
...opts.signal === void 0 ? {} : { signal: opts.signal }
|
|
2263
|
+
})
|
|
2264
|
+
);
|
|
2265
|
+
}
|
|
2266
|
+
shutdown() {
|
|
2267
|
+
return Promise.resolve();
|
|
2268
|
+
}
|
|
2269
|
+
};
|
|
2270
|
+
var OTLP_SCOPE_NAME = "grow-codes-grafana-loki";
|
|
2271
|
+
function toOtlpValue(value) {
|
|
2272
|
+
if (typeof value === "string") return { stringValue: value };
|
|
2273
|
+
if (typeof value === "boolean") return { boolValue: value };
|
|
2274
|
+
if (typeof value === "number") {
|
|
2275
|
+
return Number.isSafeInteger(value) ? { intValue: String(value) } : { doubleValue: value };
|
|
2276
|
+
}
|
|
2277
|
+
if (Array.isArray(value)) return { arrayValue: { values: value.map(toOtlpValue) } };
|
|
2278
|
+
return { kvlistValue: { values: toOtlpAttributes(value) } };
|
|
2279
|
+
}
|
|
2280
|
+
function toOtlpAttributes(attrs) {
|
|
2281
|
+
return Object.entries(attrs).map(([key, value]) => ({ key, value: toOtlpValue(value) }));
|
|
2282
|
+
}
|
|
2283
|
+
function recordsToOtlpJson(records) {
|
|
2284
|
+
const byResource = /* @__PURE__ */ new Map();
|
|
2285
|
+
for (const r of records) {
|
|
2286
|
+
const key = JSON.stringify(r.resource);
|
|
2287
|
+
let group = byResource.get(key);
|
|
2288
|
+
if (group === void 0) {
|
|
2289
|
+
group = { resource: r.resource, logRecords: [] };
|
|
2290
|
+
byResource.set(key, group);
|
|
2291
|
+
}
|
|
2292
|
+
const lr = {
|
|
2293
|
+
timeUnixNano: dateToNanos(r.timestamp),
|
|
2294
|
+
observedTimeUnixNano: dateToNanos(r.observedTimestamp ?? r.timestamp),
|
|
2295
|
+
severityNumber: r.severity,
|
|
2296
|
+
severityText: r.severityText,
|
|
2297
|
+
body: { stringValue: r.body },
|
|
2298
|
+
attributes: toOtlpAttributes(r.attributes)
|
|
2299
|
+
};
|
|
2300
|
+
if (r.traceId !== void 0) lr.traceId = r.traceId;
|
|
2301
|
+
if (r.spanId !== void 0) lr.spanId = r.spanId;
|
|
2302
|
+
if (r.traceFlags !== void 0) lr.flags = r.traceFlags;
|
|
2303
|
+
group.logRecords.push(lr);
|
|
2304
|
+
}
|
|
2305
|
+
return {
|
|
2306
|
+
resourceLogs: [...byResource.values()].map((g) => ({
|
|
2307
|
+
resource: { attributes: toOtlpAttributes(g.resource) },
|
|
2308
|
+
scopeLogs: [{ scope: { name: OTLP_SCOPE_NAME }, logRecords: g.logRecords }]
|
|
2309
|
+
}))
|
|
2310
|
+
};
|
|
2311
|
+
}
|
|
2312
|
+
var encoder = new TextEncoder();
|
|
2313
|
+
var Writer = class {
|
|
2314
|
+
#chunks = [];
|
|
2315
|
+
#length = 0;
|
|
2316
|
+
get length() {
|
|
2317
|
+
return this.#length;
|
|
2318
|
+
}
|
|
2319
|
+
bytes(b) {
|
|
2320
|
+
this.#chunks.push(b);
|
|
2321
|
+
this.#length += b.length;
|
|
2322
|
+
}
|
|
2323
|
+
varint(value) {
|
|
2324
|
+
const out = [];
|
|
2325
|
+
let v = value;
|
|
2326
|
+
while (v > 0x7fn) {
|
|
2327
|
+
out.push(Number(v & 0x7fn) | 128);
|
|
2328
|
+
v >>= 7n;
|
|
2329
|
+
}
|
|
2330
|
+
out.push(Number(v));
|
|
2331
|
+
this.bytes(Uint8Array.from(out));
|
|
2332
|
+
}
|
|
2333
|
+
tag(field, wireType) {
|
|
2334
|
+
this.varint(BigInt(field << 3 | wireType));
|
|
2335
|
+
}
|
|
2336
|
+
/** Length-delimited field (wire type 2). */
|
|
2337
|
+
lengthDelimited(field, payload) {
|
|
2338
|
+
this.tag(field, 2);
|
|
2339
|
+
this.varint(BigInt(payload.length));
|
|
2340
|
+
this.bytes(payload);
|
|
2341
|
+
}
|
|
2342
|
+
string(field, value) {
|
|
2343
|
+
this.lengthDelimited(field, encoder.encode(value));
|
|
2344
|
+
}
|
|
2345
|
+
/** Varint field (wire type 0); zero values are omitted (proto3 default). */
|
|
2346
|
+
uint(field, value) {
|
|
2347
|
+
if (value === 0n) return;
|
|
2348
|
+
this.tag(field, 0);
|
|
2349
|
+
this.varint(value);
|
|
2350
|
+
}
|
|
2351
|
+
finish() {
|
|
2352
|
+
const out = new Uint8Array(this.#length);
|
|
2353
|
+
let offset = 0;
|
|
2354
|
+
for (const c of this.#chunks) {
|
|
2355
|
+
out.set(c, offset);
|
|
2356
|
+
offset += c.length;
|
|
2357
|
+
}
|
|
2358
|
+
return out;
|
|
2359
|
+
}
|
|
2360
|
+
};
|
|
2361
|
+
function encodeTimestamp(ns) {
|
|
2362
|
+
const w = new Writer();
|
|
2363
|
+
w.uint(1, ns / 1000000000n);
|
|
2364
|
+
w.uint(2, ns % 1000000000n);
|
|
2365
|
+
return w.finish();
|
|
2366
|
+
}
|
|
2367
|
+
function encodePushRequest(streams) {
|
|
2368
|
+
const req = new Writer();
|
|
2369
|
+
for (const stream of streams) {
|
|
2370
|
+
const s = new Writer();
|
|
2371
|
+
s.string(1, formatLabelSet(stream.labels));
|
|
2372
|
+
for (const entry of stream.entries) {
|
|
2373
|
+
const e = new Writer();
|
|
2374
|
+
e.lengthDelimited(
|
|
2375
|
+
1,
|
|
2376
|
+
encodeTimestamp(BigInt(toNanos(entry.timestamp ?? /* @__PURE__ */ new Date(), "timestamp")))
|
|
2377
|
+
);
|
|
2378
|
+
e.string(2, entry.line);
|
|
2379
|
+
for (const [name, value] of Object.entries(entry.structuredMetadata ?? {})) {
|
|
2380
|
+
const pair = new Writer();
|
|
2381
|
+
pair.string(1, name);
|
|
2382
|
+
pair.string(2, value);
|
|
2383
|
+
e.lengthDelimited(3, pair.finish());
|
|
2384
|
+
}
|
|
2385
|
+
s.lengthDelimited(2, e.finish());
|
|
2386
|
+
}
|
|
2387
|
+
req.lengthDelimited(1, s.finish());
|
|
2388
|
+
}
|
|
2389
|
+
return req.finish();
|
|
2390
|
+
}
|
|
2391
|
+
function snappyCompress(data) {
|
|
2392
|
+
return snappyjs.compress(data);
|
|
2393
|
+
}
|
|
2394
|
+
function decodeRpcStatusMessage(bytes) {
|
|
2395
|
+
let pos = 0;
|
|
2396
|
+
const readVarint = () => {
|
|
2397
|
+
let result = 0;
|
|
2398
|
+
let shift = 0;
|
|
2399
|
+
while (pos < bytes.length && shift < 35) {
|
|
2400
|
+
const b = bytes[pos++];
|
|
2401
|
+
result += (b & 127) * 2 ** shift;
|
|
2402
|
+
if ((b & 128) === 0) return result;
|
|
2403
|
+
shift += 7;
|
|
2404
|
+
}
|
|
2405
|
+
return void 0;
|
|
2406
|
+
};
|
|
2407
|
+
let message;
|
|
2408
|
+
while (pos < bytes.length) {
|
|
2409
|
+
const tag = readVarint();
|
|
2410
|
+
if (tag === void 0) return void 0;
|
|
2411
|
+
const field = tag >> 3;
|
|
2412
|
+
const wire = tag & 7;
|
|
2413
|
+
if (wire === 0) {
|
|
2414
|
+
if (readVarint() === void 0) return void 0;
|
|
2415
|
+
} else if (wire === 2) {
|
|
2416
|
+
const len = readVarint();
|
|
2417
|
+
if (len === void 0 || pos + len > bytes.length) return void 0;
|
|
2418
|
+
if (field === 2) message = new TextDecoder().decode(bytes.subarray(pos, pos + len));
|
|
2419
|
+
pos += len;
|
|
2420
|
+
} else {
|
|
2421
|
+
return void 0;
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
return message;
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
// src/logql.ts
|
|
2428
|
+
var MATCH_OPS = /* @__PURE__ */ new Set(["=", "!=", "=~", "!~"]);
|
|
2429
|
+
var NUMERIC_OPS = /* @__PURE__ */ new Set(["==", "!=", ">", ">=", "<", "<="]);
|
|
2430
|
+
function quoteLogQL(value) {
|
|
2431
|
+
return JSON.stringify(value);
|
|
2432
|
+
}
|
|
2433
|
+
function checkName(name, what) {
|
|
2434
|
+
if (!LABEL_NAME_PATTERN.test(name)) {
|
|
2435
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(
|
|
2436
|
+
`LogQL: invalid ${what} ${JSON.stringify(name)}: must match [a-zA-Z_][a-zA-Z0-9_]*`
|
|
2437
|
+
);
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
function formatNumber(value) {
|
|
2441
|
+
if (!Number.isFinite(value)) throw new chunkVGAJJR3M_cjs.ValidationError("LogQL: numbers must be finite");
|
|
2442
|
+
return value.toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 });
|
|
2443
|
+
}
|
|
2444
|
+
function matchesEmpty(m) {
|
|
2445
|
+
switch (m.op) {
|
|
2446
|
+
case "=":
|
|
2447
|
+
return m.value === "";
|
|
2448
|
+
case "!=":
|
|
2449
|
+
return m.value !== "";
|
|
2450
|
+
default: {
|
|
2451
|
+
let re;
|
|
2452
|
+
try {
|
|
2453
|
+
re = new RegExp(`^(?:${m.value})$`);
|
|
2454
|
+
} catch {
|
|
2455
|
+
return false;
|
|
2456
|
+
}
|
|
2457
|
+
return m.op === "=~" ? re.test("") : !re.test("");
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
var LogQL = class _LogQL {
|
|
2462
|
+
#matchers;
|
|
2463
|
+
#stages;
|
|
2464
|
+
constructor(matchers, stages) {
|
|
2465
|
+
this.#matchers = matchers;
|
|
2466
|
+
this.#stages = stages;
|
|
2467
|
+
}
|
|
2468
|
+
/** Starts a query from equality matchers (`{app="x", env="prod"}`). */
|
|
2469
|
+
static selector(labels = {}) {
|
|
2470
|
+
let q = new _LogQL([], []);
|
|
2471
|
+
for (const [name, value] of Object.entries(labels)) q = q.label(name, "=", value);
|
|
2472
|
+
return q;
|
|
2473
|
+
}
|
|
2474
|
+
/** Quotes a string literal (see {@link quoteLogQL}). */
|
|
2475
|
+
static quote(value) {
|
|
2476
|
+
return quoteLogQL(value);
|
|
2477
|
+
}
|
|
2478
|
+
/** Adds a stream-selector matcher (`=`, `!=`, `=~`, `!~`). */
|
|
2479
|
+
label(name, op, value) {
|
|
2480
|
+
checkName(name, "label name");
|
|
2481
|
+
if (!MATCH_OPS.has(op)) throw new chunkVGAJJR3M_cjs.ValidationError(`LogQL: invalid matcher operator ${op}`);
|
|
2482
|
+
return new _LogQL([...this.#matchers, { name, op, value }], this.#stages);
|
|
2483
|
+
}
|
|
2484
|
+
#stage(text) {
|
|
2485
|
+
return new _LogQL(this.#matchers, [...this.#stages, text]);
|
|
2486
|
+
}
|
|
2487
|
+
/** Line filter `|= "text"` (case-sensitive substring). */
|
|
2488
|
+
lineContains(text) {
|
|
2489
|
+
return this.#stage(`|= ${quoteLogQL(text)}`);
|
|
2490
|
+
}
|
|
2491
|
+
/** Line filter `!= "text"`. */
|
|
2492
|
+
lineNotContains(text) {
|
|
2493
|
+
return this.#stage(`!= ${quoteLogQL(text)}`);
|
|
2494
|
+
}
|
|
2495
|
+
/** Line filter `|~ "regex"` (RE2; prefix `(?i)` for case-insensitive). */
|
|
2496
|
+
lineMatches(regex) {
|
|
2497
|
+
return this.#stage(`|~ ${quoteLogQL(regex)}`);
|
|
2498
|
+
}
|
|
2499
|
+
/** Line filter `!~ "regex"`. */
|
|
2500
|
+
lineNotMatches(regex) {
|
|
2501
|
+
return this.#stage(`!~ ${quoteLogQL(regex)}`);
|
|
2502
|
+
}
|
|
2503
|
+
/** Parser stage `| json`. */
|
|
2504
|
+
json() {
|
|
2505
|
+
return this.#stage("| json");
|
|
2506
|
+
}
|
|
2507
|
+
/** Parser stage `| logfmt`. */
|
|
2508
|
+
logfmt() {
|
|
2509
|
+
return this.#stage("| logfmt");
|
|
2510
|
+
}
|
|
2511
|
+
/** Parser stage `| unpack` (lines packed by Promtail's `pack` stage). */
|
|
2512
|
+
unpack() {
|
|
2513
|
+
return this.#stage("| unpack");
|
|
2514
|
+
}
|
|
2515
|
+
/** Parser stage `| regexp "<re>"` with named capture groups. */
|
|
2516
|
+
regexp(pattern) {
|
|
2517
|
+
return this.#stage(`| regexp ${quoteLogQL(pattern)}`);
|
|
2518
|
+
}
|
|
2519
|
+
/** Parser stage `| pattern "<pattern>"`. */
|
|
2520
|
+
pattern(pattern) {
|
|
2521
|
+
return this.#stage(`| pattern ${quoteLogQL(pattern)}`);
|
|
2522
|
+
}
|
|
2523
|
+
/** Formatting stage `| line_format "<template>"`. */
|
|
2524
|
+
lineFormat(template) {
|
|
2525
|
+
return this.#stage(`| line_format ${quoteLogQL(template)}`);
|
|
2526
|
+
}
|
|
2527
|
+
/**
|
|
2528
|
+
* Label filter on an extracted label or structured-metadata key. Numbers use the numeric
|
|
2529
|
+
* operators (`==`, `!=`, `>`, `>=`, `<`, `<=`); strings use `=`, `!=`, `=~`, `!~`.
|
|
2530
|
+
*/
|
|
2531
|
+
where(field, op, value) {
|
|
2532
|
+
checkName(field, "field name");
|
|
2533
|
+
if (typeof value === "number") {
|
|
2534
|
+
if (!NUMERIC_OPS.has(op)) {
|
|
2535
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`LogQL: operator ${op} cannot compare numbers`);
|
|
2536
|
+
}
|
|
2537
|
+
return this.#stage(`| ${field} ${op} ${formatNumber(value)}`);
|
|
2538
|
+
}
|
|
2539
|
+
if (!MATCH_OPS.has(op)) {
|
|
2540
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`LogQL: operator ${op} cannot compare strings`);
|
|
2541
|
+
}
|
|
2542
|
+
return this.#stage(`| ${field} ${op} ${quoteLogQL(value)}`);
|
|
2543
|
+
}
|
|
2544
|
+
/** Appends a raw pipeline stage (`| <stage>`, e.g. `drop level`); the text is not escaped. */
|
|
2545
|
+
pipe(stage) {
|
|
2546
|
+
return this.#stage(`| ${stage.trim()}`);
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Renders the query. Throws `ValidationError` when the selector is empty or every matcher
|
|
2550
|
+
* also matches the empty string (Loki rejects such selectors).
|
|
2551
|
+
*/
|
|
2552
|
+
toString() {
|
|
2553
|
+
if (this.#matchers.length === 0) {
|
|
2554
|
+
throw new chunkVGAJJR3M_cjs.ValidationError("LogQL: a stream selector needs at least one matcher");
|
|
2555
|
+
}
|
|
2556
|
+
if (this.#matchers.every(matchesEmpty)) {
|
|
2557
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(
|
|
2558
|
+
"LogQL: the selector needs at least one matcher that does not match the empty value"
|
|
2559
|
+
);
|
|
2560
|
+
}
|
|
2561
|
+
const selector = `{${this.#matchers.map((m) => `${m.name}${m.op}${quoteLogQL(m.value)}`).join(", ")}}`;
|
|
2562
|
+
return [selector, ...this.#stages].join(" ");
|
|
2563
|
+
}
|
|
2564
|
+
/** Same as {@link toString}. */
|
|
2565
|
+
build() {
|
|
2566
|
+
return this.toString();
|
|
2567
|
+
}
|
|
2568
|
+
};
|
|
2569
|
+
|
|
2570
|
+
// src/query-client.ts
|
|
2571
|
+
var MAX_QUERY_LIMIT = 5e3;
|
|
2572
|
+
var ALL_STREAMS_SELECTOR = '{service_name=~".+"}';
|
|
2573
|
+
var RESOURCE_KEYS = {
|
|
2574
|
+
service_name: "service.name",
|
|
2575
|
+
service_namespace: "service.namespace",
|
|
2576
|
+
service_version: "service.version",
|
|
2577
|
+
service_instance_id: "service.instance.id",
|
|
2578
|
+
deployment_environment: "deployment.environment",
|
|
2579
|
+
host_name: "host.name"
|
|
2580
|
+
};
|
|
2581
|
+
function toSearchLogQL(query) {
|
|
2582
|
+
const trimmed = query.trim();
|
|
2583
|
+
if (trimmed.startsWith("{")) return trimmed;
|
|
2584
|
+
if (trimmed === "") return ALL_STREAMS_SELECTOR;
|
|
2585
|
+
return `${ALL_STREAMS_SELECTOR} |= ${quoteLogQL(trimmed)}`;
|
|
2586
|
+
}
|
|
2587
|
+
function encodeCursor(ns, skip) {
|
|
2588
|
+
return Buffer.from(`${ns}:${skip}`, "utf8").toString("base64url");
|
|
2589
|
+
}
|
|
2590
|
+
function decodeCursor(cursor) {
|
|
2591
|
+
const text = Buffer.from(cursor, "base64url").toString("utf8");
|
|
2592
|
+
const match = /^(\d+):(\d+)$/.exec(text);
|
|
2593
|
+
if (match === null) throw new chunkVGAJJR3M_cjs.ValidationError("logging.search: invalid cursor");
|
|
2594
|
+
return { ns: match[1], skip: Number(match[2]) };
|
|
2595
|
+
}
|
|
2596
|
+
var CONSUMED_METADATA = /* @__PURE__ */ new Set([
|
|
2597
|
+
"severity_text",
|
|
2598
|
+
"severity_number",
|
|
2599
|
+
"trace_id",
|
|
2600
|
+
"span_id",
|
|
2601
|
+
"trace_flags",
|
|
2602
|
+
"observed_timestamp"
|
|
2603
|
+
]);
|
|
2604
|
+
function severityFrom(md, labels) {
|
|
2605
|
+
const fromNumber = md.severity_number === void 0 ? null : chunkVGAJJR3M_cjs.parseSeverity(md.severity_number);
|
|
2606
|
+
const fromText = md.severity_text === void 0 ? null : chunkVGAJJR3M_cjs.parseSeverity(md.severity_text);
|
|
2607
|
+
const severity = fromNumber ?? fromText ?? (md.detected_level === void 0 ? null : chunkVGAJJR3M_cjs.parseSeverity(md.detected_level)) ?? (labels.level === void 0 ? null : chunkVGAJJR3M_cjs.parseSeverity(labels.level)) ?? 9 /* Info */;
|
|
2608
|
+
return { severity, text: md.severity_text ?? chunkVGAJJR3M_cjs.severityText(severity) };
|
|
2609
|
+
}
|
|
2610
|
+
function entryToLogRecord(labels, entry) {
|
|
2611
|
+
const md = entry.structuredMetadata;
|
|
2612
|
+
const attributes = {};
|
|
2613
|
+
for (const [k, v] of Object.entries(md)) if (!CONSUMED_METADATA.has(k)) attributes[k] = v;
|
|
2614
|
+
for (const [k, v] of Object.entries(entry.parsed)) attributes[k] = v;
|
|
2615
|
+
const resource = {};
|
|
2616
|
+
for (const [k, v] of Object.entries(labels)) resource[RESOURCE_KEYS[k] ?? k] = v;
|
|
2617
|
+
const { severity, text } = severityFrom(md, labels);
|
|
2618
|
+
const record = {
|
|
2619
|
+
timestamp: entry.timestamp,
|
|
2620
|
+
severity,
|
|
2621
|
+
severityText: text,
|
|
2622
|
+
body: entry.line,
|
|
2623
|
+
attributes,
|
|
2624
|
+
resource
|
|
2625
|
+
};
|
|
2626
|
+
if (md.observed_timestamp !== void 0 && /^\d+$/.test(md.observed_timestamp)) {
|
|
2627
|
+
record.observedTimestamp = nanosToDate(md.observed_timestamp);
|
|
2628
|
+
}
|
|
2629
|
+
const traceId = md.trace_id?.toLowerCase();
|
|
2630
|
+
if (traceId !== void 0 && /^[0-9a-f]{32}$/.test(traceId)) {
|
|
2631
|
+
record.traceId = traceId;
|
|
2632
|
+
const spanId = md.span_id?.toLowerCase();
|
|
2633
|
+
if (spanId !== void 0 && /^[0-9a-f]{16}$/.test(spanId)) record.spanId = spanId;
|
|
2634
|
+
const flagsText = md.trace_flags ?? md.flags;
|
|
2635
|
+
if (flagsText !== void 0 && /^\d+$/.test(flagsText)) {
|
|
2636
|
+
record.traceFlags = Number(flagsText);
|
|
2637
|
+
if (md.trace_flags === void 0) delete attributes.flags;
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
return record;
|
|
2641
|
+
}
|
|
2642
|
+
function compareNs(a, b) {
|
|
2643
|
+
if (a.length !== b.length) return a.length - b.length;
|
|
2644
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
2645
|
+
}
|
|
2646
|
+
function mergeStreams(streams, order) {
|
|
2647
|
+
const flat = [];
|
|
2648
|
+
for (const s of streams) {
|
|
2649
|
+
const labelKey = formatLabelSet(s.labels);
|
|
2650
|
+
for (const entry of s.entries) flat.push({ labels: s.labels, labelKey, entry });
|
|
2651
|
+
}
|
|
2652
|
+
const dir = order === "asc" ? 1 : -1;
|
|
2653
|
+
flat.sort((a, b) => {
|
|
2654
|
+
const t = compareNs(a.entry.timestampNs, b.entry.timestampNs);
|
|
2655
|
+
if (t !== 0) return t * dir;
|
|
2656
|
+
if (a.labelKey !== b.labelKey) return a.labelKey < b.labelKey ? -1 : 1;
|
|
2657
|
+
return a.entry.line < b.entry.line ? -1 : a.entry.line > b.entry.line ? 1 : 0;
|
|
2658
|
+
});
|
|
2659
|
+
return flat;
|
|
2660
|
+
}
|
|
2661
|
+
var LokiLogQueryClient = class extends chunkVGAJJR3M_cjs.BaseLogQueryClient {
|
|
2662
|
+
#source;
|
|
2663
|
+
constructor(source) {
|
|
2664
|
+
super();
|
|
2665
|
+
this.#source = source;
|
|
2666
|
+
}
|
|
2667
|
+
/**
|
|
2668
|
+
* Searches with `query_range`. `query` is LogQL (starting with `{`) or free text. `order`
|
|
2669
|
+
* `desc` (default) is newest first. Pass `nextCursor` back as `cursor` for the next page
|
|
2670
|
+
* (the cursor is `<timestamp>:<entries at that timestamp already returned>`, so pages never
|
|
2671
|
+
* skip or repeat entries sharing a nanosecond). `total` is not available from Loki.
|
|
2672
|
+
*/
|
|
2673
|
+
async search(query, opts = {}) {
|
|
2674
|
+
const limit = opts.limit ?? 100;
|
|
2675
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_QUERY_LIMIT) {
|
|
2676
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`logging.search: limit must be an integer 1..${MAX_QUERY_LIMIT}`);
|
|
2677
|
+
}
|
|
2678
|
+
const order = opts.order ?? "desc";
|
|
2679
|
+
let start = opts.start;
|
|
2680
|
+
let end = opts.end;
|
|
2681
|
+
let cursor;
|
|
2682
|
+
if (opts.cursor !== void 0) {
|
|
2683
|
+
cursor = decodeCursor(opts.cursor);
|
|
2684
|
+
if (order === "desc") end = BigInt(cursor.ns) + 1n;
|
|
2685
|
+
else start = BigInt(cursor.ns);
|
|
2686
|
+
}
|
|
2687
|
+
const fetch = Math.min(limit + (cursor?.skip ?? 0), MAX_QUERY_LIMIT);
|
|
2688
|
+
const logql = toSearchLogQL(query);
|
|
2689
|
+
const direction = order === "asc" ? "forward" : "backward";
|
|
2690
|
+
const signal = opts.signal === void 0 ? {} : { signal: opts.signal };
|
|
2691
|
+
const result = await this.#source.queryRange(logql, {
|
|
2692
|
+
...start === void 0 ? {} : { start },
|
|
2693
|
+
...end === void 0 ? {} : { end },
|
|
2694
|
+
limit: fetch,
|
|
2695
|
+
direction,
|
|
2696
|
+
...signal
|
|
2697
|
+
});
|
|
2698
|
+
let merged = mergeStreams(result.streams, order);
|
|
2699
|
+
const truncated = merged.length >= fetch;
|
|
2700
|
+
const boundary = merged[merged.length - 1]?.entry.timestampNs;
|
|
2701
|
+
if (truncated && boundary !== void 0) {
|
|
2702
|
+
const exact = await this.#source.queryRange(logql, {
|
|
2703
|
+
start: BigInt(boundary),
|
|
2704
|
+
end: BigInt(boundary) + 1n,
|
|
2705
|
+
limit: MAX_QUERY_LIMIT,
|
|
2706
|
+
direction,
|
|
2707
|
+
...signal
|
|
2708
|
+
});
|
|
2709
|
+
merged = mergeStreams(
|
|
2710
|
+
[
|
|
2711
|
+
...result.streams.map((s) => ({
|
|
2712
|
+
labels: s.labels,
|
|
2713
|
+
entries: s.entries.filter((e) => e.timestampNs !== boundary)
|
|
2714
|
+
})),
|
|
2715
|
+
...exact.streams
|
|
2716
|
+
],
|
|
2717
|
+
order
|
|
2718
|
+
);
|
|
2719
|
+
}
|
|
2720
|
+
let offset = 0;
|
|
2721
|
+
if (cursor !== void 0) {
|
|
2722
|
+
while (offset < cursor.skip && offset < merged.length && merged[offset]?.entry.timestampNs === cursor.ns) {
|
|
2723
|
+
offset++;
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
const remaining = merged.slice(offset);
|
|
2727
|
+
const page = remaining.slice(0, limit);
|
|
2728
|
+
const out = {
|
|
2729
|
+
records: page.map((f) => entryToLogRecord(f.labels, f.entry))
|
|
2730
|
+
};
|
|
2731
|
+
const more = truncated || remaining.length > limit;
|
|
2732
|
+
const last = page[page.length - 1];
|
|
2733
|
+
if (more && last !== void 0) {
|
|
2734
|
+
const lastNs = last.entry.timestampNs;
|
|
2735
|
+
let atLast = page.filter((f) => f.entry.timestampNs === lastNs).length;
|
|
2736
|
+
if (cursor !== void 0 && cursor.ns === lastNs) atLast += cursor.skip;
|
|
2737
|
+
out.nextCursor = encodeCursor(lastNs, atLast);
|
|
2738
|
+
}
|
|
2739
|
+
return out;
|
|
2740
|
+
}
|
|
2741
|
+
/**
|
|
2742
|
+
* Live tail over the WebSocket API (`start` defaults to now, so only new records arrive).
|
|
2743
|
+
* Connection errors and abnormal closes go to `opts.onError`.
|
|
2744
|
+
*/
|
|
2745
|
+
tail(query, onRecord, opts = {}) {
|
|
2746
|
+
let stopped = false;
|
|
2747
|
+
let tail;
|
|
2748
|
+
const report = (error) => {
|
|
2749
|
+
if (!stopped) opts.onError?.(error);
|
|
2750
|
+
};
|
|
2751
|
+
this.#source.tail(
|
|
2752
|
+
toSearchLogQL(query),
|
|
2753
|
+
(streams) => {
|
|
2754
|
+
for (const f of mergeStreams(streams, "asc")) {
|
|
2755
|
+
if (stopped) return;
|
|
2756
|
+
onRecord(entryToLogRecord(f.labels, f.entry));
|
|
2757
|
+
}
|
|
2758
|
+
},
|
|
2759
|
+
{ start: opts.start ?? /* @__PURE__ */ new Date(), onError: report }
|
|
2760
|
+
).then((t) => {
|
|
2761
|
+
tail = t;
|
|
2762
|
+
if (stopped) t.stop();
|
|
2763
|
+
}, report);
|
|
2764
|
+
return {
|
|
2765
|
+
stop() {
|
|
2766
|
+
stopped = true;
|
|
2767
|
+
tail?.stop();
|
|
2768
|
+
}
|
|
2769
|
+
};
|
|
2770
|
+
}
|
|
2771
|
+
/** Every stream of the default window as a label-set string (`{a="b", c="d"}`), sorted. */
|
|
2772
|
+
async listStreams() {
|
|
2773
|
+
const series = await this.#source.series([ALL_STREAMS_SELECTOR]);
|
|
2774
|
+
return [...new Set(series.map(formatLabelSet))].sort();
|
|
2775
|
+
}
|
|
2776
|
+
/** Label names of the default window. */
|
|
2777
|
+
listLabels() {
|
|
2778
|
+
return this.#source.labels();
|
|
2779
|
+
}
|
|
2780
|
+
};
|
|
2781
|
+
|
|
2782
|
+
// src/results.ts
|
|
2783
|
+
function isObject(v) {
|
|
2784
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2785
|
+
}
|
|
2786
|
+
function bad(what) {
|
|
2787
|
+
throw new chunkVGAJJR3M_cjs.UnavailableError(`unexpected response from Loki: ${what}`, { retryable: false });
|
|
2788
|
+
}
|
|
2789
|
+
function stringMap(v) {
|
|
2790
|
+
const out = {};
|
|
2791
|
+
if (!isObject(v)) return out;
|
|
2792
|
+
for (const [k, val] of Object.entries(v)) {
|
|
2793
|
+
if (val === null || val === void 0) continue;
|
|
2794
|
+
out[k] = typeof val === "string" ? val : JSON.stringify(val);
|
|
2795
|
+
}
|
|
2796
|
+
return out;
|
|
2797
|
+
}
|
|
2798
|
+
function parseValue(v) {
|
|
2799
|
+
if (typeof v === "number") return v;
|
|
2800
|
+
if (typeof v !== "string") return Number.NaN;
|
|
2801
|
+
if (v === "+Inf" || v === "Inf") return Number.POSITIVE_INFINITY;
|
|
2802
|
+
if (v === "-Inf") return Number.NEGATIVE_INFINITY;
|
|
2803
|
+
return Number(v);
|
|
2804
|
+
}
|
|
2805
|
+
function decodeSample(v) {
|
|
2806
|
+
if (!Array.isArray(v) || v.length < 2 || typeof v[0] !== "number") bad("malformed sample");
|
|
2807
|
+
return { timestamp: secondsToDate(v[0]), value: parseValue(v[1]) };
|
|
2808
|
+
}
|
|
2809
|
+
function decodeEntry(v) {
|
|
2810
|
+
if (!Array.isArray(v) || typeof v[0] !== "string" || typeof v[1] !== "string") {
|
|
2811
|
+
bad("malformed stream value");
|
|
2812
|
+
}
|
|
2813
|
+
const ns = v[0];
|
|
2814
|
+
if (!/^\d+$/.test(ns)) bad("malformed timestamp");
|
|
2815
|
+
const extra = v[2];
|
|
2816
|
+
return {
|
|
2817
|
+
timestampNs: ns,
|
|
2818
|
+
timestamp: nanosToDate(ns),
|
|
2819
|
+
line: v[1],
|
|
2820
|
+
structuredMetadata: isObject(extra) ? stringMap(extra.structuredMetadata) : {},
|
|
2821
|
+
parsed: isObject(extra) ? stringMap(extra.parsed) : {}
|
|
2822
|
+
};
|
|
2823
|
+
}
|
|
2824
|
+
function decodeStreams(v) {
|
|
2825
|
+
if (v === void 0 || v === null) return [];
|
|
2826
|
+
if (!Array.isArray(v)) bad("streams is not a list");
|
|
2827
|
+
return v.map((s) => {
|
|
2828
|
+
if (!isObject(s)) bad("malformed stream");
|
|
2829
|
+
const values = Array.isArray(s.values) ? s.values : [];
|
|
2830
|
+
return { labels: stringMap(s.stream), entries: values.map(decodeEntry) };
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
function decodeQueryResult(body) {
|
|
2834
|
+
if (!isObject(body) || !isObject(body.data)) bad("missing data");
|
|
2835
|
+
const data = body.data;
|
|
2836
|
+
const resultType = data.resultType;
|
|
2837
|
+
const out = {
|
|
2838
|
+
resultType: "streams",
|
|
2839
|
+
streams: [],
|
|
2840
|
+
vector: [],
|
|
2841
|
+
matrix: [],
|
|
2842
|
+
stats: isObject(data.stats) ? data.stats : {}
|
|
2843
|
+
};
|
|
2844
|
+
const result = data.result;
|
|
2845
|
+
switch (resultType) {
|
|
2846
|
+
case "streams":
|
|
2847
|
+
out.streams = decodeStreams(result);
|
|
2848
|
+
break;
|
|
2849
|
+
case "vector":
|
|
2850
|
+
out.resultType = "vector";
|
|
2851
|
+
out.vector = (Array.isArray(result) ? result : []).map((r) => {
|
|
2852
|
+
if (!isObject(r)) bad("malformed vector sample");
|
|
2853
|
+
return { metric: stringMap(r.metric), ...decodeSample(r.value) };
|
|
2854
|
+
});
|
|
2855
|
+
break;
|
|
2856
|
+
case "matrix":
|
|
2857
|
+
out.resultType = "matrix";
|
|
2858
|
+
out.matrix = (Array.isArray(result) ? result : []).map((r) => {
|
|
2859
|
+
if (!isObject(r)) bad("malformed matrix series");
|
|
2860
|
+
const values = Array.isArray(r.values) ? r.values : [];
|
|
2861
|
+
return { metric: stringMap(r.metric), samples: values.map(decodeSample) };
|
|
2862
|
+
});
|
|
2863
|
+
break;
|
|
2864
|
+
case "scalar":
|
|
2865
|
+
out.resultType = "scalar";
|
|
2866
|
+
out.scalar = decodeSample(result);
|
|
2867
|
+
break;
|
|
2868
|
+
default:
|
|
2869
|
+
bad(`unknown resultType ${String(resultType)}`);
|
|
2870
|
+
}
|
|
2871
|
+
return out;
|
|
2872
|
+
}
|
|
2873
|
+
function decodeStringList(body) {
|
|
2874
|
+
if (!isObject(body)) bad("missing body");
|
|
2875
|
+
const data = body.data;
|
|
2876
|
+
if (data === void 0 || data === null) return [];
|
|
2877
|
+
if (!Array.isArray(data)) bad("data is not a list");
|
|
2878
|
+
return data.filter((x) => typeof x === "string");
|
|
2879
|
+
}
|
|
2880
|
+
function decodeSeries(body) {
|
|
2881
|
+
if (!isObject(body)) bad("missing body");
|
|
2882
|
+
const data = body.data;
|
|
2883
|
+
if (data === void 0 || data === null) return [];
|
|
2884
|
+
if (!Array.isArray(data)) bad("data is not a list");
|
|
2885
|
+
return data.map(stringMap);
|
|
2886
|
+
}
|
|
2887
|
+
function decodeIndexStats(body) {
|
|
2888
|
+
if (!isObject(body)) bad("missing body");
|
|
2889
|
+
const num = (k) => typeof body[k] === "number" ? body[k] : 0;
|
|
2890
|
+
return {
|
|
2891
|
+
streams: num("streams"),
|
|
2892
|
+
chunks: num("chunks"),
|
|
2893
|
+
bytes: num("bytes"),
|
|
2894
|
+
entries: num("entries")
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
function decodeBuildInfo(body) {
|
|
2898
|
+
if (!isObject(body)) bad("missing body");
|
|
2899
|
+
const str = (k) => typeof body[k] === "string" ? body[k] : "";
|
|
2900
|
+
return {
|
|
2901
|
+
version: str("version"),
|
|
2902
|
+
revision: str("revision"),
|
|
2903
|
+
branch: str("branch"),
|
|
2904
|
+
buildUser: str("buildUser"),
|
|
2905
|
+
buildDate: str("buildDate"),
|
|
2906
|
+
goVersion: str("goVersion")
|
|
2907
|
+
};
|
|
2908
|
+
}
|
|
2909
|
+
function decodeTailFrame(body) {
|
|
2910
|
+
if (!isObject(body)) bad("malformed tail frame");
|
|
2911
|
+
const dropped = Array.isArray(body.dropped_entries) ? body.dropped_entries : [];
|
|
2912
|
+
return {
|
|
2913
|
+
streams: decodeStreams(body.streams),
|
|
2914
|
+
droppedEntries: dropped.filter(isObject).map((d) => ({
|
|
2915
|
+
labels: stringMap(d.labels),
|
|
2916
|
+
timestampNs: typeof d.timestamp === "string" ? d.timestamp : String(d.timestamp)
|
|
2917
|
+
}))
|
|
2918
|
+
};
|
|
2919
|
+
}
|
|
2920
|
+
function vendorText(text, redact) {
|
|
2921
|
+
const trimmed = text.trim().replace(/\s+/g, " ");
|
|
2922
|
+
if (trimmed === "") return void 0;
|
|
2923
|
+
const red = redact(trimmed);
|
|
2924
|
+
return red.length > MAX_VENDOR_TEXT ? red.slice(0, MAX_VENDOR_TEXT - 1) + "\u2026" : red;
|
|
2925
|
+
}
|
|
2926
|
+
function tlsOptions(tls) {
|
|
2927
|
+
const ca = [
|
|
2928
|
+
tls.caCertPem,
|
|
2929
|
+
tls.caCertPath === void 0 ? void 0 : fs.readFileSync(tls.caCertPath, "utf8")
|
|
2930
|
+
].filter((v) => v !== void 0);
|
|
2931
|
+
return {
|
|
2932
|
+
rejectUnauthorized: tls.insecureSkipVerify !== true,
|
|
2933
|
+
...ca.length > 0 ? { ca } : {},
|
|
2934
|
+
...tls.clientCertPath === void 0 ? {} : { cert: fs.readFileSync(tls.clientCertPath, "utf8") },
|
|
2935
|
+
...tls.clientKeyPath === void 0 ? {} : { key: fs.readFileSync(tls.clientKeyPath, "utf8") }
|
|
2936
|
+
};
|
|
2937
|
+
}
|
|
2938
|
+
function openTail(params, onFrame, callbacks = {}) {
|
|
2939
|
+
const op = "tail";
|
|
2940
|
+
return new Promise((resolve, reject) => {
|
|
2941
|
+
if (params.signal?.aborted === true) {
|
|
2942
|
+
reject(new chunkVGAJJR3M_cjs.CancelledError(`${op}: cancelled`));
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
let settled = false;
|
|
2946
|
+
let opened = false;
|
|
2947
|
+
let stopped = false;
|
|
2948
|
+
let resolveClosed;
|
|
2949
|
+
const closed = new Promise((r) => {
|
|
2950
|
+
resolveClosed = r;
|
|
2951
|
+
});
|
|
2952
|
+
const ws = new WebSocket__default.default(params.url, {
|
|
2953
|
+
headers: params.headers,
|
|
2954
|
+
handshakeTimeout: params.connectTimeoutMs,
|
|
2955
|
+
followRedirects: false,
|
|
2956
|
+
perMessageDeflate: false,
|
|
2957
|
+
...tlsOptions(params.tls)
|
|
2958
|
+
});
|
|
2959
|
+
const fail = (error) => {
|
|
2960
|
+
if (settled) return;
|
|
2961
|
+
settled = true;
|
|
2962
|
+
params.signal?.removeEventListener("abort", onAbort);
|
|
2963
|
+
reject(error);
|
|
2964
|
+
};
|
|
2965
|
+
const report = (error) => {
|
|
2966
|
+
try {
|
|
2967
|
+
callbacks.onError?.(error);
|
|
2968
|
+
} catch {
|
|
2969
|
+
}
|
|
2970
|
+
};
|
|
2971
|
+
const handle = {
|
|
2972
|
+
stop() {
|
|
2973
|
+
if (stopped) return;
|
|
2974
|
+
stopped = true;
|
|
2975
|
+
params.signal?.removeEventListener("abort", onAbort);
|
|
2976
|
+
if (ws.readyState === WebSocket__default.default.OPEN) ws.close(1e3);
|
|
2977
|
+
else ws.terminate();
|
|
2978
|
+
},
|
|
2979
|
+
closed
|
|
2980
|
+
};
|
|
2981
|
+
function onAbort() {
|
|
2982
|
+
if (!settled) {
|
|
2983
|
+
fail(new chunkVGAJJR3M_cjs.CancelledError(`${op}: cancelled`));
|
|
2984
|
+
ws.terminate();
|
|
2985
|
+
} else {
|
|
2986
|
+
handle.stop();
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
params.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2990
|
+
ws.on("unexpected-response", (req, res) => {
|
|
2991
|
+
const socket = res.socket;
|
|
2992
|
+
const chunks = [];
|
|
2993
|
+
res.on("data", (c) => chunks.push(c));
|
|
2994
|
+
res.on("end", () => {
|
|
2995
|
+
const status = res.statusCode ?? 0;
|
|
2996
|
+
const reason = vendorText(Buffer.concat(chunks).toString("utf8"), params.redact);
|
|
2997
|
+
fail(chunkVGAJJR3M_cjs.errorForStatus(op, status, reason === void 0 ? {} : { reason }));
|
|
2998
|
+
socket.destroy();
|
|
2999
|
+
req.destroy();
|
|
3000
|
+
resolveClosed();
|
|
3001
|
+
});
|
|
3002
|
+
});
|
|
3003
|
+
ws.on("open", () => {
|
|
3004
|
+
if (settled) return;
|
|
3005
|
+
settled = true;
|
|
3006
|
+
opened = true;
|
|
3007
|
+
resolve(handle);
|
|
3008
|
+
});
|
|
3009
|
+
ws.on("message", (data) => {
|
|
3010
|
+
let frame;
|
|
3011
|
+
try {
|
|
3012
|
+
frame = decodeTailFrame(
|
|
3013
|
+
JSON.parse(Buffer.from(data).toString("utf8"))
|
|
3014
|
+
);
|
|
3015
|
+
} catch (err) {
|
|
3016
|
+
report(
|
|
3017
|
+
err instanceof chunkVGAJJR3M_cjs.UnavailableError ? err : new chunkVGAJJR3M_cjs.UnavailableError(`${op}: malformed frame`, { retryable: false })
|
|
3018
|
+
);
|
|
3019
|
+
return;
|
|
3020
|
+
}
|
|
3021
|
+
if (frame.droppedEntries.length > 0) {
|
|
3022
|
+
try {
|
|
3023
|
+
callbacks.onDropped?.(frame.droppedEntries);
|
|
3024
|
+
} catch {
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
if (frame.streams.length > 0) onFrame(frame);
|
|
3028
|
+
});
|
|
3029
|
+
ws.on("error", (err) => {
|
|
3030
|
+
if (!settled) {
|
|
3031
|
+
fail(
|
|
3032
|
+
/timed out/i.test(err.message) ? new chunkVGAJJR3M_cjs.TimeoutError(`${op}: connect timeout after ${params.connectTimeoutMs} ms`) : new chunkVGAJJR3M_cjs.UnavailableError(`${op}: ${params.redact(err.message)}`)
|
|
3033
|
+
);
|
|
3034
|
+
} else if (opened && !stopped) {
|
|
3035
|
+
report(new chunkVGAJJR3M_cjs.UnavailableError(`${op}: ${params.redact(err.message)}`));
|
|
3036
|
+
}
|
|
3037
|
+
});
|
|
3038
|
+
ws.on("close", (code, reasonBuf) => {
|
|
3039
|
+
params.signal?.removeEventListener("abort", onAbort);
|
|
3040
|
+
const reason = vendorText(reasonBuf.toString("utf8"), params.redact);
|
|
3041
|
+
if (!settled) {
|
|
3042
|
+
fail(new chunkVGAJJR3M_cjs.UnavailableError(`${op}: connection closed before the upgrade (code ${code})`));
|
|
3043
|
+
} else if (opened && !stopped && code !== 1e3) {
|
|
3044
|
+
report(
|
|
3045
|
+
new chunkVGAJJR3M_cjs.UnavailableError(
|
|
3046
|
+
`${op}: connection closed (code ${code})${reason === void 0 ? "" : `: ${reason}`}`,
|
|
3047
|
+
{ retryable: code === 1001 || code === 1006 }
|
|
3048
|
+
)
|
|
3049
|
+
);
|
|
3050
|
+
}
|
|
3051
|
+
stopped = true;
|
|
3052
|
+
resolveClosed();
|
|
3053
|
+
});
|
|
3054
|
+
});
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
// src/client.ts
|
|
3058
|
+
var ENCODING_FLAGS_HEADER = "x-loki-response-encoding-flags";
|
|
3059
|
+
var TENANT_HEADER = "x-scope-orgid";
|
|
3060
|
+
var SHUTTING_DOWN = /ingester is shutting down/i;
|
|
3061
|
+
function mapLokiError(err) {
|
|
3062
|
+
if (!(err instanceof chunkVGAJJR3M_cjs.LokiError) || !SHUTTING_DOWN.test(err.message)) return err;
|
|
3063
|
+
const message = err.message.includes("WAL") ? err.message : `${err.message} (the Loki ingester is stopping or its WAL disk is at least 90 % full)`;
|
|
3064
|
+
return new chunkVGAJJR3M_cjs.UnavailableError(message, {
|
|
3065
|
+
...err.httpStatus === void 0 ? {} : { httpStatus: err.httpStatus },
|
|
3066
|
+
...err.requestId === void 0 ? {} : { requestId: err.requestId },
|
|
3067
|
+
...err.retryAfterMs === void 0 ? {} : { retryAfterMs: err.retryAfterMs },
|
|
3068
|
+
...err.cause === void 0 ? {} : { cause: err.cause },
|
|
3069
|
+
retryable: true
|
|
3070
|
+
});
|
|
3071
|
+
}
|
|
3072
|
+
function vectorToMatrix(result) {
|
|
3073
|
+
if (result.resultType !== "vector") return result;
|
|
3074
|
+
return {
|
|
3075
|
+
...result,
|
|
3076
|
+
resultType: "matrix",
|
|
3077
|
+
matrix: result.vector.map(({ metric, timestamp, value }) => ({
|
|
3078
|
+
metric,
|
|
3079
|
+
samples: [{ timestamp, value }]
|
|
3080
|
+
})),
|
|
3081
|
+
vector: []
|
|
3082
|
+
};
|
|
3083
|
+
}
|
|
3084
|
+
function cleanRpcStatus(err) {
|
|
3085
|
+
if (!(err instanceof chunkVGAJJR3M_cjs.LokiError)) return err;
|
|
3086
|
+
const match = /^(.*?: )([\s\S]*)( \(HTTP \d+\))$/.exec(err.message);
|
|
3087
|
+
if (match === null) return err;
|
|
3088
|
+
const raw = match[2];
|
|
3089
|
+
const decoded = decodeRpcStatusMessage(new TextEncoder().encode(raw)) ?? raw;
|
|
3090
|
+
const text = decoded.replace(/[\u0000-\u001f\u007f]/g, "").trim();
|
|
3091
|
+
err.message = `${match[1]}${text}${match[3]}`;
|
|
3092
|
+
return err;
|
|
3093
|
+
}
|
|
3094
|
+
function checkLimit(limit, op, max = Number.MAX_SAFE_INTEGER) {
|
|
3095
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > max)) {
|
|
3096
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: limit must be an integer 1..${max}`);
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
3099
|
+
function checkQuery(logql, op) {
|
|
3100
|
+
if (typeof logql !== "string" || logql.trim() === "") {
|
|
3101
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: query must not be empty`);
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
var LokiClient = class _LokiClient {
|
|
3105
|
+
/** The immutable configuration. */
|
|
3106
|
+
config;
|
|
3107
|
+
#transport;
|
|
3108
|
+
#ownsTransport;
|
|
3109
|
+
#tails = /* @__PURE__ */ new Set();
|
|
3110
|
+
#logClients = /* @__PURE__ */ new Set();
|
|
3111
|
+
#guard;
|
|
3112
|
+
#closed = false;
|
|
3113
|
+
#closing;
|
|
3114
|
+
/** Accepts a {@link LokiConfig} or plain options. */
|
|
3115
|
+
constructor(config = {}, internals = {}, shared) {
|
|
3116
|
+
const cfg = LokiConfig.from(config);
|
|
3117
|
+
this.config = cfg;
|
|
3118
|
+
this.#guard = new CardinalityGuard(cfg.allowedLabels);
|
|
3119
|
+
if (shared !== void 0) {
|
|
3120
|
+
this.#transport = shared.transport;
|
|
3121
|
+
this.#ownsTransport = false;
|
|
3122
|
+
} else {
|
|
3123
|
+
this.#transport = new HttpTransport({
|
|
3124
|
+
...internals,
|
|
3125
|
+
config: cfg,
|
|
3126
|
+
defaultHeaders: () => {
|
|
3127
|
+
const auth = cfg.authorizationHeader();
|
|
3128
|
+
return auth === void 0 ? {} : { authorization: auth };
|
|
3129
|
+
},
|
|
3130
|
+
knownSecrets: () => cfg.knownSecrets()
|
|
3131
|
+
});
|
|
3132
|
+
this.#ownsTransport = true;
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
/** Builds a client from `GROW_GRAFANA_LOKI_*` (and `LOKI_*`) environment variables. */
|
|
3136
|
+
static fromEnv(overrides = {}) {
|
|
3137
|
+
return new _LokiClient(LokiConfig.fromEnv(overrides));
|
|
3138
|
+
}
|
|
3139
|
+
/** The shared HTTP transport (for service modules). @internal */
|
|
3140
|
+
get transport() {
|
|
3141
|
+
return this.#transport;
|
|
3142
|
+
}
|
|
3143
|
+
/** The tenant this client sends as `X-Scope-OrgID`, if any. */
|
|
3144
|
+
get tenantId() {
|
|
3145
|
+
return this.config.tenantId;
|
|
3146
|
+
}
|
|
3147
|
+
/**
|
|
3148
|
+
* A client for another tenant: shares this client's connections, sends `X-Scope-OrgID: id`
|
|
3149
|
+
* on every request and on the tail handshake. This client is unchanged. Closing the child
|
|
3150
|
+
* does not close the shared connections. Throws `ValidationError` for an invalid id.
|
|
3151
|
+
*/
|
|
3152
|
+
withTenant(id) {
|
|
3153
|
+
const problem = tenantIdProblem(id, this.config.multiTenantQueries);
|
|
3154
|
+
if (problem !== void 0) throw new chunkVGAJJR3M_cjs.ValidationError(`withTenant: ${problem}`);
|
|
3155
|
+
return new _LokiClient(this.config.with({ tenantId: id }), {}, { transport: this.#transport });
|
|
3156
|
+
}
|
|
3157
|
+
#tenantHeaders() {
|
|
3158
|
+
return this.config.tenantId === void 0 ? {} : { [TENANT_HEADER]: this.config.tenantId };
|
|
3159
|
+
}
|
|
3160
|
+
async #request(options) {
|
|
3161
|
+
if (this.#closed) {
|
|
3162
|
+
throw new chunkVGAJJR3M_cjs.CancelledError(`${options.operation ?? options.path}: client is closed`);
|
|
3163
|
+
}
|
|
3164
|
+
try {
|
|
3165
|
+
return await this.#transport.request({
|
|
3166
|
+
...options,
|
|
3167
|
+
headers: { ...this.#tenantHeaders(), ...options.headers }
|
|
3168
|
+
});
|
|
3169
|
+
} catch (err) {
|
|
3170
|
+
throw mapLokiError(err);
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
async #getJson(path, operation, query, options, categorize = false) {
|
|
3174
|
+
const res = await this.#request({
|
|
3175
|
+
method: "GET",
|
|
3176
|
+
path,
|
|
3177
|
+
operation,
|
|
3178
|
+
query,
|
|
3179
|
+
...categorize ? { headers: { [ENCODING_FLAGS_HEADER]: "categorize-labels" } } : {},
|
|
3180
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
3181
|
+
});
|
|
3182
|
+
return res.data;
|
|
3183
|
+
}
|
|
3184
|
+
// ---------------------------------------------------------------- status
|
|
3185
|
+
/**
|
|
3186
|
+
* Readiness: `GET /ready`. `200 ready` → healthy `ok`; `503` → unhealthy with Loki's text
|
|
3187
|
+
* (e.g. `Ingester not ready: waiting for 15s after being ready`); network errors →
|
|
3188
|
+
* `unreachable`. Never throws except for `CANCELLED` and `CONFIG`.
|
|
3189
|
+
*/
|
|
3190
|
+
health(options = {}) {
|
|
3191
|
+
return probeHealth(async () => {
|
|
3192
|
+
try {
|
|
3193
|
+
await this.#request({
|
|
3194
|
+
method: "GET",
|
|
3195
|
+
path: "/ready",
|
|
3196
|
+
operation: "health",
|
|
3197
|
+
responseType: "text",
|
|
3198
|
+
idempotent: false,
|
|
3199
|
+
// report 503 at once instead of retrying it
|
|
3200
|
+
...options
|
|
3201
|
+
});
|
|
3202
|
+
return healthStatus("ok", {});
|
|
3203
|
+
} catch (err) {
|
|
3204
|
+
if (err instanceof chunkVGAJJR3M_cjs.LokiError && err.httpStatus === 503) {
|
|
3205
|
+
const text = /^health: (.*) \(HTTP 503\)$/.exec(err.message)?.[1] ?? "unhealthy";
|
|
3206
|
+
return healthStatus(text, { httpStatus: 503 }, false);
|
|
3207
|
+
}
|
|
3208
|
+
throw err;
|
|
3209
|
+
}
|
|
3210
|
+
});
|
|
3211
|
+
}
|
|
3212
|
+
/** `true` when `GET /ready` answers 200 (same probe as {@link health}). */
|
|
3213
|
+
async ready(options = {}) {
|
|
3214
|
+
return (await this.health(options)).healthy;
|
|
3215
|
+
}
|
|
3216
|
+
/**
|
|
3217
|
+
* Authenticated round trip: `GET /loki/api/v1/labels?since=5m` with auth and tenant headers.
|
|
3218
|
+
* Returns the latency in milliseconds; `AuthenticationError` without a tenant (multi-tenant
|
|
3219
|
+
* Loki) or with wrong gateway credentials.
|
|
3220
|
+
*/
|
|
3221
|
+
async ping(options = {}) {
|
|
3222
|
+
const start = performance.now();
|
|
3223
|
+
await this.#request({
|
|
3224
|
+
method: "GET",
|
|
3225
|
+
path: "/loki/api/v1/labels",
|
|
3226
|
+
query: { since: "5m" },
|
|
3227
|
+
operation: "ping",
|
|
3228
|
+
responseType: "none",
|
|
3229
|
+
...options
|
|
3230
|
+
});
|
|
3231
|
+
return performance.now() - start;
|
|
3232
|
+
}
|
|
3233
|
+
/** Build information: `GET /loki/api/v1/status/buildinfo`. */
|
|
3234
|
+
async buildInfo(options = {}) {
|
|
3235
|
+
return decodeBuildInfo(
|
|
3236
|
+
await this.#getJson("/loki/api/v1/status/buildinfo", "buildInfo", void 0, options)
|
|
3237
|
+
);
|
|
3238
|
+
}
|
|
3239
|
+
/** Server version (`buildInfo().version`, e.g. `"3.7.10"`). */
|
|
3240
|
+
async serverVersion(options = {}) {
|
|
3241
|
+
const info = await this.buildInfo(options);
|
|
3242
|
+
if (info.version === "") {
|
|
3243
|
+
throw new chunkVGAJJR3M_cjs.UnsupportedError("serverVersion: the service does not report a version");
|
|
3244
|
+
}
|
|
3245
|
+
return info.version;
|
|
3246
|
+
}
|
|
3247
|
+
// ------------------------------------------------------------------ push
|
|
3248
|
+
/**
|
|
3249
|
+
* Pushes streams with `POST /loki/api/v1/push`. JSON by default (optionally gzip);
|
|
3250
|
+
* `format: "protobuf"` sends a Snappy-compressed `PushRequest`. The cardinality guard moves
|
|
3251
|
+
* labels outside `config.allowedLabels` to every entry's structured metadata (unless
|
|
3252
|
+
* `config.disableLabelGuard`), then labels are validated client side. Entries without a
|
|
3253
|
+
* timestamp get "now". Retrying is safe: Loki drops entries identical to stored ones (same labels,
|
|
3254
|
+
* timestamp and line), so the push is marked idempotent and retried on 5xx and network
|
|
3255
|
+
* errors. Status 260 (ingestion blocked by the operator) throws a non-retryable error.
|
|
3256
|
+
*/
|
|
3257
|
+
async push(streams, options = {}) {
|
|
3258
|
+
const op = "push";
|
|
3259
|
+
const live = streams.filter((s) => s.entries.length > 0);
|
|
3260
|
+
if (live.length === 0) return;
|
|
3261
|
+
const now = /* @__PURE__ */ new Date();
|
|
3262
|
+
const guard = this.config.disableLabelGuard || options[SKIP_LABEL_GUARD] === true ? void 0 : this.#guard;
|
|
3263
|
+
const normalized = live.map((input) => {
|
|
3264
|
+
const s = guard === void 0 ? input : guard.apply(input);
|
|
3265
|
+
validateLabels(s.labels);
|
|
3266
|
+
return {
|
|
3267
|
+
labels: s.labels,
|
|
3268
|
+
entries: s.entries.map((e) => {
|
|
3269
|
+
if (typeof e.line !== "string") throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: line must be a string`);
|
|
3270
|
+
for (const [k, v] of Object.entries(e.structuredMetadata ?? {})) {
|
|
3271
|
+
if (k === "") {
|
|
3272
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: structured metadata name must not be empty`);
|
|
3273
|
+
}
|
|
3274
|
+
if (typeof v !== "string") {
|
|
3275
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: structured metadata ${k} must be a string`);
|
|
3276
|
+
}
|
|
3277
|
+
}
|
|
3278
|
+
return { ...e, timestamp: toNanos(e.timestamp ?? now, "timestamp") };
|
|
3279
|
+
})
|
|
3280
|
+
};
|
|
3281
|
+
});
|
|
3282
|
+
const format = options.format ?? "json";
|
|
3283
|
+
if (format !== "json" && format !== "protobuf") {
|
|
3284
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: unknown format ${format}`);
|
|
3285
|
+
}
|
|
3286
|
+
let body;
|
|
3287
|
+
const headers = {};
|
|
3288
|
+
if (format === "protobuf") {
|
|
3289
|
+
body = snappyCompress(encodePushRequest(normalized));
|
|
3290
|
+
headers["content-type"] = "application/x-protobuf";
|
|
3291
|
+
} else {
|
|
3292
|
+
body = JSON.stringify({
|
|
3293
|
+
streams: normalized.map((s) => ({
|
|
3294
|
+
stream: s.labels,
|
|
3295
|
+
values: s.entries.map(
|
|
3296
|
+
(e) => e.structuredMetadata !== void 0 && Object.keys(e.structuredMetadata).length > 0 ? [e.timestamp, e.line, e.structuredMetadata] : [e.timestamp, e.line]
|
|
3297
|
+
)
|
|
3298
|
+
}))
|
|
3299
|
+
});
|
|
3300
|
+
headers["content-type"] = "application/json";
|
|
3301
|
+
if (options.gzip === true) {
|
|
3302
|
+
body = zlib.gzipSync(body);
|
|
3303
|
+
headers["content-encoding"] = "gzip";
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
const res = await this.#request({
|
|
3307
|
+
method: "POST",
|
|
3308
|
+
path: "/loki/api/v1/push",
|
|
3309
|
+
operation: op,
|
|
3310
|
+
body,
|
|
3311
|
+
headers,
|
|
3312
|
+
idempotent: true,
|
|
3313
|
+
responseType: "none",
|
|
3314
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
3315
|
+
});
|
|
3316
|
+
if (res.status === 260) {
|
|
3317
|
+
throw new chunkVGAJJR3M_cjs.UnavailableError(
|
|
3318
|
+
`${op}: ingestion is blocked by the Loki administrator (HTTP 260)`,
|
|
3319
|
+
{
|
|
3320
|
+
httpStatus: 260,
|
|
3321
|
+
retryable: false
|
|
3322
|
+
}
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
/**
|
|
3327
|
+
* Pushes records as OTLP/JSON to `POST /otlp/v1/logs` (Loki's OTLP endpoint). Loki promotes
|
|
3328
|
+
* its default resource attributes (`service.name`, `deployment.environment`, …) to labels and
|
|
3329
|
+
* stores everything else as structured metadata.
|
|
3330
|
+
*/
|
|
3331
|
+
async pushOtlp(records, options = {}) {
|
|
3332
|
+
if (records.length === 0) return;
|
|
3333
|
+
let body = JSON.stringify(recordsToOtlpJson(records));
|
|
3334
|
+
const headers = { "content-type": "application/json" };
|
|
3335
|
+
if (options.gzip === true) {
|
|
3336
|
+
body = zlib.gzipSync(body);
|
|
3337
|
+
headers["content-encoding"] = "gzip";
|
|
3338
|
+
}
|
|
3339
|
+
try {
|
|
3340
|
+
await this.#request({
|
|
3341
|
+
method: "POST",
|
|
3342
|
+
path: "/otlp/v1/logs",
|
|
3343
|
+
operation: "pushOtlp",
|
|
3344
|
+
body,
|
|
3345
|
+
headers,
|
|
3346
|
+
idempotent: true,
|
|
3347
|
+
responseType: "none",
|
|
3348
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
3349
|
+
});
|
|
3350
|
+
} catch (err) {
|
|
3351
|
+
throw cleanRpcStatus(err);
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
// ----------------------------------------------------------------- query
|
|
3355
|
+
/**
|
|
3356
|
+
* Instant metric query: `GET /loki/api/v1/query`. A plain log selector (`{...}` with or
|
|
3357
|
+
* without a pipeline) is rejected with `ValidationError`, as Loki does not run log queries
|
|
3358
|
+
* as instant queries; use {@link queryRange} instead.
|
|
3359
|
+
*/
|
|
3360
|
+
async query(logql, options = {}) {
|
|
3361
|
+
checkQuery(logql, "query");
|
|
3362
|
+
if (logql.trim().startsWith("{")) {
|
|
3363
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(
|
|
3364
|
+
"query: log queries cannot run as instant queries; use queryRange or search"
|
|
3365
|
+
);
|
|
3366
|
+
}
|
|
3367
|
+
checkLimit(options.limit, "query");
|
|
3368
|
+
return decodeQueryResult(
|
|
3369
|
+
await this.#getJson(
|
|
3370
|
+
"/loki/api/v1/query",
|
|
3371
|
+
"query",
|
|
3372
|
+
{
|
|
3373
|
+
query: logql,
|
|
3374
|
+
time: optionalNanos(options.time, "time"),
|
|
3375
|
+
limit: options.limit,
|
|
3376
|
+
direction: options.direction
|
|
3377
|
+
},
|
|
3378
|
+
options,
|
|
3379
|
+
true
|
|
3380
|
+
)
|
|
3381
|
+
);
|
|
3382
|
+
}
|
|
3383
|
+
/** Range query (logs or metrics): `GET /loki/api/v1/query_range`. */
|
|
3384
|
+
async queryRange(logql, options = {}) {
|
|
3385
|
+
checkQuery(logql, "queryRange");
|
|
3386
|
+
checkLimit(options.limit, "queryRange", MAX_QUERY_LIMIT);
|
|
3387
|
+
return decodeQueryResult(
|
|
3388
|
+
await this.#getJson(
|
|
3389
|
+
"/loki/api/v1/query_range",
|
|
3390
|
+
"queryRange",
|
|
3391
|
+
{
|
|
3392
|
+
query: logql,
|
|
3393
|
+
start: optionalNanos(options.start, "start"),
|
|
3394
|
+
end: optionalNanos(options.end, "end"),
|
|
3395
|
+
since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs"),
|
|
3396
|
+
step: options.stepMs === void 0 ? void 0 : msToDuration(options.stepMs, "stepMs"),
|
|
3397
|
+
interval: options.intervalMs === void 0 ? void 0 : msToDuration(options.intervalMs, "intervalMs"),
|
|
3398
|
+
limit: options.limit,
|
|
3399
|
+
direction: options.direction
|
|
3400
|
+
},
|
|
3401
|
+
options,
|
|
3402
|
+
true
|
|
3403
|
+
)
|
|
3404
|
+
);
|
|
3405
|
+
}
|
|
3406
|
+
/** Label names: `GET /loki/api/v1/labels` (an empty result is `[]`). */
|
|
3407
|
+
async labels(options = {}) {
|
|
3408
|
+
return decodeStringList(
|
|
3409
|
+
await this.#getJson(
|
|
3410
|
+
"/loki/api/v1/labels",
|
|
3411
|
+
"labels",
|
|
3412
|
+
{
|
|
3413
|
+
start: optionalNanos(options.start, "start"),
|
|
3414
|
+
end: optionalNanos(options.end, "end"),
|
|
3415
|
+
since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs"),
|
|
3416
|
+
query: options.query
|
|
3417
|
+
},
|
|
3418
|
+
options
|
|
3419
|
+
)
|
|
3420
|
+
);
|
|
3421
|
+
}
|
|
3422
|
+
/**
|
|
3423
|
+
* Values of one label: `GET /loki/api/v1/label/{name}/values`. The name is validated client
|
|
3424
|
+
* side (Loki answers unknown and invalid names with an empty result).
|
|
3425
|
+
*/
|
|
3426
|
+
async labelValues(name, options = {}) {
|
|
3427
|
+
validateLabelName(name);
|
|
3428
|
+
return decodeStringList(
|
|
3429
|
+
await this.#getJson(
|
|
3430
|
+
`/loki/api/v1/label/${encodeURIComponent(name)}/values`,
|
|
3431
|
+
"labelValues",
|
|
3432
|
+
{
|
|
3433
|
+
start: optionalNanos(options.start, "start"),
|
|
3434
|
+
end: optionalNanos(options.end, "end"),
|
|
3435
|
+
since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs"),
|
|
3436
|
+
query: options.query
|
|
3437
|
+
},
|
|
3438
|
+
options
|
|
3439
|
+
)
|
|
3440
|
+
);
|
|
3441
|
+
}
|
|
3442
|
+
/** Series matching any of the selectors: `GET /loki/api/v1/series` (at least one matcher). */
|
|
3443
|
+
async series(matchers, options = {}) {
|
|
3444
|
+
const list = typeof matchers === "string" ? [matchers] : [...matchers];
|
|
3445
|
+
if (list.length === 0 || list.some((m) => m.trim() === "")) {
|
|
3446
|
+
throw new chunkVGAJJR3M_cjs.ValidationError("series: at least one non-empty matcher is required");
|
|
3447
|
+
}
|
|
3448
|
+
return decodeSeries(
|
|
3449
|
+
await this.#getJson(
|
|
3450
|
+
"/loki/api/v1/series",
|
|
3451
|
+
"series",
|
|
3452
|
+
{
|
|
3453
|
+
"match[]": list,
|
|
3454
|
+
start: optionalNanos(options.start, "start"),
|
|
3455
|
+
end: optionalNanos(options.end, "end"),
|
|
3456
|
+
since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs")
|
|
3457
|
+
},
|
|
3458
|
+
options
|
|
3459
|
+
)
|
|
3460
|
+
);
|
|
3461
|
+
}
|
|
3462
|
+
/**
|
|
3463
|
+
* Approximate index statistics: `GET /loki/api/v1/index/stats`. Reads the TSDB index only,
|
|
3464
|
+
* so data still in the ingester counts after the next chunk flush.
|
|
3465
|
+
*/
|
|
3466
|
+
async indexStats(query, options = {}) {
|
|
3467
|
+
checkQuery(query, "indexStats");
|
|
3468
|
+
return decodeIndexStats(
|
|
3469
|
+
await this.#getJson(
|
|
3470
|
+
"/loki/api/v1/index/stats",
|
|
3471
|
+
"indexStats",
|
|
3472
|
+
{
|
|
3473
|
+
query,
|
|
3474
|
+
start: optionalNanos(options.start, "start"),
|
|
3475
|
+
end: optionalNanos(options.end, "end")
|
|
3476
|
+
},
|
|
3477
|
+
options
|
|
3478
|
+
)
|
|
3479
|
+
);
|
|
3480
|
+
}
|
|
3481
|
+
#volumeQuery(query, options) {
|
|
3482
|
+
checkLimit(options.limit, "volume");
|
|
3483
|
+
return {
|
|
3484
|
+
query,
|
|
3485
|
+
start: optionalNanos(options.start, "start"),
|
|
3486
|
+
end: optionalNanos(options.end, "end"),
|
|
3487
|
+
limit: options.limit,
|
|
3488
|
+
targetLabels: options.targetLabels === void 0 || options.targetLabels.length === 0 ? void 0 : options.targetLabels.join(","),
|
|
3489
|
+
aggregateBy: options.aggregateBy
|
|
3490
|
+
};
|
|
3491
|
+
}
|
|
3492
|
+
/**
|
|
3493
|
+
* Ingested bytes per series or label: `GET /loki/api/v1/index/volume` (vector result).
|
|
3494
|
+
* Needs `limits_config.volume_enabled: true`; otherwise Loki returns an empty vector.
|
|
3495
|
+
*/
|
|
3496
|
+
async volume(query, options = {}) {
|
|
3497
|
+
checkQuery(query, "volume");
|
|
3498
|
+
return decodeQueryResult(
|
|
3499
|
+
await this.#getJson(
|
|
3500
|
+
"/loki/api/v1/index/volume",
|
|
3501
|
+
"volume",
|
|
3502
|
+
this.#volumeQuery(query, options),
|
|
3503
|
+
options
|
|
3504
|
+
)
|
|
3505
|
+
);
|
|
3506
|
+
}
|
|
3507
|
+
/**
|
|
3508
|
+
* Volume over time: `GET /loki/api/v1/index/volume_range`. Always a matrix: Loki answers
|
|
3509
|
+
* with a `vector` when every series has a single point, which is converted to one-sample
|
|
3510
|
+
* matrix series.
|
|
3511
|
+
*/
|
|
3512
|
+
async volumeRange(query, options = {}) {
|
|
3513
|
+
checkQuery(query, "volumeRange");
|
|
3514
|
+
return vectorToMatrix(
|
|
3515
|
+
decodeQueryResult(
|
|
3516
|
+
await this.#getJson(
|
|
3517
|
+
"/loki/api/v1/index/volume_range",
|
|
3518
|
+
"volumeRange",
|
|
3519
|
+
{
|
|
3520
|
+
...this.#volumeQuery(query, options),
|
|
3521
|
+
step: options.stepMs === void 0 ? void 0 : msToDuration(options.stepMs, "stepMs")
|
|
3522
|
+
},
|
|
3523
|
+
options
|
|
3524
|
+
)
|
|
3525
|
+
)
|
|
3526
|
+
);
|
|
3527
|
+
}
|
|
3528
|
+
/** Normalizes a LogQL query on the server (`GET /loki/api/v1/format_query`). */
|
|
3529
|
+
async formatQuery(logql, options = {}) {
|
|
3530
|
+
checkQuery(logql, "formatQuery");
|
|
3531
|
+
const body = await this.#getJson(
|
|
3532
|
+
"/loki/api/v1/format_query",
|
|
3533
|
+
"formatQuery",
|
|
3534
|
+
{ query: logql },
|
|
3535
|
+
options
|
|
3536
|
+
);
|
|
3537
|
+
const data = body?.data;
|
|
3538
|
+
if (typeof data !== "string") {
|
|
3539
|
+
throw new chunkVGAJJR3M_cjs.UnavailableError("formatQuery: unexpected response", { retryable: false });
|
|
3540
|
+
}
|
|
3541
|
+
return data;
|
|
3542
|
+
}
|
|
3543
|
+
/**
|
|
3544
|
+
* Live tail over WebSocket (`/loki/api/v1/tail`). Resolves once connected; handshake errors
|
|
3545
|
+
* reject (`AuthenticationError`, `ValidationError`, …). `onEntries` receives the streams of
|
|
3546
|
+
* every frame; dropped entries go to `onDropped`, later errors to `onError`. Only log queries
|
|
3547
|
+
* (starting with `{`) are allowed. Stop with `handle.stop()` or `close()`.
|
|
3548
|
+
* Proxies are not used for the WebSocket.
|
|
3549
|
+
*/
|
|
3550
|
+
async tail(logql, onEntries, options = {}) {
|
|
3551
|
+
const op = "tail";
|
|
3552
|
+
checkQuery(logql, op);
|
|
3553
|
+
if (!logql.trim().startsWith("{")) {
|
|
3554
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: only log queries (starting with a selector) can be tailed`);
|
|
3555
|
+
}
|
|
3556
|
+
checkLimit(options.limit, op);
|
|
3557
|
+
let delayFor;
|
|
3558
|
+
if (options.delayForMs !== void 0) {
|
|
3559
|
+
delayFor = Math.round(options.delayForMs / 1e3);
|
|
3560
|
+
if (!Number.isFinite(delayFor) || delayFor < 0 || delayFor > 5) {
|
|
3561
|
+
throw new chunkVGAJJR3M_cjs.ValidationError(`${op}: delayForMs must be between 0 and 5000`);
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3564
|
+
if (this.#closed || this.#transport.closed) {
|
|
3565
|
+
throw new chunkVGAJJR3M_cjs.CancelledError(`${op}: client is closed`);
|
|
3566
|
+
}
|
|
3567
|
+
const url = this.#transport.buildUrl("/loki/api/v1/tail", {
|
|
3568
|
+
query: logql,
|
|
3569
|
+
start: optionalNanos(options.start ?? /* @__PURE__ */ new Date(), "start"),
|
|
3570
|
+
limit: options.limit,
|
|
3571
|
+
delay_for: delayFor
|
|
3572
|
+
});
|
|
3573
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
3574
|
+
const headers = {};
|
|
3575
|
+
const auth = this.config.authorizationHeader();
|
|
3576
|
+
for (const [k, v] of Object.entries({
|
|
3577
|
+
...this.config.headers,
|
|
3578
|
+
...auth === void 0 ? {} : { authorization: auth },
|
|
3579
|
+
...this.#tenantHeaders(),
|
|
3580
|
+
[ENCODING_FLAGS_HEADER]: "categorize-labels",
|
|
3581
|
+
"user-agent": this.#transport.userAgent
|
|
3582
|
+
})) {
|
|
3583
|
+
headers[k.toLowerCase()] = v;
|
|
3584
|
+
}
|
|
3585
|
+
const handle = await openTail(
|
|
3586
|
+
{
|
|
3587
|
+
url,
|
|
3588
|
+
headers,
|
|
3589
|
+
tls: this.config.tls,
|
|
3590
|
+
connectTimeoutMs: this.config.connectTimeoutMs,
|
|
3591
|
+
...options.signal === void 0 ? {} : { signal: options.signal },
|
|
3592
|
+
redact: (t) => this.#transport.redact(t)
|
|
3593
|
+
},
|
|
3594
|
+
(frame) => {
|
|
3595
|
+
onEntries(frame.streams, frame);
|
|
3596
|
+
},
|
|
3597
|
+
{
|
|
3598
|
+
...options.onDropped === void 0 ? {} : { onDropped: options.onDropped },
|
|
3599
|
+
...options.onError === void 0 ? {} : { onError: options.onError }
|
|
3600
|
+
}
|
|
3601
|
+
);
|
|
3602
|
+
this.#tails.add(handle);
|
|
3603
|
+
void handle.closed.then(() => this.#tails.delete(handle));
|
|
3604
|
+
return handle;
|
|
3605
|
+
}
|
|
3606
|
+
// --------------------------------------------------------------- logging
|
|
3607
|
+
/**
|
|
3608
|
+
* A batching {@link LogClient} that writes to this Loki (and tenant). Records go through
|
|
3609
|
+
* redaction and the cardinality guard; `protocol: "otlp"` uses `/otlp/v1/logs` instead.
|
|
3610
|
+
* {@link close} flushes and closes every log client created here.
|
|
3611
|
+
*/
|
|
3612
|
+
logClient(options = {}) {
|
|
3613
|
+
const { protocol, allowedLabels, ...batching } = options;
|
|
3614
|
+
const exporter = protocol === "otlp" ? new LokiOtlpExporter(this) : new LokiLogExporter(this, {
|
|
3615
|
+
format: protocol ?? "json",
|
|
3616
|
+
allowedLabels: allowedLabels ?? this.#guard.allowed
|
|
3617
|
+
});
|
|
3618
|
+
const client = new BatchingLogClient(exporter, batching);
|
|
3619
|
+
this.#logClients.add(client);
|
|
3620
|
+
return client;
|
|
3621
|
+
}
|
|
3622
|
+
/** A {@link LogQueryClient} (search, tail, listStreams, listLabels, waitForLog) on this Loki. */
|
|
3623
|
+
logQueryClient() {
|
|
3624
|
+
return new LokiLogQueryClient(this);
|
|
3625
|
+
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Flushes and closes log clients created by {@link logClient}, stops open tails and releases
|
|
3628
|
+
* connections (children from {@link withTenant} leave the shared connections open).
|
|
3629
|
+
* Idempotent.
|
|
3630
|
+
*/
|
|
3631
|
+
close() {
|
|
3632
|
+
this.#closing ??= this.#shutdown();
|
|
3633
|
+
return this.#closing;
|
|
3634
|
+
}
|
|
3635
|
+
async #shutdown() {
|
|
3636
|
+
await Promise.allSettled([...this.#logClients].map((c) => c.close()));
|
|
3637
|
+
this.#logClients.clear();
|
|
3638
|
+
this.#closed = true;
|
|
3639
|
+
for (const t of this.#tails) t.stop();
|
|
3640
|
+
this.#tails.clear();
|
|
3641
|
+
if (this.#ownsTransport) await this.#transport.close();
|
|
3642
|
+
}
|
|
3643
|
+
};
|
|
3644
|
+
|
|
3645
|
+
Object.defineProperty(exports, "AuthenticationError", {
|
|
3646
|
+
enumerable: true,
|
|
3647
|
+
get: function () { return chunkVGAJJR3M_cjs.AuthenticationError; }
|
|
3648
|
+
});
|
|
3649
|
+
Object.defineProperty(exports, "BaseLogQueryClient", {
|
|
3650
|
+
enumerable: true,
|
|
3651
|
+
get: function () { return chunkVGAJJR3M_cjs.BaseLogQueryClient; }
|
|
3652
|
+
});
|
|
3653
|
+
Object.defineProperty(exports, "CancelledError", {
|
|
3654
|
+
enumerable: true,
|
|
3655
|
+
get: function () { return chunkVGAJJR3M_cjs.CancelledError; }
|
|
3656
|
+
});
|
|
3657
|
+
Object.defineProperty(exports, "ConfigError", {
|
|
3658
|
+
enumerable: true,
|
|
3659
|
+
get: function () { return chunkVGAJJR3M_cjs.ConfigError; }
|
|
3660
|
+
});
|
|
3661
|
+
Object.defineProperty(exports, "ConflictError", {
|
|
3662
|
+
enumerable: true,
|
|
3663
|
+
get: function () { return chunkVGAJJR3M_cjs.ConflictError; }
|
|
3664
|
+
});
|
|
3665
|
+
Object.defineProperty(exports, "ErrorCode", {
|
|
3666
|
+
enumerable: true,
|
|
3667
|
+
get: function () { return chunkVGAJJR3M_cjs.ErrorCode; }
|
|
3668
|
+
});
|
|
3669
|
+
Object.defineProperty(exports, "LokiError", {
|
|
3670
|
+
enumerable: true,
|
|
3671
|
+
get: function () { return chunkVGAJJR3M_cjs.LokiError; }
|
|
3672
|
+
});
|
|
3673
|
+
Object.defineProperty(exports, "NotFoundError", {
|
|
3674
|
+
enumerable: true,
|
|
3675
|
+
get: function () { return chunkVGAJJR3M_cjs.NotFoundError; }
|
|
3676
|
+
});
|
|
3677
|
+
Object.defineProperty(exports, "PermissionDeniedError", {
|
|
3678
|
+
enumerable: true,
|
|
3679
|
+
get: function () { return chunkVGAJJR3M_cjs.PermissionDeniedError; }
|
|
3680
|
+
});
|
|
3681
|
+
Object.defineProperty(exports, "RateLimitError", {
|
|
3682
|
+
enumerable: true,
|
|
3683
|
+
get: function () { return chunkVGAJJR3M_cjs.RateLimitError; }
|
|
3684
|
+
});
|
|
3685
|
+
Object.defineProperty(exports, "Severity", {
|
|
3686
|
+
enumerable: true,
|
|
3687
|
+
get: function () { return chunkVGAJJR3M_cjs.Severity; }
|
|
3688
|
+
});
|
|
3689
|
+
Object.defineProperty(exports, "TimeoutError", {
|
|
3690
|
+
enumerable: true,
|
|
3691
|
+
get: function () { return chunkVGAJJR3M_cjs.TimeoutError; }
|
|
3692
|
+
});
|
|
3693
|
+
Object.defineProperty(exports, "UnavailableError", {
|
|
3694
|
+
enumerable: true,
|
|
3695
|
+
get: function () { return chunkVGAJJR3M_cjs.UnavailableError; }
|
|
3696
|
+
});
|
|
3697
|
+
Object.defineProperty(exports, "UnsupportedError", {
|
|
3698
|
+
enumerable: true,
|
|
3699
|
+
get: function () { return chunkVGAJJR3M_cjs.UnsupportedError; }
|
|
3700
|
+
});
|
|
3701
|
+
Object.defineProperty(exports, "UnsupportedLogQueryClient", {
|
|
3702
|
+
enumerable: true,
|
|
3703
|
+
get: function () { return chunkVGAJJR3M_cjs.UnsupportedLogQueryClient; }
|
|
3704
|
+
});
|
|
3705
|
+
Object.defineProperty(exports, "ValidationError", {
|
|
3706
|
+
enumerable: true,
|
|
3707
|
+
get: function () { return chunkVGAJJR3M_cjs.ValidationError; }
|
|
3708
|
+
});
|
|
3709
|
+
Object.defineProperty(exports, "canonicalSeverity", {
|
|
3710
|
+
enumerable: true,
|
|
3711
|
+
get: function () { return chunkVGAJJR3M_cjs.canonicalSeverity; }
|
|
3712
|
+
});
|
|
3713
|
+
Object.defineProperty(exports, "codeForStatus", {
|
|
3714
|
+
enumerable: true,
|
|
3715
|
+
get: function () { return chunkVGAJJR3M_cjs.codeForStatus; }
|
|
3716
|
+
});
|
|
3717
|
+
Object.defineProperty(exports, "errorForCode", {
|
|
3718
|
+
enumerable: true,
|
|
3719
|
+
get: function () { return chunkVGAJJR3M_cjs.errorForCode; }
|
|
3720
|
+
});
|
|
3721
|
+
Object.defineProperty(exports, "errorForStatus", {
|
|
3722
|
+
enumerable: true,
|
|
3723
|
+
get: function () { return chunkVGAJJR3M_cjs.errorForStatus; }
|
|
3724
|
+
});
|
|
3725
|
+
Object.defineProperty(exports, "isLokiError", {
|
|
3726
|
+
enumerable: true,
|
|
3727
|
+
get: function () { return chunkVGAJJR3M_cjs.isLokiError; }
|
|
3728
|
+
});
|
|
3729
|
+
Object.defineProperty(exports, "logRecordByteSize", {
|
|
3730
|
+
enumerable: true,
|
|
3731
|
+
get: function () { return chunkVGAJJR3M_cjs.logRecordByteSize; }
|
|
3732
|
+
});
|
|
3733
|
+
Object.defineProperty(exports, "logRecordFromJson", {
|
|
3734
|
+
enumerable: true,
|
|
3735
|
+
get: function () { return chunkVGAJJR3M_cjs.logRecordFromJson; }
|
|
3736
|
+
});
|
|
3737
|
+
Object.defineProperty(exports, "logRecordToJson", {
|
|
3738
|
+
enumerable: true,
|
|
3739
|
+
get: function () { return chunkVGAJJR3M_cjs.logRecordToJson; }
|
|
3740
|
+
});
|
|
3741
|
+
Object.defineProperty(exports, "parseLogRecord", {
|
|
3742
|
+
enumerable: true,
|
|
3743
|
+
get: function () { return chunkVGAJJR3M_cjs.parseLogRecord; }
|
|
3744
|
+
});
|
|
3745
|
+
Object.defineProperty(exports, "parseSeverity", {
|
|
3746
|
+
enumerable: true,
|
|
3747
|
+
get: function () { return chunkVGAJJR3M_cjs.parseSeverity; }
|
|
3748
|
+
});
|
|
3749
|
+
Object.defineProperty(exports, "pollTail", {
|
|
3750
|
+
enumerable: true,
|
|
3751
|
+
get: function () { return chunkVGAJJR3M_cjs.pollTail; }
|
|
3752
|
+
});
|
|
3753
|
+
Object.defineProperty(exports, "pollUntil", {
|
|
3754
|
+
enumerable: true,
|
|
3755
|
+
get: function () { return chunkVGAJJR3M_cjs.pollUntil; }
|
|
3756
|
+
});
|
|
3757
|
+
Object.defineProperty(exports, "reasonForCode", {
|
|
3758
|
+
enumerable: true,
|
|
3759
|
+
get: function () { return chunkVGAJJR3M_cjs.reasonForCode; }
|
|
3760
|
+
});
|
|
3761
|
+
Object.defineProperty(exports, "serializeLogRecord", {
|
|
3762
|
+
enumerable: true,
|
|
3763
|
+
get: function () { return chunkVGAJJR3M_cjs.serializeLogRecord; }
|
|
3764
|
+
});
|
|
3765
|
+
Object.defineProperty(exports, "severityText", {
|
|
3766
|
+
enumerable: true,
|
|
3767
|
+
get: function () { return chunkVGAJJR3M_cjs.severityText; }
|
|
3768
|
+
});
|
|
3769
|
+
Object.defineProperty(exports, "sleep", {
|
|
3770
|
+
enumerable: true,
|
|
3771
|
+
get: function () { return chunkVGAJJR3M_cjs.sleep; }
|
|
3772
|
+
});
|
|
3773
|
+
Object.defineProperty(exports, "throwIfAborted", {
|
|
3774
|
+
enumerable: true,
|
|
3775
|
+
get: function () { return chunkVGAJJR3M_cjs.throwIfAborted; }
|
|
3776
|
+
});
|
|
3777
|
+
Object.defineProperty(exports, "toAttrValue", {
|
|
3778
|
+
enumerable: true,
|
|
3779
|
+
get: function () { return chunkVGAJJR3M_cjs.toAttrValue; }
|
|
3780
|
+
});
|
|
3781
|
+
Object.defineProperty(exports, "toAttributes", {
|
|
3782
|
+
enumerable: true,
|
|
3783
|
+
get: function () { return chunkVGAJJR3M_cjs.toAttributes; }
|
|
3784
|
+
});
|
|
3785
|
+
Object.defineProperty(exports, "waitForLog", {
|
|
3786
|
+
enumerable: true,
|
|
3787
|
+
get: function () { return chunkVGAJJR3M_cjs.waitForLog; }
|
|
3788
|
+
});
|
|
3789
|
+
exports.ALL_STREAMS_SELECTOR = ALL_STREAMS_SELECTOR;
|
|
3790
|
+
exports.BatchProcessor = BatchProcessor;
|
|
3791
|
+
exports.BatchingLogClient = BatchingLogClient;
|
|
3792
|
+
exports.CardinalityGuard = CardinalityGuard;
|
|
3793
|
+
exports.DEFAULT_ALLOWED_LABELS = DEFAULT_ALLOWED_LABELS;
|
|
3794
|
+
exports.DEFAULT_BATCH_OPTIONS = DEFAULT_BATCH_OPTIONS;
|
|
3795
|
+
exports.DEFAULT_REDACT_KEYS = DEFAULT_REDACT_KEYS;
|
|
3796
|
+
exports.DEFAULT_REQUEST_ID_HEADERS = DEFAULT_REQUEST_ID_HEADERS;
|
|
3797
|
+
exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS;
|
|
3798
|
+
exports.ENCODING_FLAGS_HEADER = ENCODING_FLAGS_HEADER;
|
|
3799
|
+
exports.EnvReader = EnvReader;
|
|
3800
|
+
exports.HttpTransport = HttpTransport;
|
|
3801
|
+
exports.LABEL_NAME_PATTERN = LABEL_NAME_PATTERN;
|
|
3802
|
+
exports.LANGUAGE = LANGUAGE;
|
|
3803
|
+
exports.LogQL = LogQL;
|
|
3804
|
+
exports.Logger = Logger;
|
|
3805
|
+
exports.LokiClient = LokiClient;
|
|
3806
|
+
exports.LokiConfig = LokiConfig;
|
|
3807
|
+
exports.LokiLogExporter = LokiLogExporter;
|
|
3808
|
+
exports.LokiLogQueryClient = LokiLogQueryClient;
|
|
3809
|
+
exports.LokiOtlpExporter = LokiOtlpExporter;
|
|
3810
|
+
exports.MAX_QUERY_LIMIT = MAX_QUERY_LIMIT;
|
|
3811
|
+
exports.MAX_TENANT_ID_LENGTH = MAX_TENANT_ID_LENGTH;
|
|
3812
|
+
exports.MAX_VENDOR_TEXT = MAX_VENDOR_TEXT;
|
|
3813
|
+
exports.MIN_SECRET_LENGTH = MIN_SECRET_LENGTH;
|
|
3814
|
+
exports.OTLP_SCOPE_NAME = OTLP_SCOPE_NAME;
|
|
3815
|
+
exports.PACKAGE_KEY = PACKAGE_KEY;
|
|
3816
|
+
exports.REDACTED = REDACTED;
|
|
3817
|
+
exports.RESERVED_METADATA_KEYS = RESERVED_METADATA_KEYS;
|
|
3818
|
+
exports.RedactionProcessor = RedactionProcessor;
|
|
3819
|
+
exports.RetryPolicy = RetryPolicy;
|
|
3820
|
+
exports.SDK_KIT_VERSION = SDK_KIT_VERSION;
|
|
3821
|
+
exports.SDK_VERSION = SDK_VERSION;
|
|
3822
|
+
exports.SENSITIVE_FIELD_PARTS = SENSITIVE_FIELD_PARTS;
|
|
3823
|
+
exports.Secret = Secret;
|
|
3824
|
+
exports.TENANT_HEADER = TENANT_HEADER;
|
|
3825
|
+
exports.VENDOR_ENV = VENDOR_ENV;
|
|
3826
|
+
exports.WinstonTransport = WinstonTransport;
|
|
3827
|
+
exports.attrToString = attrToString;
|
|
3828
|
+
exports.createDispatcher = createDispatcher;
|
|
3829
|
+
exports.createPinoTransport = createPinoTransport;
|
|
3830
|
+
exports.dateToNanos = dateToNanos;
|
|
3831
|
+
exports.decodeBuildInfo = decodeBuildInfo;
|
|
3832
|
+
exports.decodeCursor = decodeCursor;
|
|
3833
|
+
exports.decodeEntry = decodeEntry;
|
|
3834
|
+
exports.decodeIndexStats = decodeIndexStats;
|
|
3835
|
+
exports.decodeQueryResult = decodeQueryResult;
|
|
3836
|
+
exports.decodeRpcStatusMessage = decodeRpcStatusMessage;
|
|
3837
|
+
exports.decodeSeries = decodeSeries;
|
|
3838
|
+
exports.decodeStreams = decodeStreams;
|
|
3839
|
+
exports.decodeStringList = decodeStringList;
|
|
3840
|
+
exports.decodeTailFrame = decodeTailFrame;
|
|
3841
|
+
exports.definedOnly = definedOnly;
|
|
3842
|
+
exports.describeCommonConfig = describeCommonConfig;
|
|
3843
|
+
exports.encodeCursor = encodeCursor;
|
|
3844
|
+
exports.encodePushRequest = encodePushRequest;
|
|
3845
|
+
exports.entryToLogRecord = entryToLogRecord;
|
|
3846
|
+
exports.formatLabelSet = formatLabelSet;
|
|
3847
|
+
exports.healthStatus = healthStatus;
|
|
3848
|
+
exports.isHealthyWord = isHealthyWord;
|
|
3849
|
+
exports.isIdempotentMethod = isIdempotentMethod;
|
|
3850
|
+
exports.isRetryableStatus = isRetryableStatus;
|
|
3851
|
+
exports.isSensitiveField = isSensitiveField;
|
|
3852
|
+
exports.isSensitiveHeader = isSensitiveHeader;
|
|
3853
|
+
exports.isValidLabelName = isValidLabelName;
|
|
3854
|
+
exports.mergeOptions = mergeOptions;
|
|
3855
|
+
exports.mergeStreams = mergeStreams;
|
|
3856
|
+
exports.msToDuration = msToDuration;
|
|
3857
|
+
exports.nanosToDate = nanosToDate;
|
|
3858
|
+
exports.normalizeLabelName = normalizeLabelName;
|
|
3859
|
+
exports.optionalNanos = optionalNanos;
|
|
3860
|
+
exports.parseBool = parseBool;
|
|
3861
|
+
exports.parseDuration = parseDuration;
|
|
3862
|
+
exports.parseInteger = parseInteger;
|
|
3863
|
+
exports.parseRetryAfter = parseRetryAfter;
|
|
3864
|
+
exports.pinoLevelToSeverity = pinoLevelToSeverity;
|
|
3865
|
+
exports.pinoLineToRecord = pinoLineToRecord;
|
|
3866
|
+
exports.probeHealth = probeHealth;
|
|
3867
|
+
exports.quoteLogQL = quoteLogQL;
|
|
3868
|
+
exports.readCommonEnv = readCommonEnv;
|
|
3869
|
+
exports.recordsToOtlpJson = recordsToOtlpJson;
|
|
3870
|
+
exports.recordsToStreams = recordsToStreams;
|
|
3871
|
+
exports.redactError = redactError;
|
|
3872
|
+
exports.redactFields = redactFields;
|
|
3873
|
+
exports.redactHeaders = redactHeaders;
|
|
3874
|
+
exports.redactSecretsInText = redactSecretsInText;
|
|
3875
|
+
exports.redactText = redactText;
|
|
3876
|
+
exports.redactUrl = redactUrl;
|
|
3877
|
+
exports.resolveBatchOptions = resolveBatchOptions;
|
|
3878
|
+
exports.resolveCommonConfig = resolveCommonConfig;
|
|
3879
|
+
exports.safeCall = safeCall;
|
|
3880
|
+
exports.safeLogger = safeLogger;
|
|
3881
|
+
exports.secondsToDate = secondsToDate;
|
|
3882
|
+
exports.secretValues = secretValues;
|
|
3883
|
+
exports.silentLogger = silentLogger;
|
|
3884
|
+
exports.snappyCompress = snappyCompress;
|
|
3885
|
+
exports.stringMap = stringMap;
|
|
3886
|
+
exports.tenantIdProblem = tenantIdProblem;
|
|
3887
|
+
exports.toNanos = toNanos;
|
|
3888
|
+
exports.toOtlpValue = toOtlpValue;
|
|
3889
|
+
exports.toSearchLogQL = toSearchLogQL;
|
|
3890
|
+
exports.validateCommonConfig = validateCommonConfig;
|
|
3891
|
+
exports.validateLabelName = validateLabelName;
|
|
3892
|
+
exports.validateLabels = validateLabels;
|
|
3893
|
+
exports.winstonLevelToSeverity = winstonLevelToSeverity;
|
|
3894
|
+
//# sourceMappingURL=index.cjs.map
|
|
3895
|
+
//# sourceMappingURL=index.cjs.map
|