@zucker-framework/buffer 1.0.0
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 +201 -0
- package/NOTICE +22 -0
- package/THIRD_PARTY_NOTICES +4 -0
- package/dist/index.d.mts +130 -0
- package/dist/index.d.ts +130 -0
- package/dist/index.js +258 -0
- package/dist/index.mjs +227 -0
- package/package.json +35 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Zucker Framework
|
|
2
|
+
Copyright 2026 Lind and Zucker Framework contributors
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0. See LICENSE.
|
|
5
|
+
|
|
6
|
+
The framework includes TypeScript adaptations and enhancements of concepts and
|
|
7
|
+
implementations from hsweb-framework and jetlinks-community, both distributed
|
|
8
|
+
under the Apache License, Version 2.0. Individual packages use different subsets
|
|
9
|
+
of the framework. The TypeScript adaptations and Node.js integrations were
|
|
10
|
+
modified for Zucker Framework; they are not the original upstream distribution.
|
|
11
|
+
|
|
12
|
+
hsweb-framework
|
|
13
|
+
https://github.com/hs-web/hsweb-framework
|
|
14
|
+
Copyright 2020 http://hsweb.me
|
|
15
|
+
|
|
16
|
+
jetlinks-community
|
|
17
|
+
https://github.com/jetlinks/jetlinks-community
|
|
18
|
+
|
|
19
|
+
See THIRD_PARTY_NOTICES for license texts and attribution for bundled dependencies
|
|
20
|
+
and reference implementations relevant to this package. External dependencies
|
|
21
|
+
remain subject to their own licenses. This NOTICE is informational and does not
|
|
22
|
+
modify any license or grant rights to upstream trademarks.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Buffer 配置
|
|
3
|
+
*
|
|
4
|
+
* 对齐 jetlinks BufferSettings:
|
|
5
|
+
* - filePath / fileName 用于文件队列持久化
|
|
6
|
+
* - retryWhenError 谓词控制是否重试
|
|
7
|
+
* - parallelism 基于 CPU 核数的默认值
|
|
8
|
+
*/
|
|
9
|
+
interface BufferSettings {
|
|
10
|
+
/** 缓冲区大小,超过后自动刷新,默认 1000 */
|
|
11
|
+
bufferSize: number;
|
|
12
|
+
/** 刷新超时时间(毫秒),默认 2000 */
|
|
13
|
+
flushTimeoutMs: number;
|
|
14
|
+
/** 最大重试次数,默认 5(对齐 jetlinks 默认值) */
|
|
15
|
+
maxRetries: number;
|
|
16
|
+
/** 并行度,默认 CPU/2(对齐 jetlinks) */
|
|
17
|
+
parallelism: number;
|
|
18
|
+
/** 文件队列目录,用于内存溢出时持久化 */
|
|
19
|
+
fileQueueDir?: string;
|
|
20
|
+
/** 错误重试判断谓词,返回 true 表示应重试 */
|
|
21
|
+
retryWhenError?: (error: unknown) => boolean;
|
|
22
|
+
/** Buffer 名称,用于日志和指标 */
|
|
23
|
+
name?: string;
|
|
24
|
+
}
|
|
25
|
+
/** 默认重试判断:网络/IO 相关错误可重试 */
|
|
26
|
+
declare const defaultRetryWhenError: (error: unknown) => boolean;
|
|
27
|
+
declare const DEFAULT_BUFFER_SETTINGS: BufferSettings;
|
|
28
|
+
/**
|
|
29
|
+
* 缓冲条目接口 — 对应 jetlinks Buffered<T>
|
|
30
|
+
* 允许 handler 对每个条目标记重试或死信
|
|
31
|
+
*/
|
|
32
|
+
interface Buffered<T> {
|
|
33
|
+
/** 原始数据 */
|
|
34
|
+
readonly data: T;
|
|
35
|
+
/** 当前重试次数 */
|
|
36
|
+
readonly retryTimes: number;
|
|
37
|
+
/** 标记此条目需要重试 */
|
|
38
|
+
retry(shouldRetry?: boolean): void;
|
|
39
|
+
/** 标记此条目进入死信队列 */
|
|
40
|
+
dead(): void;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 刷新上下文 — 对应 jetlinks FlushContext<T>
|
|
44
|
+
* handler 可以通过此接口报告错误
|
|
45
|
+
*/
|
|
46
|
+
interface FlushContext<T> {
|
|
47
|
+
/** 报告错误信息 */
|
|
48
|
+
error(err: Error): void;
|
|
49
|
+
/** 本批次的缓冲条目列表 */
|
|
50
|
+
readonly items: ReadonlyArray<Buffered<T>>;
|
|
51
|
+
/** 本批次大小 */
|
|
52
|
+
readonly size: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 内存使用估算接口 — 对应 jetlinks MemoryUsage
|
|
56
|
+
* 实现此接口的数据类型可以提供精确的内存占用估算
|
|
57
|
+
*/
|
|
58
|
+
interface MemoryUsage {
|
|
59
|
+
/** 返回估算的字节数 */
|
|
60
|
+
usage(): number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type FlushHandler<T> = (items: T[]) => Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* 持久化缓冲 — 批量写入工具
|
|
66
|
+
*
|
|
67
|
+
* 支持:
|
|
68
|
+
* - 自动定时刷新
|
|
69
|
+
* - 缓冲区满时自动刷新
|
|
70
|
+
* - 内存溢出时写入文件队列
|
|
71
|
+
* - 失败项进入死信队列
|
|
72
|
+
* - 可配置并行度
|
|
73
|
+
*/
|
|
74
|
+
declare class PersistenceBuffer<T> {
|
|
75
|
+
private buffer;
|
|
76
|
+
private deadLetterQueue;
|
|
77
|
+
private flushTimer;
|
|
78
|
+
private handlers;
|
|
79
|
+
private flushing;
|
|
80
|
+
private settings;
|
|
81
|
+
private fileQueueDir;
|
|
82
|
+
private disposed;
|
|
83
|
+
/** Optional error callback for non-fatal flush failures */
|
|
84
|
+
onError?: (err: unknown) => void;
|
|
85
|
+
constructor(settings?: Partial<BufferSettings>);
|
|
86
|
+
/**
|
|
87
|
+
* 注册刷新处理器
|
|
88
|
+
*/
|
|
89
|
+
onFlush(handler: FlushHandler<T>): this;
|
|
90
|
+
/**
|
|
91
|
+
* 启动定时刷新
|
|
92
|
+
*/
|
|
93
|
+
start(): this;
|
|
94
|
+
/**
|
|
95
|
+
* 停止定时刷新并刷新剩余数据
|
|
96
|
+
*/
|
|
97
|
+
stop(): Promise<void>;
|
|
98
|
+
/**
|
|
99
|
+
* 写入缓冲
|
|
100
|
+
*/
|
|
101
|
+
write(item: T): void;
|
|
102
|
+
/**
|
|
103
|
+
* 批量写入
|
|
104
|
+
*/
|
|
105
|
+
writeMany(items: T[]): void;
|
|
106
|
+
/**
|
|
107
|
+
* 手动刷新
|
|
108
|
+
*/
|
|
109
|
+
flush(): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* 获取死信队列中的数据
|
|
112
|
+
*/
|
|
113
|
+
getDeadLetterQueue(): T[];
|
|
114
|
+
/**
|
|
115
|
+
* 清空死信队列
|
|
116
|
+
*/
|
|
117
|
+
clearDeadLetterQueue(): void;
|
|
118
|
+
/**
|
|
119
|
+
* 获取当前缓冲区大小
|
|
120
|
+
*/
|
|
121
|
+
get size(): number;
|
|
122
|
+
private processChunk;
|
|
123
|
+
/**
|
|
124
|
+
* 将数据写入文件队列(内存溢出保护)
|
|
125
|
+
*/
|
|
126
|
+
spillToFile(items: T[]): void;
|
|
127
|
+
private loadFromFileQueue;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export { type BufferSettings, type Buffered, DEFAULT_BUFFER_SETTINGS, type FlushContext, type FlushHandler, type MemoryUsage, PersistenceBuffer, defaultRetryWhenError };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Buffer 配置
|
|
3
|
+
*
|
|
4
|
+
* 对齐 jetlinks BufferSettings:
|
|
5
|
+
* - filePath / fileName 用于文件队列持久化
|
|
6
|
+
* - retryWhenError 谓词控制是否重试
|
|
7
|
+
* - parallelism 基于 CPU 核数的默认值
|
|
8
|
+
*/
|
|
9
|
+
interface BufferSettings {
|
|
10
|
+
/** 缓冲区大小,超过后自动刷新,默认 1000 */
|
|
11
|
+
bufferSize: number;
|
|
12
|
+
/** 刷新超时时间(毫秒),默认 2000 */
|
|
13
|
+
flushTimeoutMs: number;
|
|
14
|
+
/** 最大重试次数,默认 5(对齐 jetlinks 默认值) */
|
|
15
|
+
maxRetries: number;
|
|
16
|
+
/** 并行度,默认 CPU/2(对齐 jetlinks) */
|
|
17
|
+
parallelism: number;
|
|
18
|
+
/** 文件队列目录,用于内存溢出时持久化 */
|
|
19
|
+
fileQueueDir?: string;
|
|
20
|
+
/** 错误重试判断谓词,返回 true 表示应重试 */
|
|
21
|
+
retryWhenError?: (error: unknown) => boolean;
|
|
22
|
+
/** Buffer 名称,用于日志和指标 */
|
|
23
|
+
name?: string;
|
|
24
|
+
}
|
|
25
|
+
/** 默认重试判断:网络/IO 相关错误可重试 */
|
|
26
|
+
declare const defaultRetryWhenError: (error: unknown) => boolean;
|
|
27
|
+
declare const DEFAULT_BUFFER_SETTINGS: BufferSettings;
|
|
28
|
+
/**
|
|
29
|
+
* 缓冲条目接口 — 对应 jetlinks Buffered<T>
|
|
30
|
+
* 允许 handler 对每个条目标记重试或死信
|
|
31
|
+
*/
|
|
32
|
+
interface Buffered<T> {
|
|
33
|
+
/** 原始数据 */
|
|
34
|
+
readonly data: T;
|
|
35
|
+
/** 当前重试次数 */
|
|
36
|
+
readonly retryTimes: number;
|
|
37
|
+
/** 标记此条目需要重试 */
|
|
38
|
+
retry(shouldRetry?: boolean): void;
|
|
39
|
+
/** 标记此条目进入死信队列 */
|
|
40
|
+
dead(): void;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 刷新上下文 — 对应 jetlinks FlushContext<T>
|
|
44
|
+
* handler 可以通过此接口报告错误
|
|
45
|
+
*/
|
|
46
|
+
interface FlushContext<T> {
|
|
47
|
+
/** 报告错误信息 */
|
|
48
|
+
error(err: Error): void;
|
|
49
|
+
/** 本批次的缓冲条目列表 */
|
|
50
|
+
readonly items: ReadonlyArray<Buffered<T>>;
|
|
51
|
+
/** 本批次大小 */
|
|
52
|
+
readonly size: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 内存使用估算接口 — 对应 jetlinks MemoryUsage
|
|
56
|
+
* 实现此接口的数据类型可以提供精确的内存占用估算
|
|
57
|
+
*/
|
|
58
|
+
interface MemoryUsage {
|
|
59
|
+
/** 返回估算的字节数 */
|
|
60
|
+
usage(): number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type FlushHandler<T> = (items: T[]) => Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* 持久化缓冲 — 批量写入工具
|
|
66
|
+
*
|
|
67
|
+
* 支持:
|
|
68
|
+
* - 自动定时刷新
|
|
69
|
+
* - 缓冲区满时自动刷新
|
|
70
|
+
* - 内存溢出时写入文件队列
|
|
71
|
+
* - 失败项进入死信队列
|
|
72
|
+
* - 可配置并行度
|
|
73
|
+
*/
|
|
74
|
+
declare class PersistenceBuffer<T> {
|
|
75
|
+
private buffer;
|
|
76
|
+
private deadLetterQueue;
|
|
77
|
+
private flushTimer;
|
|
78
|
+
private handlers;
|
|
79
|
+
private flushing;
|
|
80
|
+
private settings;
|
|
81
|
+
private fileQueueDir;
|
|
82
|
+
private disposed;
|
|
83
|
+
/** Optional error callback for non-fatal flush failures */
|
|
84
|
+
onError?: (err: unknown) => void;
|
|
85
|
+
constructor(settings?: Partial<BufferSettings>);
|
|
86
|
+
/**
|
|
87
|
+
* 注册刷新处理器
|
|
88
|
+
*/
|
|
89
|
+
onFlush(handler: FlushHandler<T>): this;
|
|
90
|
+
/**
|
|
91
|
+
* 启动定时刷新
|
|
92
|
+
*/
|
|
93
|
+
start(): this;
|
|
94
|
+
/**
|
|
95
|
+
* 停止定时刷新并刷新剩余数据
|
|
96
|
+
*/
|
|
97
|
+
stop(): Promise<void>;
|
|
98
|
+
/**
|
|
99
|
+
* 写入缓冲
|
|
100
|
+
*/
|
|
101
|
+
write(item: T): void;
|
|
102
|
+
/**
|
|
103
|
+
* 批量写入
|
|
104
|
+
*/
|
|
105
|
+
writeMany(items: T[]): void;
|
|
106
|
+
/**
|
|
107
|
+
* 手动刷新
|
|
108
|
+
*/
|
|
109
|
+
flush(): Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* 获取死信队列中的数据
|
|
112
|
+
*/
|
|
113
|
+
getDeadLetterQueue(): T[];
|
|
114
|
+
/**
|
|
115
|
+
* 清空死信队列
|
|
116
|
+
*/
|
|
117
|
+
clearDeadLetterQueue(): void;
|
|
118
|
+
/**
|
|
119
|
+
* 获取当前缓冲区大小
|
|
120
|
+
*/
|
|
121
|
+
get size(): number;
|
|
122
|
+
private processChunk;
|
|
123
|
+
/**
|
|
124
|
+
* 将数据写入文件队列(内存溢出保护)
|
|
125
|
+
*/
|
|
126
|
+
spillToFile(items: T[]): void;
|
|
127
|
+
private loadFromFileQueue;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export { type BufferSettings, type Buffered, DEFAULT_BUFFER_SETTINGS, type FlushContext, type FlushHandler, type MemoryUsage, PersistenceBuffer, defaultRetryWhenError };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
29
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
|
|
31
|
+
// src/index.ts
|
|
32
|
+
var index_exports = {};
|
|
33
|
+
__export(index_exports, {
|
|
34
|
+
DEFAULT_BUFFER_SETTINGS: () => DEFAULT_BUFFER_SETTINGS,
|
|
35
|
+
PersistenceBuffer: () => PersistenceBuffer,
|
|
36
|
+
defaultRetryWhenError: () => defaultRetryWhenError
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(index_exports);
|
|
39
|
+
|
|
40
|
+
// src/persistence-buffer.ts
|
|
41
|
+
var fs = __toESM(require("fs"));
|
|
42
|
+
var path = __toESM(require("path"));
|
|
43
|
+
var os = __toESM(require("os"));
|
|
44
|
+
var import_core = require("@zucker-framework/core");
|
|
45
|
+
|
|
46
|
+
// src/buffer-settings.ts
|
|
47
|
+
var defaultRetryWhenError = /* @__PURE__ */ __name((error) => {
|
|
48
|
+
if (error instanceof Error) {
|
|
49
|
+
const msg = error.message.toLowerCase();
|
|
50
|
+
return msg.includes("timeout") || msg.includes("econnrefused") || msg.includes("econnreset") || msg.includes("epipe") || msg.includes("network") || msg.includes("unavailable") || msg.includes("deadlock");
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}, "defaultRetryWhenError");
|
|
54
|
+
function getDefaultParallelism() {
|
|
55
|
+
try {
|
|
56
|
+
const os2 = require("os");
|
|
57
|
+
return Math.max(1, Math.floor(os2.cpus().length / 2));
|
|
58
|
+
} catch {
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
__name(getDefaultParallelism, "getDefaultParallelism");
|
|
63
|
+
var DEFAULT_BUFFER_SETTINGS = {
|
|
64
|
+
bufferSize: 1e3,
|
|
65
|
+
flushTimeoutMs: 2e3,
|
|
66
|
+
maxRetries: 5,
|
|
67
|
+
parallelism: getDefaultParallelism(),
|
|
68
|
+
retryWhenError: defaultRetryWhenError
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// src/persistence-buffer.ts
|
|
72
|
+
var PersistenceBuffer = class {
|
|
73
|
+
static {
|
|
74
|
+
__name(this, "PersistenceBuffer");
|
|
75
|
+
}
|
|
76
|
+
buffer = [];
|
|
77
|
+
deadLetterQueue = [];
|
|
78
|
+
flushTimer = null;
|
|
79
|
+
handlers = [];
|
|
80
|
+
flushing = false;
|
|
81
|
+
settings;
|
|
82
|
+
fileQueueDir;
|
|
83
|
+
disposed = false;
|
|
84
|
+
/** Optional error callback for non-fatal flush failures */
|
|
85
|
+
onError;
|
|
86
|
+
constructor(settings) {
|
|
87
|
+
this.settings = {
|
|
88
|
+
...DEFAULT_BUFFER_SETTINGS,
|
|
89
|
+
...settings
|
|
90
|
+
};
|
|
91
|
+
this.fileQueueDir = this.settings.fileQueueDir ?? path.join(os.tmpdir(), "zucker-buffer");
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 注册刷新处理器
|
|
95
|
+
*/
|
|
96
|
+
onFlush(handler) {
|
|
97
|
+
this.handlers.push(handler);
|
|
98
|
+
return this;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* 启动定时刷新
|
|
102
|
+
*/
|
|
103
|
+
start() {
|
|
104
|
+
if (this.flushTimer) return this;
|
|
105
|
+
this.flushTimer = setInterval(() => {
|
|
106
|
+
this.flush().catch((err) => {
|
|
107
|
+
if (this.onError) this.onError(err);
|
|
108
|
+
});
|
|
109
|
+
}, this.settings.flushTimeoutMs);
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* 停止定时刷新并刷新剩余数据
|
|
114
|
+
*/
|
|
115
|
+
async stop() {
|
|
116
|
+
this.disposed = true;
|
|
117
|
+
if (this.flushTimer) {
|
|
118
|
+
clearInterval(this.flushTimer);
|
|
119
|
+
this.flushTimer = null;
|
|
120
|
+
}
|
|
121
|
+
await this.flush();
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* 写入缓冲
|
|
125
|
+
*/
|
|
126
|
+
write(item) {
|
|
127
|
+
if (this.disposed) {
|
|
128
|
+
throw new import_core.BusinessException("Buffer has been disposed", "BUFFER_DISPOSED", 500);
|
|
129
|
+
}
|
|
130
|
+
this.buffer.push(item);
|
|
131
|
+
if (this.buffer.length >= this.settings.bufferSize) {
|
|
132
|
+
this.flush().catch((err) => {
|
|
133
|
+
if (this.onError) this.onError(err);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* 批量写入
|
|
139
|
+
*/
|
|
140
|
+
writeMany(items) {
|
|
141
|
+
if (!items || items.length === 0) return;
|
|
142
|
+
for (const item of items) {
|
|
143
|
+
this.write(item);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* 手动刷新
|
|
148
|
+
*/
|
|
149
|
+
async flush() {
|
|
150
|
+
if (this.flushing || this.buffer.length === 0) return;
|
|
151
|
+
this.flushing = true;
|
|
152
|
+
try {
|
|
153
|
+
const items = this.buffer.splice(0);
|
|
154
|
+
const fileItems = this.loadFromFileQueue();
|
|
155
|
+
const allItems = [
|
|
156
|
+
...fileItems,
|
|
157
|
+
...items
|
|
158
|
+
];
|
|
159
|
+
if (allItems.length === 0) return;
|
|
160
|
+
const chunkSize = Math.ceil(allItems.length / this.settings.parallelism);
|
|
161
|
+
const chunks = [];
|
|
162
|
+
for (let i = 0; i < allItems.length; i += chunkSize) {
|
|
163
|
+
chunks.push(allItems.slice(i, i + chunkSize));
|
|
164
|
+
}
|
|
165
|
+
await Promise.all(chunks.map((chunk) => this.processChunk(chunk)));
|
|
166
|
+
} finally {
|
|
167
|
+
this.flushing = false;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* 获取死信队列中的数据
|
|
172
|
+
*/
|
|
173
|
+
getDeadLetterQueue() {
|
|
174
|
+
return [
|
|
175
|
+
...this.deadLetterQueue
|
|
176
|
+
];
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* 清空死信队列
|
|
180
|
+
*/
|
|
181
|
+
clearDeadLetterQueue() {
|
|
182
|
+
this.deadLetterQueue = [];
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* 获取当前缓冲区大小
|
|
186
|
+
*/
|
|
187
|
+
get size() {
|
|
188
|
+
return this.buffer.length;
|
|
189
|
+
}
|
|
190
|
+
async processChunk(items) {
|
|
191
|
+
let retries = 0;
|
|
192
|
+
while (retries <= this.settings.maxRetries) {
|
|
193
|
+
try {
|
|
194
|
+
for (const handler of this.handlers) {
|
|
195
|
+
await handler(items);
|
|
196
|
+
}
|
|
197
|
+
return;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
retries++;
|
|
200
|
+
const shouldRetry = this.settings.retryWhenError?.(err) ?? false;
|
|
201
|
+
if (!shouldRetry || retries > this.settings.maxRetries) {
|
|
202
|
+
if (this.onError) this.onError(err);
|
|
203
|
+
this.deadLetterQueue.push(...items);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
await new Promise((r) => setTimeout(r, Math.min(100 * Math.pow(2, retries), 5e3)));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* 将数据写入文件队列(内存溢出保护)
|
|
212
|
+
*/
|
|
213
|
+
spillToFile(items) {
|
|
214
|
+
if (!items || items.length === 0) return;
|
|
215
|
+
try {
|
|
216
|
+
if (!fs.existsSync(this.fileQueueDir)) {
|
|
217
|
+
fs.mkdirSync(this.fileQueueDir, {
|
|
218
|
+
recursive: true
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
const filename = `buffer-${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
|
|
222
|
+
fs.writeFileSync(path.join(this.fileQueueDir, filename), JSON.stringify(items));
|
|
223
|
+
} catch (err) {
|
|
224
|
+
if (this.onError) this.onError(err);
|
|
225
|
+
this.deadLetterQueue.push(...items);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
loadFromFileQueue() {
|
|
229
|
+
const items = [];
|
|
230
|
+
try {
|
|
231
|
+
if (!fs.existsSync(this.fileQueueDir)) return items;
|
|
232
|
+
const files = fs.readdirSync(this.fileQueueDir).filter((f) => f.endsWith(".json"));
|
|
233
|
+
for (const file of files) {
|
|
234
|
+
const filePath = path.join(this.fileQueueDir, file);
|
|
235
|
+
try {
|
|
236
|
+
const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
237
|
+
if (Array.isArray(data)) items.push(...data);
|
|
238
|
+
fs.unlinkSync(filePath);
|
|
239
|
+
} catch (parseErr) {
|
|
240
|
+
if (this.onError) this.onError(parseErr);
|
|
241
|
+
try {
|
|
242
|
+
fs.unlinkSync(filePath);
|
|
243
|
+
} catch {
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
} catch (dirErr) {
|
|
248
|
+
if (this.onError) this.onError(dirErr);
|
|
249
|
+
}
|
|
250
|
+
return items;
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
254
|
+
0 && (module.exports = {
|
|
255
|
+
DEFAULT_BUFFER_SETTINGS,
|
|
256
|
+
PersistenceBuffer,
|
|
257
|
+
defaultRetryWhenError
|
|
258
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
// src/persistence-buffer.ts
|
|
11
|
+
import * as fs from "fs";
|
|
12
|
+
import * as path from "path";
|
|
13
|
+
import * as os from "os";
|
|
14
|
+
import { BusinessException } from "@zucker-framework/core";
|
|
15
|
+
|
|
16
|
+
// src/buffer-settings.ts
|
|
17
|
+
var defaultRetryWhenError = /* @__PURE__ */ __name((error) => {
|
|
18
|
+
if (error instanceof Error) {
|
|
19
|
+
const msg = error.message.toLowerCase();
|
|
20
|
+
return msg.includes("timeout") || msg.includes("econnrefused") || msg.includes("econnreset") || msg.includes("epipe") || msg.includes("network") || msg.includes("unavailable") || msg.includes("deadlock");
|
|
21
|
+
}
|
|
22
|
+
return false;
|
|
23
|
+
}, "defaultRetryWhenError");
|
|
24
|
+
function getDefaultParallelism() {
|
|
25
|
+
try {
|
|
26
|
+
const os2 = __require("os");
|
|
27
|
+
return Math.max(1, Math.floor(os2.cpus().length / 2));
|
|
28
|
+
} catch {
|
|
29
|
+
return 1;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
__name(getDefaultParallelism, "getDefaultParallelism");
|
|
33
|
+
var DEFAULT_BUFFER_SETTINGS = {
|
|
34
|
+
bufferSize: 1e3,
|
|
35
|
+
flushTimeoutMs: 2e3,
|
|
36
|
+
maxRetries: 5,
|
|
37
|
+
parallelism: getDefaultParallelism(),
|
|
38
|
+
retryWhenError: defaultRetryWhenError
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// src/persistence-buffer.ts
|
|
42
|
+
var PersistenceBuffer = class {
|
|
43
|
+
static {
|
|
44
|
+
__name(this, "PersistenceBuffer");
|
|
45
|
+
}
|
|
46
|
+
buffer = [];
|
|
47
|
+
deadLetterQueue = [];
|
|
48
|
+
flushTimer = null;
|
|
49
|
+
handlers = [];
|
|
50
|
+
flushing = false;
|
|
51
|
+
settings;
|
|
52
|
+
fileQueueDir;
|
|
53
|
+
disposed = false;
|
|
54
|
+
/** Optional error callback for non-fatal flush failures */
|
|
55
|
+
onError;
|
|
56
|
+
constructor(settings) {
|
|
57
|
+
this.settings = {
|
|
58
|
+
...DEFAULT_BUFFER_SETTINGS,
|
|
59
|
+
...settings
|
|
60
|
+
};
|
|
61
|
+
this.fileQueueDir = this.settings.fileQueueDir ?? path.join(os.tmpdir(), "zucker-buffer");
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 注册刷新处理器
|
|
65
|
+
*/
|
|
66
|
+
onFlush(handler) {
|
|
67
|
+
this.handlers.push(handler);
|
|
68
|
+
return this;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* 启动定时刷新
|
|
72
|
+
*/
|
|
73
|
+
start() {
|
|
74
|
+
if (this.flushTimer) return this;
|
|
75
|
+
this.flushTimer = setInterval(() => {
|
|
76
|
+
this.flush().catch((err) => {
|
|
77
|
+
if (this.onError) this.onError(err);
|
|
78
|
+
});
|
|
79
|
+
}, this.settings.flushTimeoutMs);
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* 停止定时刷新并刷新剩余数据
|
|
84
|
+
*/
|
|
85
|
+
async stop() {
|
|
86
|
+
this.disposed = true;
|
|
87
|
+
if (this.flushTimer) {
|
|
88
|
+
clearInterval(this.flushTimer);
|
|
89
|
+
this.flushTimer = null;
|
|
90
|
+
}
|
|
91
|
+
await this.flush();
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 写入缓冲
|
|
95
|
+
*/
|
|
96
|
+
write(item) {
|
|
97
|
+
if (this.disposed) {
|
|
98
|
+
throw new BusinessException("Buffer has been disposed", "BUFFER_DISPOSED", 500);
|
|
99
|
+
}
|
|
100
|
+
this.buffer.push(item);
|
|
101
|
+
if (this.buffer.length >= this.settings.bufferSize) {
|
|
102
|
+
this.flush().catch((err) => {
|
|
103
|
+
if (this.onError) this.onError(err);
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* 批量写入
|
|
109
|
+
*/
|
|
110
|
+
writeMany(items) {
|
|
111
|
+
if (!items || items.length === 0) return;
|
|
112
|
+
for (const item of items) {
|
|
113
|
+
this.write(item);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* 手动刷新
|
|
118
|
+
*/
|
|
119
|
+
async flush() {
|
|
120
|
+
if (this.flushing || this.buffer.length === 0) return;
|
|
121
|
+
this.flushing = true;
|
|
122
|
+
try {
|
|
123
|
+
const items = this.buffer.splice(0);
|
|
124
|
+
const fileItems = this.loadFromFileQueue();
|
|
125
|
+
const allItems = [
|
|
126
|
+
...fileItems,
|
|
127
|
+
...items
|
|
128
|
+
];
|
|
129
|
+
if (allItems.length === 0) return;
|
|
130
|
+
const chunkSize = Math.ceil(allItems.length / this.settings.parallelism);
|
|
131
|
+
const chunks = [];
|
|
132
|
+
for (let i = 0; i < allItems.length; i += chunkSize) {
|
|
133
|
+
chunks.push(allItems.slice(i, i + chunkSize));
|
|
134
|
+
}
|
|
135
|
+
await Promise.all(chunks.map((chunk) => this.processChunk(chunk)));
|
|
136
|
+
} finally {
|
|
137
|
+
this.flushing = false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* 获取死信队列中的数据
|
|
142
|
+
*/
|
|
143
|
+
getDeadLetterQueue() {
|
|
144
|
+
return [
|
|
145
|
+
...this.deadLetterQueue
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* 清空死信队列
|
|
150
|
+
*/
|
|
151
|
+
clearDeadLetterQueue() {
|
|
152
|
+
this.deadLetterQueue = [];
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* 获取当前缓冲区大小
|
|
156
|
+
*/
|
|
157
|
+
get size() {
|
|
158
|
+
return this.buffer.length;
|
|
159
|
+
}
|
|
160
|
+
async processChunk(items) {
|
|
161
|
+
let retries = 0;
|
|
162
|
+
while (retries <= this.settings.maxRetries) {
|
|
163
|
+
try {
|
|
164
|
+
for (const handler of this.handlers) {
|
|
165
|
+
await handler(items);
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
} catch (err) {
|
|
169
|
+
retries++;
|
|
170
|
+
const shouldRetry = this.settings.retryWhenError?.(err) ?? false;
|
|
171
|
+
if (!shouldRetry || retries > this.settings.maxRetries) {
|
|
172
|
+
if (this.onError) this.onError(err);
|
|
173
|
+
this.deadLetterQueue.push(...items);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
await new Promise((r) => setTimeout(r, Math.min(100 * Math.pow(2, retries), 5e3)));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 将数据写入文件队列(内存溢出保护)
|
|
182
|
+
*/
|
|
183
|
+
spillToFile(items) {
|
|
184
|
+
if (!items || items.length === 0) return;
|
|
185
|
+
try {
|
|
186
|
+
if (!fs.existsSync(this.fileQueueDir)) {
|
|
187
|
+
fs.mkdirSync(this.fileQueueDir, {
|
|
188
|
+
recursive: true
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const filename = `buffer-${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
|
|
192
|
+
fs.writeFileSync(path.join(this.fileQueueDir, filename), JSON.stringify(items));
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (this.onError) this.onError(err);
|
|
195
|
+
this.deadLetterQueue.push(...items);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
loadFromFileQueue() {
|
|
199
|
+
const items = [];
|
|
200
|
+
try {
|
|
201
|
+
if (!fs.existsSync(this.fileQueueDir)) return items;
|
|
202
|
+
const files = fs.readdirSync(this.fileQueueDir).filter((f) => f.endsWith(".json"));
|
|
203
|
+
for (const file of files) {
|
|
204
|
+
const filePath = path.join(this.fileQueueDir, file);
|
|
205
|
+
try {
|
|
206
|
+
const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
207
|
+
if (Array.isArray(data)) items.push(...data);
|
|
208
|
+
fs.unlinkSync(filePath);
|
|
209
|
+
} catch (parseErr) {
|
|
210
|
+
if (this.onError) this.onError(parseErr);
|
|
211
|
+
try {
|
|
212
|
+
fs.unlinkSync(filePath);
|
|
213
|
+
} catch {
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
} catch (dirErr) {
|
|
218
|
+
if (this.onError) this.onError(dirErr);
|
|
219
|
+
}
|
|
220
|
+
return items;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
export {
|
|
224
|
+
DEFAULT_BUFFER_SETTINGS,
|
|
225
|
+
PersistenceBuffer,
|
|
226
|
+
defaultRetryWhenError
|
|
227
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zucker-framework/buffer",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"main": "dist/index.js",
|
|
5
|
+
"module": "dist/index.mjs",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"LICENSE",
|
|
10
|
+
"NOTICE",
|
|
11
|
+
"THIRD_PARTY_NOTICES"
|
|
12
|
+
],
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@zucker-framework/core": "1.0.0"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@types/node": "^20.19.43"
|
|
18
|
+
},
|
|
19
|
+
"license": "Apache-2.0",
|
|
20
|
+
"author": "Lind",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/Lind-pro/zucker-framework.git",
|
|
24
|
+
"directory": "packages/buffer"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "tsup src/index.ts --format cjs,esm --dts",
|
|
32
|
+
"clean": "rm -rf dist",
|
|
33
|
+
"lint": "eslint src/"
|
|
34
|
+
}
|
|
35
|
+
}
|