# @gobing-ai/ts-infra 中文文档

规范地址：https://npmcn.com/package/%40gobing-ai/ts-infra/

版本：0\.7\.1
npm 元数据更新时间：2026-10-25T00:55:28.899Z
中文译文更新时间：2026-11-16T17:50:55.001Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gobing-ai/ts-infra
原文对照：https://npmcn.com/package/%40gobing-ai/ts-infra/?lang=original
项目主页：https://github.com/gobing-ai/ts-libs#readme
源码仓库：https://github.com/gobing-ai/ts-libs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：558 kB，162 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：@gobing-ai/ts-db ^0\.7\.1，@opentelemetry/api ^1\.9\.0，@gobing-ai/ts-runtime ^0\.7\.1，@opentelemetry/resources ^2\.0\.0，@opentelemetry/sdk-metrics ^2\.0\.0，@opentelemetry/sdk-trace-node ^2\.0\.0，@opentelemetry/semantic-conventions ^1\.30\.0，@opentelemetry/exporter-trace-otlp-http \>=0\.200\.0，@opentelemetry/exporter-metrics-otlp-http \>=0\.200\.0
- 首次发布：2026-05-29T16:57:28.023Z
- 最新版本发布：2026-10-25T00:55:28.542Z
- 近 30 天下载量：4135（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：136（近 12 个月 136 个）

## 中文简介

@gobing-ai/ts-infra — 基础设施主干线:事件总线,工作队列,排程器,遥测,API客户端,以及日志.

## 安装

```sh
npm install @gobing-ai/ts-infra
```

也可以使用：`pnpm add @gobing-ai/ts-infra`、`yarn add @gobing-ai/ts-infra`、`bun add @gobing-ai/ts-infra`

## README

# @gobing-ai/ts-infra (英语)

基础设施主干线——打出事件总线,队列/排程合同,适配子路径,OpenTeleometry仪器,HTTP API客户端,以及结构化记录.

## 概览

`ts-infra` 提供构成应用程序主干线的子系统:

| 子系统 | 模块 | 目的 |
| --- | --- | --- |
| **活动总线** | `event-bus/` | 键入有同步 + async 调度的 pub/ sub, 命名为 async 处理器, 队列消费者桥, 生命周期自监视 |
| **任务队列** | 核心 + `/job-queue-db` | 核心中的队列接口; DB 后置的正弦/相容流( C)`DBJobQueue`, (中文(简体) ), `DBQueueConsumer`)通过选入子路径;可选类型事件排放 |
| **调度器** | 核心 + 调度子路径 | 排程合同、登记、内置行动、核心中的节点适配器;节点和Cloudflare适配器,通过选入子路径 |
| **遥测** | `telemetry/` | OTEL 仪器——追踪`traceAsync`)带有主开关,度量衡(12个仪器),SQL消毒器;选入OTLP通过 `/otel-node` 子路径 |
| **API 客户端** | `api-client.ts` | 输入了 HTTP 客户端, 带有 OTel 追踪、 超时、 按请求中止、 可选事件排放 |
| **锁定器** | `logger.ts` | LogTape 后置结构记录器,包含级别、儿童记录器、可注入汇和哑弹切换 |
| **应用程序启动** | `application/` | 插件驱动的生命周期:确定启动 — 关闭、DI 协调、服务作为插件 |
| **插件主机** | `application/plugins/` | 插入有序的插件注册、 故障快活/ 故障软化的生命周期扇出、 理性的撕裂 |

## 建筑

