@easy-sync/batching
Version:
Batching library for easy-sync.
92 lines (84 loc) • 3.25 kB
TypeScript
export declare class BatchCancellationError extends Error {
constructor(message?: string);
}
export declare class BatchManager<CombinedResponse, Result, Id extends RequestId = undefined, Payload = undefined> {
private processor;
private resolver;
private scheduler;
private pending;
private firstRequestTime;
private lastRequestTime;
private timer;
constructor(options: {
processor: BatchProcessor<CombinedResponse, Id, Payload>;
resolver: RequestResolver<CombinedResponse, Result, Id, Payload>;
scheduler?: Scheduler;
});
/**
* Enqueue a new request into the batch. Returns a promise handle that can be awaited for the result,
* with a cancel() method and id property for cancellation or reference.
*/
enqueue: (request: Id | {
payload: Payload;
id?: Id;
}, signal?: AbortSignal) => BatchRequestHandle<Id, Result>;
/**
* Cancel a pending request or the entire batch.
* @param id If provided, cancels the request(s) with this id. If omitted, cancels all pending requests.
*
* Cancelling a request rejects its promise with a BatchCancellationError.
* (Requests already being processed in a batch cannot be cancelled via this method.)
*/
cancel: (id?: Id) => void;
/**
* --Internal Helper--
* Create a promise handle for a new request
* - Create a promise
* - Extend the promise with id and cancel properties
* - Return the promise handle
*
* @param reqId The id of the request
* @param signal The signal
* @returns The promise handle
*/
private createPromiseHandle;
/**
* --Internal Helper--
* Manage timers and scheduler for the batch (for when a new request is enqueued)
*
* @param options { firstRequestTime: number }
*/
private manageTimersAndScheduler;
/**
* --Internal Helper--
* Clear any existing timer
*/
private clearExistingTimer;
/**
* --Internal Helper--
* Reset the current batch
*/
private resetCurrentBatch;
/**
* --Internal Helper--
* Trigger the batch execution
*/
private triggerBatch;
}
export declare type BatchProcessor<CombinedResponse, Id = undefined, Payload = undefined> = (requests: Array<{
id: Id;
payload: Payload;
}>) => Promise<CombinedResponse>;
export declare interface BatchRequestHandle<Id, Result> extends Promise<Result> {
/** The id of this request (possibly auto-generated if not provided) */
id: Id;
/** Cancel this individual request (if the batch has not yet been executed) */
cancel: (reason?: unknown) => void;
}
export declare type RequestId = string | number | symbol | undefined;
declare type RequestResolver<CombinedResponse, Result, Id = undefined, Payload = undefined> = (combinedResponse: CombinedResponse, request: {
id: Id;
payload: Payload;
}) => Result;
declare type Scheduler = (firstRequestTime: number, lastRequestTime: number, batchSize: number) => number;
export { }