@lark-apaas/client-toolkit 1.2.82-beta.1 → 1.2.83-alpha.20261106060351
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.
|
@@ -20,54 +20,49 @@ interface BatchLoggerConfig {
|
|
|
20
20
|
}
|
|
21
21
|
export declare class BatchLogger {
|
|
22
22
|
private config;
|
|
23
|
-
private
|
|
23
|
+
private pendingQueue;
|
|
24
|
+
private activeBatch;
|
|
24
25
|
private flushTimer;
|
|
25
|
-
private
|
|
26
|
+
private processingPromise;
|
|
27
|
+
private retainedNormalBytes;
|
|
28
|
+
private retainedNormalEntries;
|
|
29
|
+
private overflowRecord;
|
|
30
|
+
private nextSequence;
|
|
26
31
|
private originConsole;
|
|
27
32
|
constructor(console: Console, config?: BatchLoggerConfig);
|
|
28
|
-
/**
|
|
29
|
-
* 批量记录日志(对外暴露的唯一方法)
|
|
30
|
-
*/
|
|
33
|
+
/** 批量记录日志(对外暴露的唯一方法) */
|
|
31
34
|
batchLog(level: string, message: string, source?: string): void;
|
|
32
|
-
/**
|
|
33
|
-
* 刷新日志队列,全部发送
|
|
34
|
-
*/
|
|
35
|
+
/** Flushes all currently retained work, split by count and exact wire size. */
|
|
35
36
|
flush(): Promise<void>;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
private
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
37
|
+
private drainQueue;
|
|
38
|
+
private prepareNextBatch;
|
|
39
|
+
private replaceOversizedLog;
|
|
40
|
+
private sendPreparedBatch;
|
|
41
|
+
private handlePayloadTooLarge;
|
|
42
|
+
private replaceSingle413WithSurrogate;
|
|
43
|
+
private executeBatch;
|
|
44
|
+
private isRetryable;
|
|
45
|
+
private recordOverflow;
|
|
46
|
+
private mergeOverflow;
|
|
47
|
+
private emitImmediateOverflow;
|
|
48
|
+
private createDiagnosticRequest;
|
|
49
|
+
private replaceRetainedRequest;
|
|
50
|
+
private emitBatchTerminal;
|
|
51
|
+
private emitLossSignal;
|
|
52
|
+
private releaseLogs;
|
|
53
|
+
private batchSizeThreshold;
|
|
54
|
+
/** 执行实际的fetch请求 */
|
|
43
55
|
private execFetch;
|
|
44
|
-
/**
|
|
45
|
-
* 启动自动刷新定时器
|
|
46
|
-
*/
|
|
56
|
+
/** 启动自动刷新定时器 */
|
|
47
57
|
private startFlushTimer;
|
|
48
|
-
/**
|
|
49
|
-
* 设置页面卸载时的处理
|
|
50
|
-
*/
|
|
58
|
+
/** 设置页面卸载时的处理 */
|
|
51
59
|
private setupBeforeUnloadHandler;
|
|
52
|
-
/**
|
|
53
|
-
* 延迟函数
|
|
54
|
-
*/
|
|
55
60
|
private delay;
|
|
56
|
-
/**
|
|
57
|
-
* 生成唯一ID
|
|
58
|
-
*/
|
|
59
61
|
private generateId;
|
|
60
|
-
/**
|
|
61
|
-
* 销毁资源
|
|
62
|
-
*/
|
|
62
|
+
/** 销毁资源并发送剩余日志。 */
|
|
63
63
|
destroy(): Promise<void>;
|
|
64
|
-
/**
|
|
65
|
-
* 获取队列大小
|
|
66
|
-
*/
|
|
64
|
+
/** Returns the number of queued (not currently active) retained records. */
|
|
67
65
|
getQueueSize(): number;
|
|
68
|
-
/**
|
|
69
|
-
* 更新配置
|
|
70
|
-
*/
|
|
71
66
|
updateConfig(newConfig: Partial<BatchLoggerConfig>): void;
|
|
72
67
|
}
|
|
73
68
|
export declare function getBatchLogger(): BatchLogger;
|
|
@@ -1,14 +1,36 @@
|
|
|
1
|
+
import { LOG_MAX_413_CANONICAL_ATTEMPTS, LOG_NORMAL_RETAINED_MAX_BYTES, LOG_NORMAL_RETAINED_MAX_ENTRIES, LOG_OVERFLOW_RESERVED_BYTES, LOG_REQUEST_BODY_MAX_BYTES, boundedCanonicalJsonFingerprint, boundedUtf8Preview, jsonArrayUtf8Bytes, jsonValueUtf8Bytes, serializeJson, sha256Utf8, utf8ByteLength } from "./log-payload-budget.js";
|
|
2
|
+
const LOSS_SCHEMA = 'batch-logger-loss-v1';
|
|
3
|
+
const LOSS_PREVIEW_MAX_BYTES = 1024;
|
|
4
|
+
const DIAGNOSTIC_IDENTITY_MAX_BYTES = 512;
|
|
5
|
+
function retainedBudgetBytes(requestBytes) {
|
|
6
|
+
return requestBytes + 2;
|
|
7
|
+
}
|
|
8
|
+
function finiteNonNegativeInteger(value) {
|
|
9
|
+
return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
10
|
+
}
|
|
11
|
+
function finiteNonNegativeNumber(value) {
|
|
12
|
+
return Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
13
|
+
}
|
|
14
|
+
function boundedSafeIntegerSum(left, right) {
|
|
15
|
+
return Math.min(Number.MAX_SAFE_INTEGER, left + right);
|
|
16
|
+
}
|
|
1
17
|
class BatchLogger {
|
|
2
18
|
config;
|
|
3
|
-
|
|
19
|
+
pendingQueue = [];
|
|
20
|
+
activeBatch = [];
|
|
4
21
|
flushTimer = null;
|
|
5
|
-
|
|
22
|
+
processingPromise = null;
|
|
23
|
+
retainedNormalBytes = 0;
|
|
24
|
+
retainedNormalEntries = 0;
|
|
25
|
+
overflowRecord = null;
|
|
26
|
+
nextSequence = 0;
|
|
6
27
|
originConsole;
|
|
7
28
|
constructor(console1, config){
|
|
8
29
|
this.originConsole = {
|
|
9
30
|
...console1
|
|
10
31
|
};
|
|
11
|
-
const
|
|
32
|
+
const browserContext = 'undefined' == typeof window ? {} : window;
|
|
33
|
+
const { userId = '', tenantId = '', appId = '' } = browserContext;
|
|
12
34
|
this.config = {
|
|
13
35
|
userId,
|
|
14
36
|
tenantId,
|
|
@@ -27,60 +49,449 @@ class BatchLogger {
|
|
|
27
49
|
this.setupBeforeUnloadHandler();
|
|
28
50
|
}
|
|
29
51
|
batchLog(level, message, source) {
|
|
30
|
-
const
|
|
31
|
-
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
const id = this.generateId();
|
|
54
|
+
const sequence = this.nextSequence++;
|
|
55
|
+
const request = {
|
|
32
56
|
level,
|
|
33
57
|
message,
|
|
58
|
+
time: new Date(now).toISOString(),
|
|
34
59
|
source,
|
|
35
|
-
|
|
60
|
+
user_id: this.config.userId,
|
|
61
|
+
tenant_id: this.config.tenantId,
|
|
62
|
+
app_id: this.config.appId
|
|
63
|
+
};
|
|
64
|
+
const requestBytes = jsonValueUtf8Bytes(request);
|
|
65
|
+
const budgetBytes = retainedBudgetBytes(requestBytes);
|
|
66
|
+
if (this.overflowRecord?.overflowState?.sealed === false) return void this.mergeOverflow(this.overflowRecord, id, sequence, message, requestBytes, now);
|
|
67
|
+
const fitsNormalBudget = this.retainedNormalEntries < LOG_NORMAL_RETAINED_MAX_ENTRIES && this.retainedNormalBytes + budgetBytes <= LOG_NORMAL_RETAINED_MAX_BYTES;
|
|
68
|
+
if (!fitsNormalBudget) return void this.recordOverflow(id, sequence, message, requestBytes, now);
|
|
69
|
+
const retained = {
|
|
70
|
+
id,
|
|
71
|
+
sequence,
|
|
72
|
+
request,
|
|
73
|
+
requestBytes,
|
|
74
|
+
budgetBytes,
|
|
75
|
+
budgetClass: 'normal',
|
|
76
|
+
kind: 'normal',
|
|
77
|
+
released: false
|
|
36
78
|
};
|
|
37
|
-
this.
|
|
38
|
-
|
|
79
|
+
this.retainedNormalEntries += 1;
|
|
80
|
+
this.retainedNormalBytes += budgetBytes;
|
|
81
|
+
this.pendingQueue.push(retained);
|
|
82
|
+
if (this.pendingQueue.length >= this.batchSizeThreshold()) this.flush();
|
|
83
|
+
}
|
|
84
|
+
flush() {
|
|
85
|
+
if (this.processingPromise) return this.processingPromise;
|
|
86
|
+
if (0 === this.pendingQueue.length) return Promise.resolve();
|
|
87
|
+
const processing = this.drainQueue();
|
|
88
|
+
this.processingPromise = processing.finally(()=>{
|
|
89
|
+
this.processingPromise = null;
|
|
90
|
+
});
|
|
91
|
+
return this.processingPromise;
|
|
92
|
+
}
|
|
93
|
+
async drainQueue() {
|
|
94
|
+
while(this.pendingQueue.length > 0){
|
|
95
|
+
const prepared = await this.prepareNextBatch();
|
|
96
|
+
if (0 === prepared.length) continue;
|
|
97
|
+
this.activeBatch = prepared;
|
|
98
|
+
const policy = {
|
|
99
|
+
endpoint: this.config.endpoint,
|
|
100
|
+
headers: {
|
|
101
|
+
...this.config.headers
|
|
102
|
+
},
|
|
103
|
+
maxRetries: finiteNonNegativeInteger(this.config.maxRetries),
|
|
104
|
+
retryDelay: finiteNonNegativeNumber(this.config.retryDelay)
|
|
105
|
+
};
|
|
106
|
+
await this.sendPreparedBatch(prepared, policy);
|
|
107
|
+
this.activeBatch = [];
|
|
108
|
+
}
|
|
39
109
|
}
|
|
40
|
-
async
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
110
|
+
async prepareNextBatch() {
|
|
111
|
+
const prepared = [];
|
|
112
|
+
const elementBytes = [];
|
|
113
|
+
const countLimit = this.batchSizeThreshold();
|
|
114
|
+
while(this.pendingQueue.length > 0 && prepared.length < countLimit){
|
|
115
|
+
const next = this.pendingQueue[0];
|
|
116
|
+
if (jsonArrayUtf8Bytes([
|
|
117
|
+
next.requestBytes
|
|
118
|
+
]) > LOG_REQUEST_BODY_MAX_BYTES) {
|
|
119
|
+
const replaced = await this.replaceOversizedLog(next);
|
|
120
|
+
if (!replaced) {
|
|
121
|
+
this.pendingQueue.shift();
|
|
122
|
+
this.releaseLogs([
|
|
123
|
+
next
|
|
124
|
+
]);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const candidateBytes = jsonArrayUtf8Bytes([
|
|
129
|
+
...elementBytes,
|
|
130
|
+
next.requestBytes
|
|
131
|
+
]);
|
|
132
|
+
if (candidateBytes > LOG_REQUEST_BODY_MAX_BYTES) break;
|
|
133
|
+
this.pendingQueue.shift();
|
|
134
|
+
if (next.overflowState) next.overflowState.sealed = true;
|
|
135
|
+
prepared.push(next);
|
|
136
|
+
elementBytes.push(next.requestBytes);
|
|
137
|
+
}
|
|
138
|
+
return prepared;
|
|
139
|
+
}
|
|
140
|
+
async replaceOversizedLog(item) {
|
|
141
|
+
const originalRequest = item.request;
|
|
142
|
+
if (!originalRequest) return false;
|
|
44
143
|
try {
|
|
45
|
-
|
|
144
|
+
const originalMessageBytes = utf8ByteLength(originalRequest.message);
|
|
145
|
+
const digest = await sha256Utf8(originalRequest.message);
|
|
146
|
+
const signal = {
|
|
147
|
+
schema: LOSS_SCHEMA,
|
|
148
|
+
reason: 'single-envelope-over-16-mib-wire-budget',
|
|
149
|
+
terminal_action: 'send-bounded-surrogate',
|
|
150
|
+
count: 1,
|
|
151
|
+
log_ids: [
|
|
152
|
+
item.id
|
|
153
|
+
],
|
|
154
|
+
sequence_range: [
|
|
155
|
+
item.sequence
|
|
156
|
+
],
|
|
157
|
+
original_utf8_bytes: originalMessageBytes,
|
|
158
|
+
original_envelope_utf8_bytes: item.requestBytes,
|
|
159
|
+
preview: boundedUtf8Preview(originalRequest.message, LOSS_PREVIEW_MAX_BYTES),
|
|
160
|
+
first_seen: originalRequest.time,
|
|
161
|
+
last_seen: originalRequest.time,
|
|
162
|
+
sha256: digest
|
|
163
|
+
};
|
|
164
|
+
const diagnostic = this.createDiagnosticRequest(signal, originalRequest.time);
|
|
165
|
+
this.replaceRetainedRequest(item, diagnostic, 'surrogate');
|
|
166
|
+
item.lossSignal = signal;
|
|
167
|
+
this.emitLossSignal(signal);
|
|
168
|
+
return true;
|
|
46
169
|
} catch (error) {
|
|
47
|
-
this.
|
|
48
|
-
|
|
49
|
-
|
|
170
|
+
this.emitLossSignal({
|
|
171
|
+
schema: LOSS_SCHEMA,
|
|
172
|
+
reason: 'single-envelope-surrogate-construction-failed',
|
|
173
|
+
terminal_action: 'drop-with-console-terminal-signal',
|
|
174
|
+
count: 1,
|
|
175
|
+
log_ids: [
|
|
176
|
+
item.id
|
|
177
|
+
],
|
|
178
|
+
sequence_range: [
|
|
179
|
+
item.sequence
|
|
180
|
+
],
|
|
181
|
+
original_utf8_bytes: utf8ByteLength(originalRequest.message),
|
|
182
|
+
original_envelope_utf8_bytes: item.requestBytes,
|
|
183
|
+
preview: boundedUtf8Preview(originalRequest.message, LOSS_PREVIEW_MAX_BYTES),
|
|
184
|
+
first_seen: originalRequest.time,
|
|
185
|
+
last_seen: originalRequest.time
|
|
186
|
+
});
|
|
187
|
+
this.originConsole.error('[batch-logger-loss-v1] surrogate construction error', error);
|
|
188
|
+
return false;
|
|
50
189
|
}
|
|
51
190
|
}
|
|
52
|
-
async
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
191
|
+
async sendPreparedBatch(items, policy, rejectedCanonicals, enforceRejectedCanonical = false) {
|
|
192
|
+
let attempts = 0;
|
|
193
|
+
while(attempts <= policy.maxRetries){
|
|
194
|
+
attempts += 1;
|
|
195
|
+
const result = await this.executeBatch(items, policy, rejectedCanonicals, enforceRejectedCanonical);
|
|
196
|
+
const status = result.response?.status;
|
|
197
|
+
if (result.knownRejectedCanonical) return void await this.handlePayloadTooLarge(items, policy, rejectedCanonicals);
|
|
198
|
+
if (void 0 !== status && status >= 200 && status < 300) return void this.releaseLogs(items);
|
|
199
|
+
if (413 === status) {
|
|
200
|
+
const tracker = rejectedCanonicals || {
|
|
201
|
+
attempts: new Map()
|
|
202
|
+
};
|
|
203
|
+
if (result.canonicalFingerprint) {
|
|
204
|
+
const rejectedAttempts = tracker.attempts.get(result.canonicalFingerprint) || 0;
|
|
205
|
+
tracker.attempts.set(result.canonicalFingerprint, Math.min(LOG_MAX_413_CANONICAL_ATTEMPTS, rejectedAttempts + 1));
|
|
206
|
+
}
|
|
207
|
+
await this.handlePayloadTooLarge(items, policy, tracker);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (!this.isRetryable(result)) {
|
|
211
|
+
this.emitBatchTerminal(items, `non-retryable-http-${status ?? 'unknown'}`, 'drop-and-continue', status);
|
|
212
|
+
this.releaseLogs(items);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (attempts > policy.maxRetries) {
|
|
216
|
+
this.emitBatchTerminal(items, result.error ? 'network-retries-exhausted' : `http-${status}-retries-exhausted`, 'drop-after-lifecycle-retry-limit', status);
|
|
217
|
+
this.releaseLogs(items);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
this.originConsole.warn(`Failed to send logs (attempt ${attempts}), retrying in ${policy.retryDelay * attempts}ms...`);
|
|
221
|
+
await this.delay(policy.retryDelay * attempts);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async handlePayloadTooLarge(items, policy, rejectedCanonicals) {
|
|
225
|
+
if (items.length > 1) {
|
|
226
|
+
const midpoint = Math.ceil(items.length / 2);
|
|
227
|
+
await this.sendPreparedBatch(items.slice(0, midpoint), policy, rejectedCanonicals, true);
|
|
228
|
+
await this.sendPreparedBatch(items.slice(midpoint), policy, rejectedCanonicals, true);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const item = items[0];
|
|
232
|
+
if ('normal' !== item.kind || !item.request) {
|
|
233
|
+
this.emitBatchTerminal(items, 'single-surrogate-rejected-with-413', 'drop-with-console-terminal-signal', 413);
|
|
234
|
+
this.releaseLogs(items);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const signal = this.replaceSingle413WithSurrogate(item);
|
|
238
|
+
const result = await this.executeBatch(items, policy);
|
|
239
|
+
const status = result.response?.status;
|
|
240
|
+
if (void 0 !== status && status >= 200 && status < 300) {
|
|
241
|
+
this.emitLossSignal(signal);
|
|
242
|
+
this.releaseLogs(items);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
this.emitBatchTerminal(items, result.error ? 'surrogate-network-delivery-failed' : `surrogate-http-${status ?? 'unknown'}-delivery-failed`, 'surrogate-delivery-failed-drop-and-continue', status);
|
|
246
|
+
this.releaseLogs(items);
|
|
247
|
+
}
|
|
248
|
+
replaceSingle413WithSurrogate(item) {
|
|
249
|
+
const originalRequest = item.request;
|
|
250
|
+
const signal = {
|
|
251
|
+
schema: LOSS_SCHEMA,
|
|
252
|
+
reason: 'single-log-rejected-with-413',
|
|
253
|
+
terminal_action: 'send-bounded-surrogate-once',
|
|
254
|
+
count: 1,
|
|
255
|
+
log_ids: [
|
|
256
|
+
item.id
|
|
257
|
+
],
|
|
258
|
+
sequence_range: [
|
|
259
|
+
item.sequence
|
|
260
|
+
],
|
|
261
|
+
original_utf8_bytes: utf8ByteLength(originalRequest.message),
|
|
262
|
+
original_envelope_utf8_bytes: item.requestBytes,
|
|
263
|
+
preview: boundedUtf8Preview(originalRequest.message, LOSS_PREVIEW_MAX_BYTES),
|
|
264
|
+
first_seen: originalRequest.time,
|
|
265
|
+
last_seen: originalRequest.time
|
|
266
|
+
};
|
|
267
|
+
const diagnostic = this.createDiagnosticRequest(signal, originalRequest.time);
|
|
268
|
+
this.replaceRetainedRequest(item, diagnostic, 'surrogate');
|
|
269
|
+
item.lossSignal = signal;
|
|
270
|
+
return signal;
|
|
271
|
+
}
|
|
272
|
+
async executeBatch(items, policy, rejectedCanonicals, enforceRejectedCanonical = false) {
|
|
273
|
+
const requests = items.map((item)=>item.request);
|
|
274
|
+
const { json: body, utf8Bytes } = serializeJson(requests);
|
|
275
|
+
if (utf8Bytes > LOG_REQUEST_BODY_MAX_BYTES) return {
|
|
276
|
+
error: new Error(`BatchLogger refused ${utf8Bytes}-byte over-budget request`)
|
|
277
|
+
};
|
|
278
|
+
const fingerprint = enforceRejectedCanonical || rejectedCanonicals ? boundedCanonicalJsonFingerprint(body, utf8Bytes) : void 0;
|
|
279
|
+
if (enforceRejectedCanonical && fingerprint && (rejectedCanonicals?.attempts.get(fingerprint) || 0) >= LOG_MAX_413_CANONICAL_ATTEMPTS) return {
|
|
280
|
+
knownRejectedCanonical: true
|
|
281
|
+
};
|
|
282
|
+
try {
|
|
283
|
+
const response = await this.execFetch(policy.endpoint, {
|
|
65
284
|
method: 'POST',
|
|
66
|
-
headers:
|
|
67
|
-
body
|
|
285
|
+
headers: policy.headers,
|
|
286
|
+
body
|
|
68
287
|
});
|
|
69
|
-
return
|
|
288
|
+
return {
|
|
289
|
+
response,
|
|
290
|
+
canonicalFingerprint: 413 === response.status ? fingerprint || boundedCanonicalJsonFingerprint(body, utf8Bytes) : void 0
|
|
291
|
+
};
|
|
70
292
|
} catch (error) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
await this.delay(this.config.retryDelay * retries);
|
|
293
|
+
return {
|
|
294
|
+
error
|
|
295
|
+
};
|
|
75
296
|
}
|
|
76
297
|
}
|
|
298
|
+
isRetryable(result) {
|
|
299
|
+
if (result.error) return true;
|
|
300
|
+
const status = result.response?.status;
|
|
301
|
+
return 408 === status || 429 === status || void 0 !== status && status >= 500;
|
|
302
|
+
}
|
|
303
|
+
recordOverflow(id, sequence, message, requestBytes, timestamp) {
|
|
304
|
+
if (this.overflowRecord) return void this.emitImmediateOverflow(id, sequence, message, requestBytes, timestamp);
|
|
305
|
+
const time = new Date(timestamp).toISOString();
|
|
306
|
+
const signal = {
|
|
307
|
+
schema: LOSS_SCHEMA,
|
|
308
|
+
reason: 'shared-retained-budget-exceeded',
|
|
309
|
+
terminal_action: 'aggregate-bounded-overflow-record',
|
|
310
|
+
count: 1,
|
|
311
|
+
log_ids: [
|
|
312
|
+
id,
|
|
313
|
+
id
|
|
314
|
+
],
|
|
315
|
+
sequence_range: [
|
|
316
|
+
sequence
|
|
317
|
+
],
|
|
318
|
+
original_utf8_bytes: utf8ByteLength(message),
|
|
319
|
+
original_envelope_utf8_bytes: requestBytes,
|
|
320
|
+
preview: boundedUtf8Preview(message, LOSS_PREVIEW_MAX_BYTES),
|
|
321
|
+
first_seen: time,
|
|
322
|
+
last_seen: time
|
|
323
|
+
};
|
|
324
|
+
const request = this.createDiagnosticRequest(signal, time);
|
|
325
|
+
const requestBytesForDiagnostic = jsonValueUtf8Bytes(request);
|
|
326
|
+
const overflow = {
|
|
327
|
+
id,
|
|
328
|
+
sequence,
|
|
329
|
+
request,
|
|
330
|
+
requestBytes: requestBytesForDiagnostic,
|
|
331
|
+
budgetBytes: retainedBudgetBytes(requestBytesForDiagnostic),
|
|
332
|
+
budgetClass: 'overflow',
|
|
333
|
+
kind: 'overflow',
|
|
334
|
+
overflowState: {
|
|
335
|
+
signal,
|
|
336
|
+
sealed: false
|
|
337
|
+
},
|
|
338
|
+
lossSignal: signal,
|
|
339
|
+
released: false
|
|
340
|
+
};
|
|
341
|
+
this.overflowRecord = overflow;
|
|
342
|
+
this.pendingQueue.push(overflow);
|
|
343
|
+
this.emitLossSignal(signal);
|
|
344
|
+
if (this.pendingQueue.length >= this.batchSizeThreshold()) this.flush();
|
|
345
|
+
}
|
|
346
|
+
mergeOverflow(overflow, id, sequence, message, requestBytes, timestamp) {
|
|
347
|
+
const state = overflow.overflowState;
|
|
348
|
+
const signal = state.signal;
|
|
349
|
+
signal.count = boundedSafeIntegerSum(signal.count, 1);
|
|
350
|
+
signal.log_ids[1] = id;
|
|
351
|
+
signal.sequence_range = [
|
|
352
|
+
signal.sequence_range[0],
|
|
353
|
+
sequence
|
|
354
|
+
];
|
|
355
|
+
signal.original_utf8_bytes = boundedSafeIntegerSum(signal.original_utf8_bytes, utf8ByteLength(message));
|
|
356
|
+
signal.original_envelope_utf8_bytes = boundedSafeIntegerSum(signal.original_envelope_utf8_bytes || 0, requestBytes);
|
|
357
|
+
signal.last_seen = new Date(timestamp).toISOString();
|
|
358
|
+
const request = this.createDiagnosticRequest(signal, signal.first_seen);
|
|
359
|
+
overflow.request = request;
|
|
360
|
+
overflow.requestBytes = jsonValueUtf8Bytes(request);
|
|
361
|
+
overflow.budgetBytes = retainedBudgetBytes(overflow.requestBytes);
|
|
362
|
+
}
|
|
363
|
+
emitImmediateOverflow(id, sequence, message, requestBytes, timestamp) {
|
|
364
|
+
const time = new Date(timestamp).toISOString();
|
|
365
|
+
this.emitLossSignal({
|
|
366
|
+
schema: LOSS_SCHEMA,
|
|
367
|
+
reason: 'overflow-reservation-already-in-flight',
|
|
368
|
+
terminal_action: 'drop-with-console-terminal-signal',
|
|
369
|
+
count: 1,
|
|
370
|
+
log_ids: [
|
|
371
|
+
id
|
|
372
|
+
],
|
|
373
|
+
sequence_range: [
|
|
374
|
+
sequence
|
|
375
|
+
],
|
|
376
|
+
original_utf8_bytes: utf8ByteLength(message),
|
|
377
|
+
original_envelope_utf8_bytes: requestBytes,
|
|
378
|
+
preview: boundedUtf8Preview(message, LOSS_PREVIEW_MAX_BYTES),
|
|
379
|
+
first_seen: time,
|
|
380
|
+
last_seen: time
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
createDiagnosticRequest(signal, time) {
|
|
384
|
+
const request = {
|
|
385
|
+
level: 'error',
|
|
386
|
+
message: JSON.stringify(signal),
|
|
387
|
+
time,
|
|
388
|
+
source: LOSS_SCHEMA,
|
|
389
|
+
user_id: boundedUtf8Preview(this.config.userId, DIAGNOSTIC_IDENTITY_MAX_BYTES),
|
|
390
|
+
tenant_id: boundedUtf8Preview(this.config.tenantId, DIAGNOSTIC_IDENTITY_MAX_BYTES),
|
|
391
|
+
app_id: boundedUtf8Preview(this.config.appId, DIAGNOSTIC_IDENTITY_MAX_BYTES)
|
|
392
|
+
};
|
|
393
|
+
if (jsonArrayUtf8Bytes([
|
|
394
|
+
jsonValueUtf8Bytes(request)
|
|
395
|
+
]) <= LOG_OVERFLOW_RESERVED_BYTES) return request;
|
|
396
|
+
signal.preview = '';
|
|
397
|
+
signal.log_ids = signal.log_ids.map((id)=>boundedUtf8Preview(id, 128));
|
|
398
|
+
request.message = JSON.stringify(signal);
|
|
399
|
+
if (jsonArrayUtf8Bytes([
|
|
400
|
+
jsonValueUtf8Bytes(request)
|
|
401
|
+
]) > LOG_OVERFLOW_RESERVED_BYTES) {
|
|
402
|
+
request.user_id = '';
|
|
403
|
+
request.tenant_id = '';
|
|
404
|
+
request.app_id = '';
|
|
405
|
+
}
|
|
406
|
+
return request;
|
|
407
|
+
}
|
|
408
|
+
replaceRetainedRequest(item, request, kind) {
|
|
409
|
+
const previousBudgetBytes = item.budgetBytes;
|
|
410
|
+
const requestBytes = jsonValueUtf8Bytes(request);
|
|
411
|
+
item.request = request;
|
|
412
|
+
item.requestBytes = requestBytes;
|
|
413
|
+
item.budgetBytes = retainedBudgetBytes(requestBytes);
|
|
414
|
+
item.kind = kind;
|
|
415
|
+
if ('normal' === item.budgetClass) this.retainedNormalBytes += item.budgetBytes - previousBudgetBytes;
|
|
416
|
+
}
|
|
417
|
+
emitBatchTerminal(items, deliveryReason, action, status) {
|
|
418
|
+
if (0 === items.length) return;
|
|
419
|
+
for (const item of items){
|
|
420
|
+
if (!item.lossSignal) continue;
|
|
421
|
+
const underlying = item.lossSignal;
|
|
422
|
+
const terminal = {
|
|
423
|
+
...underlying,
|
|
424
|
+
log_ids: [
|
|
425
|
+
...underlying.log_ids
|
|
426
|
+
],
|
|
427
|
+
sequence_range: [
|
|
428
|
+
...underlying.sequence_range
|
|
429
|
+
],
|
|
430
|
+
terminal_action: action,
|
|
431
|
+
delivery_outcome: 'failed',
|
|
432
|
+
delivery_reason: deliveryReason,
|
|
433
|
+
...void 0 === status ? {} : {
|
|
434
|
+
delivery_status: status
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
this.emitLossSignal(terminal);
|
|
438
|
+
}
|
|
439
|
+
const ordinaryItems = items.filter((item)=>!item.lossSignal);
|
|
440
|
+
if (0 === ordinaryItems.length) return;
|
|
441
|
+
const first = ordinaryItems[0];
|
|
442
|
+
const last = ordinaryItems[ordinaryItems.length - 1];
|
|
443
|
+
const requests = ordinaryItems.map((item)=>item.request).filter((request)=>Boolean(request));
|
|
444
|
+
const originalBytes = requests.reduce((total, request)=>boundedSafeIntegerSum(total, utf8ByteLength(request.message)), 0);
|
|
445
|
+
this.emitLossSignal({
|
|
446
|
+
schema: LOSS_SCHEMA,
|
|
447
|
+
reason: deliveryReason,
|
|
448
|
+
terminal_action: action,
|
|
449
|
+
count: ordinaryItems.length,
|
|
450
|
+
log_ids: [
|
|
451
|
+
first.id,
|
|
452
|
+
last.id
|
|
453
|
+
],
|
|
454
|
+
sequence_range: first === last ? [
|
|
455
|
+
first.sequence
|
|
456
|
+
] : [
|
|
457
|
+
first.sequence,
|
|
458
|
+
last.sequence
|
|
459
|
+
],
|
|
460
|
+
original_utf8_bytes: originalBytes,
|
|
461
|
+
preview: boundedUtf8Preview(requests[0]?.message || '', LOSS_PREVIEW_MAX_BYTES),
|
|
462
|
+
first_seen: requests[0]?.time || new Date().toISOString(),
|
|
463
|
+
last_seen: requests[requests.length - 1]?.time || new Date().toISOString(),
|
|
464
|
+
delivery_outcome: 'failed',
|
|
465
|
+
delivery_reason: deliveryReason,
|
|
466
|
+
...void 0 === status ? {} : {
|
|
467
|
+
delivery_status: status
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
emitLossSignal(signal) {
|
|
472
|
+
this.originConsole.error('[batch-logger-loss-v1]', signal);
|
|
473
|
+
}
|
|
474
|
+
releaseLogs(items) {
|
|
475
|
+
for (const item of items)if (!item.released) {
|
|
476
|
+
item.released = true;
|
|
477
|
+
if ('normal' === item.budgetClass) {
|
|
478
|
+
this.retainedNormalEntries -= 1;
|
|
479
|
+
this.retainedNormalBytes -= item.budgetBytes;
|
|
480
|
+
} else if (this.overflowRecord === item) this.overflowRecord = null;
|
|
481
|
+
item.request = null;
|
|
482
|
+
item.lossSignal = void 0;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
batchSizeThreshold() {
|
|
486
|
+
return Math.max(1, Math.floor(this.config.sizeThreshold));
|
|
487
|
+
}
|
|
77
488
|
async execFetch(url, options) {
|
|
78
489
|
return fetch(url, options);
|
|
79
490
|
}
|
|
80
491
|
startFlushTimer() {
|
|
81
492
|
if (this.flushTimer) clearInterval(this.flushTimer);
|
|
82
493
|
this.flushTimer = setInterval(()=>{
|
|
83
|
-
if (this.
|
|
494
|
+
if (this.pendingQueue.length > 0) this.flush();
|
|
84
495
|
}, this.config.flushInterval);
|
|
85
496
|
}
|
|
86
497
|
setupBeforeUnloadHandler() {
|
|
@@ -101,10 +512,10 @@ class BatchLogger {
|
|
|
101
512
|
clearInterval(this.flushTimer);
|
|
102
513
|
this.flushTimer = null;
|
|
103
514
|
}
|
|
104
|
-
|
|
515
|
+
await this.flush();
|
|
105
516
|
}
|
|
106
517
|
getQueueSize() {
|
|
107
|
-
return this.
|
|
518
|
+
return this.pendingQueue.length;
|
|
108
519
|
}
|
|
109
520
|
updateConfig(newConfig) {
|
|
110
521
|
this.config = {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare const LOG_REQUEST_BODY_MAX_BYTES: number;
|
|
2
|
+
export declare const LOG_RETAINED_MAX_BYTES: number;
|
|
3
|
+
export declare const LOG_RETAINED_MAX_ENTRIES = 1000;
|
|
4
|
+
export declare const LOG_OVERFLOW_RESERVED_BYTES: number;
|
|
5
|
+
export declare const LOG_OVERFLOW_RESERVED_ENTRIES = 1;
|
|
6
|
+
export declare const LOG_MAX_IN_FLIGHT_REQUESTS = 1;
|
|
7
|
+
export declare const LOG_MAX_413_CANONICAL_ATTEMPTS = 1;
|
|
8
|
+
export declare const LOG_NORMAL_RETAINED_MAX_BYTES: number;
|
|
9
|
+
export declare const LOG_NORMAL_RETAINED_MAX_ENTRIES: number;
|
|
10
|
+
export declare function utf8ByteLength(value: string): number;
|
|
11
|
+
export declare function serializeJson(value: unknown): {
|
|
12
|
+
json: string;
|
|
13
|
+
utf8Bytes: number;
|
|
14
|
+
};
|
|
15
|
+
export declare function jsonValueUtf8Bytes(value: unknown): number;
|
|
16
|
+
/**
|
|
17
|
+
* A fixed-size, non-cryptographic identity for an already-canonical JSON body.
|
|
18
|
+
* It is used only inside an active 413 split lifecycle; SHA-256 remains confined
|
|
19
|
+
* to the exceptional oversized-single-entry loss path.
|
|
20
|
+
*/
|
|
21
|
+
export declare function boundedCanonicalJsonFingerprint(json: string, utf8Bytes: number): string;
|
|
22
|
+
/** The exact wire size of a JSON array whose element sizes are already known. */
|
|
23
|
+
export declare function jsonArrayUtf8Bytes(elementBytes: readonly number[]): number;
|
|
24
|
+
/**
|
|
25
|
+
* Returns a prefix without reading the remainder of a potentially huge string.
|
|
26
|
+
* The returned string is always at most maxBytes once encoded as UTF-8.
|
|
27
|
+
*/
|
|
28
|
+
export declare function boundedUtf8Preview(value: string, maxBytes: number): string;
|
|
29
|
+
export declare function sha256Utf8(value: string): Promise<string>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const LOG_REQUEST_BODY_MAX_BYTES = 16777216;
|
|
2
|
+
const LOG_RETAINED_MAX_BYTES = 33554432;
|
|
3
|
+
const LOG_RETAINED_MAX_ENTRIES = 1000;
|
|
4
|
+
const LOG_OVERFLOW_RESERVED_BYTES = 65536;
|
|
5
|
+
const LOG_OVERFLOW_RESERVED_ENTRIES = 1;
|
|
6
|
+
const LOG_MAX_IN_FLIGHT_REQUESTS = 1;
|
|
7
|
+
const LOG_MAX_413_CANONICAL_ATTEMPTS = 1;
|
|
8
|
+
const LOG_NORMAL_RETAINED_MAX_BYTES = LOG_RETAINED_MAX_BYTES - LOG_OVERFLOW_RESERVED_BYTES;
|
|
9
|
+
const LOG_NORMAL_RETAINED_MAX_ENTRIES = LOG_RETAINED_MAX_ENTRIES - LOG_OVERFLOW_RESERVED_ENTRIES;
|
|
10
|
+
const utf8Encoder = new TextEncoder();
|
|
11
|
+
function utf8ByteLength(value) {
|
|
12
|
+
return utf8Encoder.encode(value).byteLength;
|
|
13
|
+
}
|
|
14
|
+
function serializeJson(value) {
|
|
15
|
+
const json = JSON.stringify(value);
|
|
16
|
+
return {
|
|
17
|
+
json,
|
|
18
|
+
utf8Bytes: utf8ByteLength(json)
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function jsonValueUtf8Bytes(value) {
|
|
22
|
+
return serializeJson(value).utf8Bytes;
|
|
23
|
+
}
|
|
24
|
+
function boundedCanonicalJsonFingerprint(json, utf8Bytes) {
|
|
25
|
+
let first = 0x811c9dc5;
|
|
26
|
+
let second = 0x9e3779b9;
|
|
27
|
+
let third = 0x85ebca6b;
|
|
28
|
+
let fourth = 0xc2b2ae35;
|
|
29
|
+
for(let index = 0; index < json.length; index += 1){
|
|
30
|
+
const codeUnit = json.charCodeAt(index);
|
|
31
|
+
first = Math.imul(first ^ codeUnit, 0x01000193);
|
|
32
|
+
second = Math.imul(second ^ codeUnit, 0x85ebca6b);
|
|
33
|
+
third = Math.imul(third ^ codeUnit, 0xc2b2ae35);
|
|
34
|
+
fourth = Math.imul(fourth ^ codeUnit, 0x27d4eb2f);
|
|
35
|
+
}
|
|
36
|
+
const hex = (value)=>(value >>> 0).toString(16).padStart(8, '0');
|
|
37
|
+
return `${utf8Bytes}:${json.length}:${hex(first)}${hex(second)}${hex(third)}${hex(fourth)}`;
|
|
38
|
+
}
|
|
39
|
+
function jsonArrayUtf8Bytes(elementBytes) {
|
|
40
|
+
if (0 === elementBytes.length) return 2;
|
|
41
|
+
return 2 + elementBytes.reduce((total, current)=>total + current, 0) + elementBytes.length - 1;
|
|
42
|
+
}
|
|
43
|
+
function boundedUtf8Preview(value, maxBytes) {
|
|
44
|
+
if (maxBytes <= 0 || 0 === value.length) return '';
|
|
45
|
+
let result = '';
|
|
46
|
+
let resultBytes = 0;
|
|
47
|
+
for (const character of value){
|
|
48
|
+
const characterBytes = utf8ByteLength(character);
|
|
49
|
+
if (resultBytes + characterBytes > maxBytes) break;
|
|
50
|
+
result += character;
|
|
51
|
+
resultBytes += characterBytes;
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
async function sha256Utf8(value) {
|
|
56
|
+
const subtle = globalThis.crypto?.subtle;
|
|
57
|
+
if (!subtle) throw new Error('Web Crypto SHA-256 is unavailable');
|
|
58
|
+
const digest = await subtle.digest('SHA-256', utf8Encoder.encode(value));
|
|
59
|
+
return Array.from(new Uint8Array(digest), (byte)=>byte.toString(16).padStart(2, '0')).join('');
|
|
60
|
+
}
|
|
61
|
+
export { LOG_MAX_413_CANONICAL_ATTEMPTS, LOG_MAX_IN_FLIGHT_REQUESTS, LOG_NORMAL_RETAINED_MAX_BYTES, LOG_NORMAL_RETAINED_MAX_ENTRIES, LOG_OVERFLOW_RESERVED_BYTES, LOG_OVERFLOW_RESERVED_ENTRIES, LOG_REQUEST_BODY_MAX_BYTES, LOG_RETAINED_MAX_BYTES, LOG_RETAINED_MAX_ENTRIES, boundedCanonicalJsonFingerprint, boundedUtf8Preview, jsonArrayUtf8Bytes, jsonValueUtf8Bytes, serializeJson, sha256Utf8, utf8ByteLength };
|