```mermaid
classDiagram
    namespace event-bus {
        class EventBus~TEvents~ {
            +on(event, handler, opts?) void
            +once(event, handler, opts?) void
            +off(event, handler) void
            +emit(event, ...args) Promise~void~
            +removeAllListeners(event?) void
            +listenerCount(event) number
            +eventNames() string[]
            +createJobHandler() JobHandler<AsyncEventJobPayload>
        }
    }

    namespace job-queue {
        class JobQueue~T~ {
            <<interface>>
            +enqueue(type, payload, opts?) Promise~string~
            +enqueueBatch(jobs) Promise~string[]~
        }
        class QueueConsumer~T~ {
            <<interface>>
            +register(type, handler) void
            +start() Promise~void~
            +stop() Promise~void~
            +stats() Promise~QueueStats~
        }
        class DBJobQueue~T~ {
            +enqueue(type, payload, opts?) Promise~string~
            +enqueueBatch(jobs) Promise~string[]~
            +stats() Promise~QueueStats~
        }
        class DBQueueConsumer~T~ {
            +register(type, handler) void
            +start() Promise~void~
            +stop() Promise~void~
            +processOnce() Promise~number~
            +stats() Promise~QueueStats~
        }
        class Job~T~ {
            <<interface>>
        }
        class QueueStats {
            <<interface>>
        }
    }

    namespace scheduler {
        class SchedulerAdapter {
            <<interface>>
            +register(cron, action, options?) void
            +start() Promise~void~
            +stop() Promise~void~
        }
        class NodeSchedulerAdapter {
        }
        class CloudflareSchedulerAdapter {
        }
        class NoopSchedulerAdapter {
        }
        class SchedulerFactory {
            +initScheduler(cronEntries?) SchedulerAdapter
            +setSchedulerAdapter(adapter) void
            +getSchedulerAdapter() SchedulerAdapter
        }
    }

    namespace telemetry {
        class TelemetrySDK {
            +initTelemetry(config?) void
            +shutdownTelemetry() Promise~void~
            +getTracer() Tracer
        }
        class Tracing {
            +traceAsync~T~(name, fn) Promise~T~
            +traceSync~T~(name, fn) T
            +addSpanAttributes(attrs) void
            +getActiveSpan() Span
        }
        class Metrics {
            +getHttpClientRequestTotal() Counter
            +getHttpClientRequestDuration() Histogram
            +getEventbusEmitsTotal() Counter
            +getQueueJobEnqueuedTotal() Counter
            +getSchedulerJobExecutedTotal() Counter
        }
        class OtelNode {
            +initNodeTelemetry(opts) void
            +shutdownNodeTelemetry() Promise~void~
        }
        class DbSanitize {
            +sanitizeSql(sql) string
            +extractSqlOperation(sql) string
        }
    }

    namespace api-client {
        class APIClient {
            +get~T~(path, opts?) Promise~T~
            +post~T~(path, body?, opts?) Promise~T~
            +put~T~(path, body?, opts?) Promise~T~
            +patch~T~(path, body?, opts?) Promise~T~
            +delete~T~(path, opts?) Promise~T~
            +rawRequest(method, path, body?, opts?) Promise~RawHttpResponse~
        }
        class APIError {
            +number status
            +string body
        }
        class RawHttpResponse {
            +number status
            +Record&lt;string,string&gt; headers
            +string body
            +boolean truncated?
        }
    }

    namespace logger {
        class Logger {
            <<interface>>
            +trace(msg, data?) void
            +debug(msg, data?) void
            +info(msg, data?) void
            +warn(msg, data?) void
            +error(msg, data?) void
            +fatal(msg, data?) void
            +child(context) Logger
        }
        class LoggerFactory {
            +getLogger(category) Logger
            +initializeLogger(options?) Promise~void~
        }
    }

    SchedulerAdapter <|.. NodeSchedulerAdapter : implements
    SchedulerAdapter <|.. CloudflareSchedulerAdapter : implements
    SchedulerAdapter <|.. NoopSchedulerAdapter : implements
    SchedulerFactory --> SchedulerAdapter : "uses injected adapter"
    SchedulerFactory --> NoopSchedulerAdapter : "default when none injected"
    EventBus --> JobQueue : "async dispatch"
    EventBus --> QueueConsumer : "createJobHandler bridge"
    DBJobQueue --> JobQueue : "implements"
    DBQueueConsumer --> QueueConsumer : "implements"
    DBJobQueue --> EventBus : "optional QueueEvents"
    DBQueueConsumer --> EventBus : "optional QueueEvents"
    EventBus --> Logger : "self-observability"
    APIClient --> Tracing : "traceAsync"
    APIClient --> Metrics : "counters + histograms"
    APIClient --> EventBus : "optional ApiClientEvents"
```

## 如何运作

### 公共汽车-打字酒吧/分机

```ts
import { attachDefaultObservers, createLifecycleBus, EventBus, type EventMap } from '@gobing-ai/ts-infra';

// Define your event map
type AppEvents = {
    'user.signed_up': (email: string, plan: string) => void;
    'order.placed': (orderId: string, total: number) => void;
};

const bus = new EventBus<AppEvents>();

// Sync handler (runs in-process immediately)
bus.on('user.signed_up', (email, plan) => {
    console.log(`Welcome ${email} on ${plan} plan!`);
});

// Async handler (runs through the async handler path)
bus.on('order.placed', (orderId) => {
    console.log(`Order placed: ${orderId}`);
}, { async: true });

// Emit
await bus.emit('user.signed_up', 'alice@test.com', 'pro');
// → "Welcome alice@test.com on pro plan!"

// Once (auto-removes after first emit)
bus.once('user.signed_up', () => console.log('one-time'));
```

**已命名的合成处理器** 启用后排调度 。 使用 `name` 指定一个稳定的id,用于跨进程重新启动所消耗的工作,以及 `createJobHandler()` 在队列消费者上注册桥:

