@lark-apaas/client-toolkit 1.2.84 → 1.2.85-alpha.20261112221213
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.
|
@@ -23,6 +23,7 @@ export declare class BatchLogger {
|
|
|
23
23
|
private logQueue;
|
|
24
24
|
private flushTimer;
|
|
25
25
|
private isProcessing;
|
|
26
|
+
private nextSequence;
|
|
26
27
|
private originConsole;
|
|
27
28
|
constructor(console: Console, config?: BatchLoggerConfig);
|
|
28
29
|
/**
|
|
@@ -33,10 +34,16 @@ export declare class BatchLogger {
|
|
|
33
34
|
* 刷新日志队列,全部发送
|
|
34
35
|
*/
|
|
35
36
|
flush(): Promise<void>;
|
|
37
|
+
private captureFlushConfig;
|
|
38
|
+
private processSnapshot;
|
|
39
|
+
private prepareLog;
|
|
40
|
+
private createSendActions;
|
|
36
41
|
/**
|
|
37
|
-
*
|
|
42
|
+
* Sends one final wire body. Only fetch rejection is retried; resolved HTTP
|
|
43
|
+
* responses are returned to the snapshot processor after one request.
|
|
38
44
|
*/
|
|
39
|
-
private
|
|
45
|
+
private sendRequest;
|
|
46
|
+
private emitTerminal;
|
|
40
47
|
/**
|
|
41
48
|
* 执行实际的fetch请求
|
|
42
49
|
*/
|
|
@@ -1,14 +1,19 @@
|
|
|
1
|
+
import { LOG_REQUEST_BODY_MAX_BYTES, boundedUtf8Preview, jsonArrayUtf8Bytes, utf8ByteLength } from "./log-payload-budget.js";
|
|
2
|
+
const TERMINAL_ID_MAX_BYTES = 128;
|
|
3
|
+
const TERMINAL_REASON_MAX_BYTES = 256;
|
|
1
4
|
class BatchLogger {
|
|
2
5
|
config;
|
|
3
6
|
logQueue = [];
|
|
4
7
|
flushTimer = null;
|
|
5
8
|
isProcessing = false;
|
|
9
|
+
nextSequence = 0;
|
|
6
10
|
originConsole;
|
|
7
11
|
constructor(console1, config){
|
|
8
12
|
this.originConsole = {
|
|
9
13
|
...console1
|
|
10
14
|
};
|
|
11
|
-
const
|
|
15
|
+
const globalAppInfo = 'undefined' == typeof window ? {} : window;
|
|
16
|
+
const { userId = '', tenantId = '', appId = '' } = globalAppInfo;
|
|
12
17
|
this.config = {
|
|
13
18
|
userId,
|
|
14
19
|
tenantId,
|
|
@@ -29,11 +34,13 @@ class BatchLogger {
|
|
|
29
34
|
batchLog(level, message, source) {
|
|
30
35
|
const logEntry = {
|
|
31
36
|
id: this.generateId(),
|
|
37
|
+
sequence: this.nextSequence,
|
|
32
38
|
level,
|
|
33
39
|
message,
|
|
34
40
|
source,
|
|
35
41
|
timestamp: Date.now()
|
|
36
42
|
};
|
|
43
|
+
this.nextSequence += 1;
|
|
37
44
|
this.logQueue.push(logEntry);
|
|
38
45
|
if (this.logQueue.length >= this.config.sizeThreshold) this.flush();
|
|
39
46
|
}
|
|
@@ -41,39 +48,165 @@ class BatchLogger {
|
|
|
41
48
|
if (this.isProcessing || 0 === this.logQueue.length) return;
|
|
42
49
|
this.isProcessing = true;
|
|
43
50
|
const logsToSend = this.logQueue.splice(0, this.logQueue.length);
|
|
51
|
+
const progress = {
|
|
52
|
+
nextIndex: 0
|
|
53
|
+
};
|
|
44
54
|
try {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
55
|
+
const flushConfig = this.captureFlushConfig();
|
|
56
|
+
await this.processSnapshot(logsToSend, flushConfig, progress);
|
|
57
|
+
} catch {
|
|
58
|
+
this.emitTerminal(logsToSend.slice(progress.nextIndex), 'PROCESSING_ERROR', 'unexpected-snapshot-processing-error');
|
|
48
59
|
} finally{
|
|
49
60
|
this.isProcessing = false;
|
|
50
61
|
}
|
|
51
62
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
63
|
+
captureFlushConfig() {
|
|
64
|
+
return {
|
|
65
|
+
userId: this.config.userId,
|
|
66
|
+
tenantId: this.config.tenantId,
|
|
67
|
+
appId: this.config.appId,
|
|
68
|
+
endpoint: this.config.endpoint,
|
|
69
|
+
maxRetries: this.config.maxRetries,
|
|
70
|
+
retryDelay: this.config.retryDelay,
|
|
71
|
+
headers: {
|
|
72
|
+
...this.config.headers
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
async processSnapshot(logs, config, progress) {
|
|
77
|
+
const prepared = logs.map((log)=>this.prepareLog(log, config));
|
|
78
|
+
const actions = this.createSendActions(prepared);
|
|
79
|
+
for (const action of actions){
|
|
80
|
+
if ('oversized' === action.kind) {
|
|
81
|
+
this.emitTerminal(action.logs.map((item)=>item.log), 'PAYLOAD_TOO_LARGE', 'single-envelope-over-20-mib-wire-budget');
|
|
82
|
+
progress.nextIndex = action.startIndex + action.logs.length;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const result = await this.sendRequest(action.logs, config);
|
|
86
|
+
if ('success' === result.kind) {
|
|
87
|
+
progress.nextIndex = action.startIndex + action.logs.length;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if ('payload-too-large' === result.kind) {
|
|
91
|
+
this.emitTerminal(action.logs.map((item)=>item.log), 'PAYLOAD_TOO_LARGE', 'final-wire-body-over-20-mib-budget');
|
|
92
|
+
progress.nextIndex = action.startIndex + action.logs.length;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const unsentLogs = logs.slice(action.startIndex);
|
|
96
|
+
if ('http-error' === result.kind) this.emitTerminal(unsentLogs, result.status, 'http-non-2xx-response');
|
|
97
|
+
else this.emitTerminal(unsentLogs, 'NETWORK_ERROR', 'fetch-rejected-after-retries-exhausted');
|
|
69
98
|
return;
|
|
70
|
-
} catch (error) {
|
|
71
|
-
retries++;
|
|
72
|
-
if (retries > this.config.maxRetries) this.originConsole.error(`Failed to send logs (attempt ${retries}), retrying in ${this.config.retryDelay}ms...`);
|
|
73
|
-
else this.originConsole.warn(`Failed to send logs (attempt ${retries}), retrying in ${this.config.retryDelay}ms...`);
|
|
74
|
-
await this.delay(this.config.retryDelay * retries);
|
|
75
99
|
}
|
|
76
100
|
}
|
|
101
|
+
prepareLog(log, config) {
|
|
102
|
+
const request = {
|
|
103
|
+
level: log.level,
|
|
104
|
+
message: log.message,
|
|
105
|
+
time: new Date(log.timestamp).toISOString(),
|
|
106
|
+
source: log.source,
|
|
107
|
+
user_id: config.userId,
|
|
108
|
+
tenant_id: config.tenantId,
|
|
109
|
+
app_id: config.appId
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
log,
|
|
113
|
+
request,
|
|
114
|
+
requestBytes: utf8ByteLength(JSON.stringify(request))
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
createSendActions(logs) {
|
|
118
|
+
const actions = [];
|
|
119
|
+
let currentBatch = [];
|
|
120
|
+
let currentBatchBytes = 2;
|
|
121
|
+
let currentBatchStart = 0;
|
|
122
|
+
const pushCurrentBatch = ()=>{
|
|
123
|
+
if (0 === currentBatch.length) return;
|
|
124
|
+
actions.push({
|
|
125
|
+
kind: 'request',
|
|
126
|
+
startIndex: currentBatchStart,
|
|
127
|
+
logs: currentBatch
|
|
128
|
+
});
|
|
129
|
+
currentBatch = [];
|
|
130
|
+
currentBatchBytes = 2;
|
|
131
|
+
};
|
|
132
|
+
logs.forEach((log, index)=>{
|
|
133
|
+
if (jsonArrayUtf8Bytes([
|
|
134
|
+
log.requestBytes
|
|
135
|
+
]) > LOG_REQUEST_BODY_MAX_BYTES) {
|
|
136
|
+
pushCurrentBatch();
|
|
137
|
+
actions.push({
|
|
138
|
+
kind: 'oversized',
|
|
139
|
+
startIndex: index,
|
|
140
|
+
logs: [
|
|
141
|
+
log
|
|
142
|
+
]
|
|
143
|
+
});
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const candidateBytes = currentBatchBytes + log.requestBytes + (currentBatch.length > 0 ? 1 : 0);
|
|
147
|
+
if (currentBatch.length > 0 && candidateBytes > LOG_REQUEST_BODY_MAX_BYTES) pushCurrentBatch();
|
|
148
|
+
if (0 === currentBatch.length) currentBatchStart = index;
|
|
149
|
+
currentBatchBytes += log.requestBytes + (currentBatch.length > 0 ? 1 : 0);
|
|
150
|
+
currentBatch.push(log);
|
|
151
|
+
});
|
|
152
|
+
pushCurrentBatch();
|
|
153
|
+
return actions;
|
|
154
|
+
}
|
|
155
|
+
async sendRequest(logs, config) {
|
|
156
|
+
const body = JSON.stringify(logs.map((log)=>log.request));
|
|
157
|
+
const maxRetries = Number.isFinite(config.maxRetries) ? Math.max(0, Math.floor(config.maxRetries)) : 0;
|
|
158
|
+
for(let attempt = 0; attempt <= maxRetries; attempt += 1){
|
|
159
|
+
if (utf8ByteLength(body) > LOG_REQUEST_BODY_MAX_BYTES) return {
|
|
160
|
+
kind: 'payload-too-large'
|
|
161
|
+
};
|
|
162
|
+
let response;
|
|
163
|
+
try {
|
|
164
|
+
response = await this.execFetch(config.endpoint, {
|
|
165
|
+
method: 'POST',
|
|
166
|
+
headers: config.headers,
|
|
167
|
+
body
|
|
168
|
+
});
|
|
169
|
+
} catch {
|
|
170
|
+
if (attempt >= maxRetries) return {
|
|
171
|
+
kind: 'network-error'
|
|
172
|
+
};
|
|
173
|
+
const retryNumber = attempt + 1;
|
|
174
|
+
this.originConsole.warn(`Failed to send logs (attempt ${retryNumber}), retrying in ${config.retryDelay * retryNumber}ms...`);
|
|
175
|
+
await this.delay(config.retryDelay * retryNumber);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
const status = response.status;
|
|
179
|
+
if (status >= 200 && status < 300) return {
|
|
180
|
+
kind: 'success'
|
|
181
|
+
};
|
|
182
|
+
return {
|
|
183
|
+
kind: 'http-error',
|
|
184
|
+
status
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
kind: 'network-error'
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
emitTerminal(logs, status, reason) {
|
|
192
|
+
if (0 === logs.length) return;
|
|
193
|
+
const first = logs[0];
|
|
194
|
+
const last = logs[logs.length - 1];
|
|
195
|
+
const sequence = {
|
|
196
|
+
first: first.sequence,
|
|
197
|
+
last: last.sequence,
|
|
198
|
+
firstId: boundedUtf8Preview(first.id, TERMINAL_ID_MAX_BYTES),
|
|
199
|
+
lastId: boundedUtf8Preview(last.id, TERMINAL_ID_MAX_BYTES)
|
|
200
|
+
};
|
|
201
|
+
const terminal = {
|
|
202
|
+
terminal: true,
|
|
203
|
+
status,
|
|
204
|
+
reason: boundedUtf8Preview(reason, TERMINAL_REASON_MAX_BYTES),
|
|
205
|
+
count: logs.length,
|
|
206
|
+
sequence
|
|
207
|
+
};
|
|
208
|
+
this.originConsole.error('[batch-logger-terminal]', terminal);
|
|
209
|
+
}
|
|
77
210
|
async execFetch(url, options) {
|
|
78
211
|
return fetch(url, options);
|
|
79
212
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const LOG_REQUEST_BODY_MAX_BYTES: number;
|
|
2
|
+
export declare function utf8ByteLength(value: string): number;
|
|
3
|
+
/** The exact wire size of a JSON array whose element sizes are already known. */
|
|
4
|
+
export declare function jsonArrayUtf8Bytes(elementBytes: readonly number[]): number;
|
|
5
|
+
/** Bounds both UTF-8 and JSON-escaped bytes without reading the entire value. */
|
|
6
|
+
export declare function boundedUtf8Preview(value: string, maxBytes: number): string;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const LOG_REQUEST_BODY_MAX_BYTES = 20971520;
|
|
2
|
+
const utf8Encoder = new TextEncoder();
|
|
3
|
+
function utf8ByteLength(value) {
|
|
4
|
+
return utf8Encoder.encode(value).byteLength;
|
|
5
|
+
}
|
|
6
|
+
function jsonArrayUtf8Bytes(elementBytes) {
|
|
7
|
+
if (0 === elementBytes.length) return 2;
|
|
8
|
+
return 2 + elementBytes.reduce((total, current)=>total + current, 0) + elementBytes.length - 1;
|
|
9
|
+
}
|
|
10
|
+
function boundedUtf8Preview(value, maxBytes) {
|
|
11
|
+
if (maxBytes <= 0 || 0 === value.length) return '';
|
|
12
|
+
let result = '';
|
|
13
|
+
let resultBytes = 0;
|
|
14
|
+
let escapedBytes = 0;
|
|
15
|
+
for (const character of value){
|
|
16
|
+
const characterBytes = utf8ByteLength(character);
|
|
17
|
+
const characterEscapedBytes = utf8ByteLength(JSON.stringify(character)) - 2;
|
|
18
|
+
if (resultBytes + characterBytes > maxBytes || escapedBytes + characterEscapedBytes > maxBytes) break;
|
|
19
|
+
result += character;
|
|
20
|
+
resultBytes += characterBytes;
|
|
21
|
+
escapedBytes += characterEscapedBytes;
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
export { LOG_REQUEST_BODY_MAX_BYTES, boundedUtf8Preview, jsonArrayUtf8Bytes, utf8ByteLength };
|