Host 与 Worker 缓存
查询 @mapseekai/tasklane/host 的 serve、output、HostContext、ScopedCache 与 ScratchArena 接口。
在 Worker 线程内,使用 @mapseekai/tasklane/host 导出的 serve<Tasks>(port, handlers) 注册任务处理函数(返回用于取消监听的清理函数 () => void)。处理函数通过 output(value, transfer?) 显式声明返回结果与需要转移所有权的 ArrayBuffer 列表。
HostContext 属性与方法
每个任务处理函数 handler(input, ctx) 的第二个参数为 HostContext:
| 属性或方法 | 类型 | 用途与契约约束 |
|---|---|---|
signal | AbortSignal | 当前任务的取消信号;收到协作取消指令时变为 aborted |
outputLimit | number | 本次任务允许返回的协议输出包最大字节数(即调用方声明的 budget.outputBytes) |
scopeId | string | 提交该任务的 Scope 唯一标识 |
sessionId | string | undefined | 若通过 Session 提交,则为该会话的唯一标识;普通池任务为 undefined |
epoch | number | 当前物理 Worker 实例的代际号 |
cache | ScopedCache | 自动隔离到当前 sessionId(优先)或 scopeId 命名空间的本地缓存接口 |
scratch | ScratchArena | 受本任务 budget.scratchBytes 上限约束的临时 ArrayBuffer 分配器 |
progress(value) | void | 发送有界进度控制消息(最多 64 个对象、256 条边、4 KiB 计费量;Host 自动按 16ms 与 ACK 节流) |
checkpoint() | Promise<void> | 让出一次真实宏观事件循环以接收取消消息,若已取消则立即抛出中止错误(任务结束后调用会拒绝) |
export interface TaskOutput<T> {
value: T;
transfer?: readonly Transferable[];
}
export function output<T>(value: T, transfer: readonly Transferable[] = []): TaskOutput<T> {
return { value, transfer };
}
export interface HostContext {
readonly signal: AbortSignal;
/** Reserved packet bytes for this task's output, available before allocating a chunk. */
readonly outputLimit: number;
readonly scopeId: string;
readonly sessionId?: string;
readonly epoch: number;
readonly cache: ScopedCache;
/** Task-owned, measured backing stores. Allocations outside this arena are not tracked. */
readonly scratch: ScratchArena;
/** Throttled to at most one message per 16ms per physical task. */
progress(value: unknown): void;
/** A real task-queue yield. Promise.resolve() is NOT sufficient for cancellation messages. */
checkpoint(): Promise<void>;
}
export type TaskHandler<I, O> = (
payload: I,
context: HostContext,
) => TaskOutput<O> | Promise<TaskOutput<O>>;
export type TaskHandlers<T extends Catalog<T>> = {
[K in keyof T]: TaskHandler<T[K]['input'], T[K]['output']>;
};
ScopedCache 与 ScratchArena 方法说明
ScopedCache(Worker 本地缓存)
get<T>(key: string): T | undefined:读取当前命名空间下的缓存值,命中时更新 LRU 顺序并递增hits,未命中递增misses。set<T>(key: string, value: T, bytes?: number): T:保存可被 LRU 淘汰的普通结构化数据。若显式传入bytes,该值不得低于dataByteLength(value)的实际核算值。setBinary<T extends ArrayBufferView>(key: string, view: T): T:零拷贝保存原生TypedArray或DataView快照。不枚举数组下标、不复制底层内存,按完整底层ArrayBuffer计费,支持 LRU 淘汰(缓存持有期间切勿将底层缓冲区transfer转移走)。setPinned<T>(key: string, value: T, bytes?: number): T:仅在Session任务中可用;保存不会被 LRU 自动淘汰的固定普通数据。setResource<T>(key: string, value: T, bytes: number, disposer: (value: T) => void | Promise<void>, options?: CacheResourceOptions): CacheResourceLease<T>:仅在Session任务中可用;注册数据库句柄、WASM 实例等不透明资源,信任声明的bytes上界。可选传入options.trim(targetBytes)响应内存压力裁剪。返回CacheResourceLease,可通过lease.report(snapshot)上报内部缓存命中计数与块keys足迹。delete(key: string): boolean | Promise<boolean>:删除指定键。若条目为注册了异步disposer的不透明资源,则返回 Promise,调用方在替换同名资源前必须await ctx.cache.delete(key)。clear(): void | Promise<void>:清空当前命名空间下的所有条目并等待所有disposer完成。
ScratchArena(任务内受控暂存)
ctx.scratch.allocate(bytes: number): ArrayBuffer:在当前任务的scratchBytes额度内分配一块新的ArrayBuffer;累计未释放字节超过上限时抛出BUDGET_EXCEEDED。ctx.scratch.release(buffer: ArrayBuffer | ArrayBufferView): void:立即detach回收该临时缓冲区并归还当前任务的暂存可用额度。任务结束时,Arena 中所有尚未手动释放的缓冲区均会被自动detach关闭。
export interface CacheResourceOptions {
/** Dispose reader-owned cache data, then return the remaining reservation. */
trim?(targetBytes: number): number | Promise<number>;
}
export interface CacheResourceLease {
/** Complete current footprint plus absolute reader-owned cache counters. */
report(snapshot: ResourceCacheReport): void;
readonly bytes: number;
readonly released: boolean;
/** Grow before allocation, shrink after disposal. Failure preserves the previous accounting. */
resize(bytes: number): void;
/** Credits remain held until the disposer succeeds; failures can be retried. */
release(): Promise<void>;
}
export interface ScopedCache {
get<T = unknown>(key: string): T | undefined;
/** Declared bytes are checked against backing stores plus scalar/key metadata. */
set(key: string, value: unknown, bytes: number): void;
/** Fresh native view, shared backing storage, no custom view properties. Charges the full buffer. */
setBinary(key: string, value: ArrayBufferView): void;
setPinned(key: string, value: unknown, bytes: number): void;
/** Opaque session-owned state. Accounting is caller-declared; disposal is explicit and may be async. */
setResource<T>(
key: string,
value: T,
bytes: number,
dispose: (value: T) => void | Promise<void>,
options?: CacheResourceOptions,
): CacheResourceLease;
delete(key: string): void | Promise<void>;
}