```ts
// Producer side: register async handlers with stable names
bus.on('order.placed', (orderId) => {
    console.log(`Order: ${orderId}`);
}, { async: true, name: 'order-handler' });

// Consumer side: register createJobHandler on your DBQueueConsumer
const jobHandler = bus.createJobHandler();
queueConsumer.register('order.placed', jobHandler);
queueConsumer.register('order.updated', jobHandler);
// → enqueued { event, args, handlerId } jobs dispatch to the matching named handler
```

**生命周期事件** 注射一秒钟 `EventBus` 观察公共汽车内部:

```ts
const lifecycleBus = createLifecycleBus();
attachDefaultObservers(lifecycleBus); // log + telemetry spans; metrics are emitted by EventBus itself
lifecycleBus.on('bus.emit.done', (detail) => {
    // { event, syncCount, asyncCount, emitDurationMs, errors }
    console.debug('EventBus emit complete', detail);
});

const bus = new EventBus<AppEvents>({ lifecycleBus });
```

### 任务队列 — DB 支持的同步工作

`DBJobQueue` 财务报告和审定财务报表 `DBQueueConsumer` 住在后边 `@gobing-ai/ts-infra/job-queue-db` 子路径并运行过 `@gobing-ai/ts-db`是因为 `QueueJobDao`。当事件处理器、调度器或 API 处理器需要用重试进行持久的背景工作时使用此功能.

```ts
import { createDbAdapter, QueueJobDao } from '@gobing-ai/ts-db';
import { DBJobQueue, DBQueueConsumer } from '@gobing-ai/ts-infra/job-queue-db';

const db = await createDbAdapter({ driver: 'bun-sqlite', url: './jobs.db' });
const dao = new QueueJobDao(db);

const queue = new DBJobQueue<{ to: string; subject: string }>(dao);
await queue.enqueue(
    'send-email',
    { to: 'alice@example.com', subject: 'Welcome' },
    // maxRetries is a total attempt budget, not retries after the first:
    // 5 means up to 5 attempts, and `maxRetries: 1` runs the job once with no retry.
    // timeoutMs is the per-job execution policy: positive ms, or `null` = unlimited.
    { maxRetries: 5, delay: 1_000, ttlMs: 86_400_000, timeoutMs: 60_000 },
);

const consumer = new DBQueueConsumer<{ to: string; subject: string }>(dao, {
    batchSize: 10,
    maxConcurrency: 4,
    visibilityTimeout: 30_000,
    // Execution policy: defaultTimeoutMs applies to jobs without their own
    // timeoutMs (job timeoutMs wins; explicit null = unlimited). Handlers that
    // overrun are failed with a deadline message; lease loss or cancel(jobId)
    // aborts the handler context and fences the ack.
    defaultTimeoutMs: 120_000,
    drainPolicy: 'bounded',
});

consumer.register('send-email', async (job, context) => {
    // context.signal aborts on deadline expiry, lease loss, or cancel(jobId).
    await sendEmail(job.payload.to, job.payload.subject, context.signal);
});

await consumer.start();
```

排水和测试时间: `processOnce()` 而不是开始投票循环:

```ts
const processed = await consumer.processOnce();
```

消费者声称已准备好的工作,在可见度超时后重新设置被卡住的处理工作,以指数回放重试失败的工作,标记过期的工作失败通过 `QueueJobDao`腐败的有效载荷在不拒绝批次的情况下单独失效。 下个周期记录并重审了弹道循环出错——一次DAO打嗝不会崩溃过程.

**执行期限(A21):** 每次尝试都在一个共享的截止时间钟下运行 `@gobing-ai/ts-infra` (单位:千美元)`resolveExecutionTimeoutMs`, (中文(简体) ), `runWithExecutionDeadline`) (中文(简体) ). 解析为一对胜:工作 `timeoutMs` (解释性) `null` = 无限) = 消费者 `defaultTimeoutMs` ——无限. 截止日期中止处理器 `context.signal` 工作失败; 租赁损失或 `consumer.cancel(jobId)` 报告 `cancelled` 并跳过所有角.

`stop()` 排出优雅的地道:它停止投票,然后等待已经在飞行中的工作——包括一个尚未声称什么的民意调查周期——才能解决。 等待被盖住 `drainTimeoutMs` (默认30s)所以被卡住的处理器无法阻挡关闭;当被击中后, `queue.consumer.stopped` 报告 `drained: false` 尚未解决的 `inFlightAtStop` 计数.

**腾讯身份.** 消费者一旦获得事件支持(a) `events` 总线已经配置, 它 **必须** 提供非空的、 已经调整过的 `queueName` - 建筑投掷 `Queue consumer queueName …` 否则,所以一个可观察到的消费者 永远不能释放匿名 `queue.consumer.started`编号 :`queue.consumer.stopped` 排队 名称被验证,从未正常化,并且以字节表示 `queueName` 两个生命周期的细节。 静默消费者(无) `events`)可能完全省略身份.

