123 lines
6.4 KiB
Markdown
123 lines
6.4 KiB
Markdown
# 本地文件队列(app.fileWriter)
|
||
|
||
本文档说明仓库中提供的本地文件队列写入能力(实现文件:app/lib/file_writer.js),用于把业务数据按 JSON Lines 追加到本地文件并由消费者按需读取处理,适合低延迟、本地持久化、批处理/异步消费场景。
|
||
|
||
**实现要点(写入特性)**
|
||
- 串行写入:同一进程内通过内部队列 `enqueue` 串行化写入,保证单进程内顺序性。
|
||
- 强制落盘:每次写入使用文件句柄写入并调用 `handle.sync()` 进行 fsync,尽量保证数据落盘。
|
||
- 自动轮转:当当前文件大小 + 待写入字节数 超过 `maxFileSize` 时,会自增序号并切换到新文件(sequence)。
|
||
- 自动按行轮转:当单个数据文件累计达到 `maxFileLines` 行后,下一条写入会自动切换到下一个 sequence 文件,默认阈值为 `2000` 行。
|
||
- 目录结构:默认 baseDir 下按业务与日期分区:
|
||
- baseDir/<businessSegment>/<YYYY>/<MM>/<DD>/
|
||
- 文件命名:文件前缀包含业务段与进程标识(`<business>-<machine>-<worker>-p<pid>-<seq>`),尾部带序号与扩展名(`fileExtension`,默认 `.log`)。
|
||
- 进度(.progress)断点续传:每个消费者使用独立的隐藏进度文件(以 `.<consumerName>.progress` 命名),写入采用临时文件+rename 的原子替换策略,消费端可通过进度恢复消费位置。
|
||
- Worker/进程隔离:写入文件名包含 `machineId`、`workerId` 与 `pid`,不同进程不会写入同一文件,避免互相竞争。
|
||
- 清理策略:基于 `retentionDays` 定期删除过期的数据文件与进度文件。
|
||
|
||
**目录与文件示例**
|
||
- 目录:`/path/to/runtime/file-writer/orders/2026/04/09/`
|
||
- 数据文件示例:`orders-myhost-worker1-p1234-0001.log`
|
||
- 进度文件示例:`.consumer-1.progress`(位于同一分区目录下)
|
||
|
||
**配置项说明(config.fileWriter)**
|
||
- `baseDir`:基础目录,默认 `path.join(app.baseDir, 'runtime', 'file-writer')`。
|
||
- `maxFileSize`:单文件最大字节数,超过后轮转。支持数字(字节)或带单位字符串(如 `100M`、`1G`)。默认 `100 * 1024 * 1024`(100MB)。
|
||
- `maxFileLines`:单文件最大行数,达到后下一条写入会自动轮转到新的 sequence 文件。默认 `2000`。
|
||
- `retentionDays`:保留天数,超过则删除。设为 `0` 或负值可禁用清理。默认 `7`。
|
||
- `cleanupIntervalMs`:触发清理的最小间隔(毫秒),写入时会基于此决定是否执行清理,设置为 `0` 或负值可禁用定期清理。默认 `3600000`(1 小时)。
|
||
- `sequenceWidth`:文件序号宽度(零填充),默认 `4`(例如 `0001`)。
|
||
- `fileExtension`:数据文件扩展名,默认 `.log`。
|
||
- `progressExtension`:进度文件扩展名,默认 `.progress`。
|
||
- `machineId`、`workerId`(可选):可通过配置覆盖,默认使用主机名与 `process.env.EGG_WORKER_ID`。
|
||
|
||
默认配置位置:`config/config.default.js` 的 `config.fileWriter` 节点。
|
||
|
||
示例(可放入 `config/config.local.js` 覆盖默认):
|
||
|
||
```js
|
||
const path = require('path');
|
||
|
||
exports.fileWriter = {
|
||
baseDir: path.join(__dirname, '..', 'runtime', 'file-writer'),
|
||
maxFileSize: '200M',
|
||
maxFileLines: 2000,
|
||
retentionDays: 14,
|
||
cleanupIntervalMs: 60 * 60 * 1000,
|
||
sequenceWidth: 4,
|
||
fileExtension: '.log',
|
||
progressExtension: '.progress',
|
||
// machineId: 'my-host',
|
||
// workerId: 'worker-1',
|
||
};
|
||
```
|
||
|
||
**写入示例(业务侧)**
|
||
简单写入(在任何可以访问 `app` 的位置):
|
||
|
||
```js
|
||
// 在 controller/service 中
|
||
await app.fileWriter.write('orders', { id: 123, event: 'created', payload: { /* ... */ } });
|
||
// 返回对象包含 filePath、sequence、bytesWritten 等信息
|
||
```
|
||
|
||
**消费/读取示例(推荐使用 app.fileWriter 提供的 API)**
|
||
推荐使用 `getProgressFilePath` + `consumeFiles` 提供的断点续传能力:
|
||
|
||
```js
|
||
// 示例:定期或守护进程式消费 orders
|
||
async function consumeOrders(app) {
|
||
const writer = app.fileWriter;
|
||
const progressFile = writer.getProgressFilePath('orders', new Date(), 'order-consumer-1');
|
||
|
||
const result = await writer.consumeFiles({
|
||
businessName: 'orders',
|
||
progressFilePath: progressFile,
|
||
onRecord: async (record, meta) => {
|
||
// record: 解析后的对象
|
||
// meta: { filePath, offset, index }
|
||
// 在这里实现消息处理逻辑(去重、入库、调用外部服务等)
|
||
},
|
||
parseJson: true,
|
||
});
|
||
|
||
return result; // 包含 processedCount 与最新 progress
|
||
}
|
||
```
|
||
|
||
如需逐文件手动控制消费,也可使用 `readRecords`:
|
||
|
||
```js
|
||
const res = await app.fileWriter.readRecords(filePath, { startOffset: 0 });
|
||
for (const rec of res.records) {
|
||
// 处理 rec
|
||
}
|
||
// 手动保存进度
|
||
await app.fileWriter.saveProgress(progressFilePath, {
|
||
filePath,
|
||
offset: res.nextOffset,
|
||
processedCount: (previousCount || 0) + res.records.length,
|
||
});
|
||
```
|
||
|
||
**进度文件(.progress)格式**
|
||
- 保存为 JSON,包含至少字段:`filePath`、`offset`、`processedCount`、`updatedAt`。
|
||
- 写入采用临时文件写入 + `fsync` + `rename` 的方式尽量保证原子性。
|
||
|
||
**注意事项 / 运行时建议**
|
||
- 不要通过静态文件服务或外部 URL 直接暴露 `baseDir`(例如 `runtime/`),避免被外部下载或篡改。
|
||
- 多 Worker / 多机部署:
|
||
- 默认每个进程生成独立的数据文件(文件名包含 `machineId`、`workerId`、`pid`),不会有多个进程同时写入同一文件。若你的设计需要跨进程全局严格顺序,请在上游统一入口合并写入或使用集中式队列(如 Kafka/Redis)。
|
||
- 消费者可以按进程拆分(针对单进程的文件)或由独立中心消费者按文件目录遍历处理。
|
||
- 可通过配置显式设置 `machineId`/`workerId` 来标识不同实例。
|
||
- 关闭或调整清理策略:若需长期保留数据,请将 `retentionDays` 设为合适值或禁用清理(`0` 或负值)。
|
||
- 性能角度:每次写入触发 fsync 会有性能开销,适合需要高可靠性的场景;若对持久性要求不高,可考虑将写入逻辑改为批量 fsync(此处为实现约束,不建议直接修改核心行为)。
|
||
|
||
---
|
||
|
||
如果希望在项目首页或工具箱中添加跳转链接,建议把一行链接加入到 [README.md](README.md) 或 [AI_TOOLBOX.md](AI_TOOLBOX.md) 的相关位置,指向本文件 `docs/file-writer.md`。
|
||
|
||
----
|
||
**参考实现位置**
|
||
- 代码实现:app/lib/file_writer.js
|
||
- 默认配置:config/config.default.js -> `config.fileWriter`
|