**队列生命周期事件** 选择通过注入 `EventBus`数字 :

```ts
import { EventBus } from '@gobing-ai/ts-infra';
import type { QueueEvents } from '@gobing-ai/ts-infra';
import { DBJobQueue, DBQueueConsumer } from '@gobing-ai/ts-infra/job-queue-db';

const events = new EventBus<QueueEvents>();
events.on('queue.job.enqueued', ({ jobId, type }) => { /* ... */ });
events.on('queue.job.completed', ({ jobId, type }) => { /* ... */ });
events.on('queue.job.failed', ({ jobId, type, error, attempt }) => { /* ... */ });
events.on('queue.job.retrying', ({ jobId, type, attempt, nextRetryAt }) => { /* ... */ });
events.on('queue.consumer.started', () => { /* ... */ });
events.on('queue.consumer.stopped', () => { /* ... */ });

const queue = new DBJobQueue<Payload>(dao, events);                // emits enqueued
const consumer = new DBQueueConsumer<Payload>(dao, {
    events,                             // emits lifecycle + job events
    queueName: 'email-jobs',            // required when `events` is configured (ADR-068)
});
```

### 排程器——类似克龙的动作

```ts
import { initScheduler } from '@gobing-ai/ts-infra';
import { NodeSchedulerAdapter } from '@gobing-ai/ts-infra/scheduler-node';

// Core factory — pass the adapter and entries in one call
const sched = initScheduler(new NodeSchedulerAdapter(), [
    ['300000', async () => cleanupExpiredSessions()],
    ['3600000', async () => generateReports()],
]);
await sched.start();

// Or register directly on the adapter
const sched2 = new NodeSchedulerAdapter();
sched2.register('*/5 * * * *', async () => {
    console.log('Runs every 5 minutes');
});
await sched2.start();

// Cloudflare Workers
import { CloudflareSchedulerAdapter } from '@gobing-ai/ts-infra/scheduler-cloudflare';
const cfScheduler = new CloudflareSchedulerAdapter();
cfScheduler.register('* * * * *', async () => { /* ... */ });

export default {
    async scheduled(event, env, ctx) {
        cfScheduler.handleScheduledEvent(event, ctx);
    },
};
```

**克伦支持(任务0734).** 保存了3个遗留的地块,作为从 适配器起始数:正数毫秒(`'60000'`, (中文(简体) ), `'* * * * *'` (60年代)和 `'*/N * * * *'` (N > 0) (中文(简体) ). 其它所有有效的五字段表达方式都是真实的 Cron, 以本地时间点评 并自行重新安排 `setTimeout` 因此,勾选永远不会重叠,错失的发生被跳过. 支持的字段:分钟 `0-59`小时 `0-23`每月日数 `1-31`月数 `1-12`每周的日数 `0-7` (单位:千美元)`0` 财务报告和审定财务报表 `7` 是星期日);每个接受 `*`,步骤形式、逗号分隔的数字列表或 包含非包装范围,或一个数字。 当两日字段都受到限制时,标准 cron OR 语义学应用. 错误的字段计数,超出范围值,下行范围,零步, 空列表成员、名称/宏和不支持的运算符 `RangeError` 登记时 没有什么会悄悄退后.

**申报工作.** `runNodeApplication` (见 `./application-node`验证 `bootstrap.scheduler.jobs`,以 `SchedulerJobConfig` 物品——每个不是空的 `name` 财务报告和审定财务报表 `command` 加上一个整数 `intervalMinutes` (单位:千美元)`1..35791`或使用 以上语法. 无论是否启用调度器, 任务都会被验证和正常化; 已禁用 调度器保留了已验证的定义,但没有创建适配器并运行一无所有. {\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}再给你点颜色看看 `command` 作为声明性数据,而从未执行它——消耗性应用程序将它与它本身联系在一起 处理者.

### API 客户端 - 有追踪功能的 HTTP

```ts
import { APIClient, APIError } from '@gobing-ai/ts-infra';

const api = new APIClient({
    baseUrl: 'https://api.example.com',
    defaultHeaders: { Authorization: `Bearer ${token}` },
    timeout: 10_000,
});

// Typed response — spans are auto-created
const user = await api.get<{ id: string; name: string }>('/users/me');

try {
    await api.post('/orders', { productId: 'p1', quantity: 2 });
} catch (error) {
    if (error instanceof APIError) {
        console.error(`HTTP ${error.status}: ${error.body}`);
    }
}

// PATCH method
await api.patch('/users/1', { name: 'updated' });

// Raw request — returns status/headers/body for ALL status codes (no throw on 4xx/5xx)
const { status, headers, body, truncated } = await api.rawRequest('GET', '/debug', undefined, {
    redirect: 'follow',
    maxResponseBytes: 10_000,  // cap response body; truncated === true when exceeded
});

// Per-request abort signal (not confused with timeouts)
const controller = new AbortController();
setTimeout(() => controller.abort(), 2_000);
await api.get('/slow', { signal: controller.signal }); // throws DOMException AbortError

// Custom operation name for tracing
const items = await api.get<Item[]>('/items', { operationName: 'inventory.list' });
```

客户端自动处理每个请求:创建 `CLIENT` 间距、记录方法/URL/状态属性、发出请求计数+持续时间度量,以及记录出错。 超时抛出 `APIError(0, "Request timed out after …ms")` - 从不生 `DOMException`。调用者启动的中止 `AbortError`。 。 。 .

**API 客户端事件** 通过构造器选择进入:

```ts
import { EventBus } from '@gobing-ai/ts-infra';
import type { ApiClientEvents } from '@gobing-ai/ts-infra';

const events = new EventBus<ApiClientEvents>();
events.on('api.request.error', ({ url, method, status, error }) => {
    console.error(`HTTP error — ${method} ${url}: ${error}`);
});

const api = new APIClient({ baseUrl: '...', events });
```

### Logger——结构化的JSON

```ts
import { getLogger, initializeLogger } from '@gobing-ai/ts-infra';

await initializeLogger({
    level: 'debug',
    console: true,
    json: true,
});

const log = getLogger('auth');
log.info('User logged in', { userId: 'u1', method: 'password' });
// → {"level":"info","message":"User logged in",...,"category":"auth","userId":"u1"}

// Child loggers carry context
const reqLog = log.child({ requestId: 'req-123' });
reqLog.error('Validation failed', { field: 'email' });
// → {...,"category":"auth","requestId":"req-123","field":"email"}

// File logging is also injectable; ts-infra never opens files directly.
await initializeLogger({
    console: false,
    fileSink: (line) => {
        // Append `line` using the host runtime's FileSystem / stream owner.
    },
});

// In tests, prefer injecting a logger boundary or initializing with console: false.
```

### 遥测——开口遥测

```ts
import {
    initTelemetry, shutdownTelemetry,
    traceAsync, addSpanAttributes, getActiveSpan,
    sanitizeSql,
} from '@gobing-ai/ts-infra';

// Initialize at startup — the master switch is real:
// enabled: false short-circuits ALL infra tracing + metrics to shared noop instruments
initTelemetry({
    enabled: true,
    serviceName: 'my-api',
    environment: 'production',
});

// Trace an operation
const result = await traceAsync('db.query', async (span) => {
    addSpanAttributes({ 'db.system': 'sqlite', 'db.operation': 'SELECT' });
    return db.select().from(users);
});

// Sanitize SQL before export
const safe = sanitizeSql("SELECT * FROM users WHERE email = 'alice@test.com'");
// → "SELECT * FROM users WHERE email = ?"

// Shutdown gracefully
process.on('SIGTERM', async () => {
    await shutdownTelemetry();
});
```

量子是懒惰的初始化的——除此之外不需要配置 `initTelemetry()`数字 :

```ts
import { getQueueJobEnqueuedTotal, getQueueJobProcessingDuration } from '@gobing-ai/ts-infra';

getQueueJobEnqueuedTotal().add(1, { 'queue.job_type': 'send-email' });
getQueueJobProcessingDuration().record(42, { 'queue.job_type': 'send-email' });
```

#### 仪器与出口

只有主枪管 **文书** - 记录跨度和度量度与 在全球注册的 OpenTeleometry 服务商, 当无设备时则降解为无设备 注册。 没错 **没有** 因此它从不强迫出口者使用OTel SDK或 收集者对消费者的看法。 两种实际出口方式:

1.  **再见** - 在下列地点注册自己的OTel SDK(Tracer + meter 供应商、出口商) 进程启动。 ts-infra的跨度/度量自动流入.
2.  **总钥匙OTLP** - 选择加入 `@gobing-ai/ts-infra/otel-node` 子路径, 其中 用于信号和登记供应商的节点OTLP/HTTP导出 在全球.

```ts
// Node-only convenience: pulls the optional OTLP exporter peers.
import { initNodeTelemetry, shutdownNodeTelemetry } from '@gobing-ai/ts-infra/otel-node';

initNodeTelemetry({
    serviceName: 'my-api',
    serviceVersion: '1.4.0',
    endpoint: 'http://otel-collector:4318', // signal paths (/v1/traces, /v1/metrics) appended
    headers: { authorization: `Bearer ${process.env.OTEL_TOKEN}` },
});

process.on('SIGTERM', async () => {
    await shutdownNodeTelemetry(); // flush + drain buffered spans/metrics
});
```

出口包是: **选项同伴** - 只有消费者 `/otel-node` 需要安装它们. `@opentelemetry/api` 语义公约是唯一 核心仪器表面使用的OTel包. 主要内容 `@gobing-ai/ts-infra` 进口从不牵引出口商/供应商 SDK,因此BYO和 浏览器/终端消费者保持倾斜。 使用子路径 :

```bash
bun add @opentelemetry/sdk-trace-node @opentelemetry/sdk-metrics \
        @opentelemetry/resources \
        @opentelemetry/exporter-trace-otlp-http \
        @opentelemetry/exporter-metrics-otlp-http
```

### 应用程序启动

应用靴子 API 为接线提供了决定性的生命周期 基础设施服务。 两层:

1.  **便携式 DI 拖带** (单位:千美元)`@gobing-ai/ts-infra/application`——管弦乐团 注入依存. 从不打开文件、创建 DB 连接或线条 具体运行时间的出口商.
2.  **节点/节点便利** (单位:千美元)`@gobing-ai/ts-infra/application-node`()——作曲 带有运行时间特定适配器的便携式靴子: YAML 配置装入, 文件日志槽, Bun SQLite DB 创建, 节点 OTel 导出, 节点调度器.

#### 便携式 DI 拖带

```ts
import { runApplication } from '@gobing-ai/ts-infra/application';

const app = await runApplication({
    config: {
        logging: { level: 'info', console: true },
        telemetry: { enabled: true, serviceName: 'my-api' },
    },
    appConfig: { port: 3000 },
    async start(app) {
        app.logger.info('started', { port: app.appConfig.port });
    },
});

// Graceful shutdown — idempotent
await app.stop();
```

便携 `runApplication` 接受通过 `services` 财务报告和审定财务报表 从不读取文件 。 生命周期是 **插件驱动**: 基层服务(开发者, 遥测、调度和用户 `start`编号 :`stop` 回调被注册为 a 上的内建插件 `PluginHost`,按抚养顺序排列:

```
logger → telemetry → [your plugins] → user-callback → scheduler
```

`loadAll()` 接下来 `startAll()` (a) 将它们推向前进(A-Z)。 标记插件 `failFast` (内置服务)如果靴子 `onStart` 抛出; 其他 插件为故障软. 关闭是反向扇出—— `stop(reason)` 电话 每个插件 `onStop(host, reason)` 按倒数登记顺序排列(排期) 停下来,你的 `stop(app, reason)`遥测关闭. `stop()` 具有本能—— 安全地从多个信号处理器呼叫.

**DB所有权.** 便携式层 **从不关闭被注射的呼叫者 `services.db`** 你拥有它的生命周期,必须自己关闭它。 只有一个 将靴子绑住 _创建_ (例如节点子路径的 Bun SQLite 适配器)是 自动关闭,通过内置的 DB 插件。 (变化于0.x-以前 便携式地层封闭式接驳器无条件注射. )

#### 节点/节点便利靴

```ts
import { runNodeApplication } from '@gobing-ai/ts-infra/application-node';

await runNodeApplication({
    configLoader: {
        configFile: 'config/app.yaml',
        bootstrapSection: 'bootstrap',
        appSection: 'billing',
        appConfig: {
            // Structural safeParse adapter — works with Zod or any validator
            safeParse(raw) {
                return billingSchema.safeParse(raw);
            },
        },
    },
    async start(app) {
        app.logger.info('billing app started', {
            settlementWindowMinutes: app.appConfig.settlementWindowMinutes,
        });
    },
});
```

示例 YAML 配置文件 :

```yaml
app:
  name: billing-api
  env: production

bootstrap:
  logging:
    level: info
    console: true
    filePath: ./logs/app.jsonl   # a directory (e.g. ./logs/) writes daily spur{YYYYMMDD}.log files
  telemetry:
    enabled: true
    serviceName: billing-api
    endpoint: http://otel-collector:4318
    headers:
      authorization: Bearer ${OTEL_TOKEN}
  database:
    enabled: true
    driver: bun-sqlite
    url: ./data/app.db

billing:
  settlementWindowMinutes: 15
  riskLimit: 100000
```

配置验证器接受四个形状:

-   `{ safeParse(raw) → { success, data?, errors? } }` - 与Zod兼容
-   `(raw) => TAppConfig` - 全能
-   `{ validate(raw) => TAppConfig }` 方法表
-   `{ parse(raw) => TAppConfig }` 方法表

校验错误包括配置文件路径和诊断的区名.

**故意不在主桶内的东西:** `runApplication` 财务报告和审定财务报表 `runNodeApplication` 住在明显的子道后 所以主要的 `@gobing-ai/ts-infra` 导入时保持便携式和适配器灯光。 未来的发展成果评估 可决定仅型再出口是否可以接受.

#### CLI 便利拖带

火灾和遗忘的CLI(指挥官、亚尔格等), `@gobing-ai/ts-infra/application-cli` 包装 `runNodeApplication` 最终每个CLI都会做一件事: 命令结果为进程退出代码,并终止。 相同的选项形状, 相同的 默认,相同的回调合同——无出乎意料.

```ts
import { runCliApplication } from '@gobing-ai/ts-infra/application-cli';
import { Command } from 'commander';

await runCliApplication({
    async start(app) {
        const program = new Command().name('mycli');
        // ...register commands...
        program.parse();               // Commander sets exit code on error
        return process.exitCode;       // forward to runCliApplication
    },
});
```

与 `runNodeApplication`数字 :

-   `start` 返回时 `number | void` ——数字变为出站代码(void=0)
-   关于成功,电话 `app.stop('shutdown')` 接下来 `process.exit(code)`
-   错误时, 将信件写入 stderr 并退出 1( 在优雅地撕裂后)

用于 CLIs 。 对于长期服务(服务器、守护进程、工人),使用 `runNodeApplication` 直接 —— 它返回一个运行时控件您控制 .

## 使用量

### 安装

```bash
bun add @gobing-ai/ts-infra

# Only needed when using @gobing-ai/ts-infra/job-queue-db.
bun add @gobing-ai/ts-db

# Only needed when using @gobing-ai/ts-infra/otel-node.
bun add @opentelemetry/sdk-trace-node @opentelemetry/sdk-metrics \
        @opentelemetry/resources \
        @opentelemetry/exporter-trace-otlp-http \
        @opentelemetry/exporter-metrics-otlp-http
```

### 完整拖网示例(建议: `runApplication` 或者说 `runNodeApplication`(中文(简体) )

将插件驱动的靴子绑在手动接线上——主机生命周期手柄上 启动命令、倒置命令拆卸、故障快放/故障软政策以及同位素 停下来 两个切入点:

```ts
// Portable — inject everything yourself:
import { runApplication } from '@gobing-ai/ts-infra/application';

const app = await runApplication({
    config: {
        logging: { level: 'info', console: true },
        telemetry: { enabled: true, serviceName: 'my-app' },
    },
    services: { db }, // caller-owned — you close it
    async start(app) {
        app.logger.info('started');
    },
    async stop(app, reason) {
        app.logger.info('shutting down', { reason });
    },
});

await app.stop('signal');
```

```ts
// Node / Bun — YAML config, file logs, OTel export, Bun SQLite, Node scheduler:
import { runNodeApplication } from '@gobing-ai/ts-infra/application-node';

const app = await runNodeApplication({
    configLoader: {
        configFile: 'config/app.yaml',
        bootstrapSection: 'bootstrap',
        appSection: 'billing',
        appConfig: { safeParse: (raw) => mySchema.safeParse(raw) },
    },
    async start(app) {
        app.logger.info('started', { port: app.appConfig.port });
    },
});
```

### 系统事件——生命周期公共汽车推广合同

`runApplication` 创建单个 `lifecycleBus` (单位:千美元)`EventBus<BusLifecycleEvents>`(中文(简体) ) 和家长的应用活动总线。 下游的消费者也加入 调用者通过时的流 `app.lifecycleBus` 进入他们的建筑者。 域外传 扇出为 `bus.*` 父母的生命周期事件以及——当文件观察员是 附加的——与域事件本身并列的JSONL系统事件日志中的土地.

**六种系统事件前缀及其起源地:**

| 前缀 | 来源 | 构造时间 `events` 删除 |
| --- | --- | --- |
| `bus.*` | `EventBus` 寿命周期自可观察性 `lifecycleBus` 页:1 | 总是.. `runApplication` 创造它 |
| `api.*` | `APIClient` (单位:千美元)`api.request.error`(中文(简体) ) | `new EventBus<ApiClientEvents>({ lifecycleBus })` (兰5) |
| `rule.*` | `RuleEngine` (规则管理结构的可观察性) | `new EventBus<RuleEngineEvents>({ lifecycleBus })` (R2级) |
| `workflow.*` | `WorkflowService` (工作流程的可观察性) | `new EventBus<WorkflowEngineEvents>({ lifecycleBus })` 通过 `resolveEvents` (R3级) |
| `agent.*` | `AiRunner` 编号 : `TeamOrchestrator` (代理人援引可观察性) | `new EventBus<AgentEvents>({ lifecycleBus })` (中文(简体) ) |
| `process.*` | `AiRunner` 默认执行程序事件 | `new EventBus<AiRunnerProcessEvents>({ lifecycleBus })` (中文(简体) ) |

**调用 `events` 总是赢.** 每个消费者都接受一个明确的 `events?: EventBus<TEvents>` (或等同)和可选 `lifecycleBus?`。 。 。 . 何时 `events` (b) 消费者何时使用 `events` 删除 财务报告和审定财务报表 `lifecycleBus` 消费者建造内部公共汽车 父为生命周期总线 。 保持独立使用零配置并允许 靴子将每个消费者 选入系统事件流 通过一个 单人 `lifecycleBus`。 。 。 .

**Portable vs 节点子路径分拆(ADR-011).** `runApplication` (便携式) 从不打开文件: 它调用 `attachFileObserver(lifecycleBus, filePath, writer)` 仅在 `services.fileObserverWriter` 提供;其便携式默认路径是 `.spur/logs/system-events.jsonl`。节点子路径 `runNodeApplication` 构造 a 节点写入和使用 `createNodeFileSystem()` 解决路径 `<projectRoot>/.spur/logs/system-events{YYYYMM}.jsonl` (每月一份档案). 节点 作者扩展 `{YYYYMM}` 编号 : `{YYYYMMDD}` (当地日期) `filePath` 每次写,所以 长期运行的进程在不重启的情况下滚动。 设定 `config.events.fileObserver: false` 禁用; 提供自定义 `filePath` (或通过测试站写作) `services.fileObserverWriter`),以推翻.

**手动给消费者打电话.** 当你建造一个消费者外 靴子陷阱(或希望共享靴子陷阱的公交车),通过暴露的 `app.lifecycleBus`数字 :

```ts
import { RuleEngine } from '@gobing-ai/ts-rule-engine';

const engine = new RuleEngine({ lifecycleBus: app.lifecycleBus });
// engine now emits `rule.*` events into the same JSONL log as the bootstrap.
```

如果您更喜欢手动接线( 例如, 您已经拥有了 init 序列) , 个人 子系统仍然独立运作—— `EventBus`, (中文(简体) ), `APIClient`, (中文(简体) ), `getLogger`,等等为: 全部可以直接从主桶进口,不需要靴子.

#### 自定义插件

以登记顺序向前运行的插件( E)`loadAll → startAll`)和倒转顺序 拆卸(`stopAll → unloadAll`:

```ts
import { runApplication } from '@gobing-ai/ts-infra/application';
import type { Plugin } from '@gobing-ai/ts-infra';

const auditPlugin: Plugin = {
    name: 'audit-logger',
    version: '1.0.0',
    failFast: false, // fail-soft: a throwing onStart is logged, boot continues
    onLoad: async (host) => { /* validate preconditions — throws abort boot */ },
    onStart: async (host) => { host.events.on('order.placed', auditHandler); },
    onStop: async (host, reason) => { host.logger.info('persisting audit buffer', { reason }); },
    onUnload: async () => { /* release resources */ },
};

const app = await runApplication({
    plugins: [auditPlugin],
    config: { logging: { console: true } },
});
```

主机转发可选拆分 `reason` (平面图) `string` 在核心合同, `ApplicationStopReason` —— 说 `'manual' | 'signal' | 'error' | 'shutdown'` ——在应用层面) 到每个插件 `onStop`编号 :`onUnload`。内建服务插件在日志上下文时使用此选项; 用户召回插件将它发送给您 `stop(app, reason)`。 。 。 .

````

### Graceful shutdown

With `runApplication` or `runNodeApplication`, shutdown is a single idempotent call:

```ts
process.on('SIGTERM', () => app.stop('signal'));
process.on('SIGINT', () => app.stop('signal'));
````

主机运行 `stopAll(reason) → unloadAll(reason)` 以反向登记顺序排列: 调度器停止,您的 `stop` 回叫起火、遥测冲和可选 DB 适配器关闭( 如果靴子设置了它—— 调用器注入适配器是 你的责任。 同上:避免信号处理器重叠.

## 常见问题

### @gobing-ai/ts-infra 是什么？

@gobing-ai/ts-infra — 基础设施主干线:事件总线,工作队列,排程器,遥测,API客户端,以及日志\.

### 如何安装 @gobing-ai/ts-infra？

在项目目录运行 npm install @gobing-ai/ts-infra，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@opentelemetry/api（^1\.9\.0）、@opentelemetry/semantic-conventions（^1\.30\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @gobing-ai/ts-infra 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gobing-ai/ts-infra 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @gobing-ai/ts-infra 可以商用吗？

@gobing-ai/ts-infra 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @gobing-ai/ts-infra 的下载量有多少？

根据 npm 官方下载统计，@gobing-ai/ts-infra 在 2026/10/17 – 2026/11/15 这 30 天内被下载 4,135 次，日均约 138 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gobing-ai/ts-infra 还在维护吗？

最新版本 0\.7\.1 发布于 2026/10/25（22 天前）；至今共发布 136 个版本，其中过去 12 个月发布了 136 个；首次发布于 2026/05/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

