mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-07-29 00:06:09 +08:00
feat(infra): op call with signal (#11567)
This commit is contained in:
@@ -11,7 +11,13 @@ import {
|
||||
type SubscribeMessage,
|
||||
type UnsubscribeMessage,
|
||||
} from './message';
|
||||
import type { OpInput, OpNames, OpOutput, OpSchema } from './types';
|
||||
import type {
|
||||
OpInput,
|
||||
OpInputWithSignal,
|
||||
OpNames,
|
||||
OpOutput,
|
||||
OpSchema,
|
||||
} from './types';
|
||||
|
||||
export interface CancelablePromise<T> extends Promise<T> {
|
||||
cancel(): void;
|
||||
@@ -107,10 +113,14 @@ export class OpClient<Ops extends OpSchema> extends AutoMessageHandler {
|
||||
|
||||
call<Op extends OpNames<Ops>>(
|
||||
op: Op,
|
||||
...args: OpInput<Ops, Op>
|
||||
...args: OpInputWithSignal<Ops, Op>
|
||||
): CancelablePromise<OpOutput<Ops, Op>> {
|
||||
const promiseWithResolvers = Promise.withResolvers<any>();
|
||||
const payload = args[0];
|
||||
const abortSignal =
|
||||
args[args.length - 1] instanceof AbortSignal
|
||||
? (args.pop() as AbortSignal)
|
||||
: undefined;
|
||||
const payload = args.pop();
|
||||
|
||||
const msg = {
|
||||
type: 'call',
|
||||
@@ -121,7 +131,7 @@ export class OpClient<Ops extends OpSchema> extends AutoMessageHandler {
|
||||
|
||||
const promise = promiseWithResolvers.promise as CancelablePromise<any>;
|
||||
|
||||
const raise = (reason: string) => {
|
||||
const raise = (reason: any) => {
|
||||
const pending = this.pendingCalls.get(msg.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
@@ -130,11 +140,15 @@ export class OpClient<Ops extends OpSchema> extends AutoMessageHandler {
|
||||
type: 'cancel',
|
||||
id: msg.id,
|
||||
} satisfies CancelMessage);
|
||||
promiseWithResolvers.reject(new Error(reason));
|
||||
promiseWithResolvers.reject(reason);
|
||||
clearTimeout(pending.timeout);
|
||||
this.pendingCalls.delete(msg.id);
|
||||
};
|
||||
|
||||
abortSignal?.addEventListener('abort', () => {
|
||||
raise(abortSignal.reason);
|
||||
});
|
||||
|
||||
promise.cancel = () => {
|
||||
raise('canceled');
|
||||
};
|
||||
|
||||
@@ -26,6 +26,11 @@ export type OpInput<
|
||||
: never
|
||||
: never;
|
||||
|
||||
export type OpInputWithSignal<Ops extends OpSchema, Type extends OpNames<Ops>> =
|
||||
OpInput<Ops, Type> extends [infer In]
|
||||
? [In, AbortSignal | undefined] | [In]
|
||||
: [AbortSignal | undefined] | [];
|
||||
|
||||
export type OpOutput<
|
||||
Ops extends OpSchema,
|
||||
Type extends OpNames<Ops>,
|
||||
|
||||
Reference in New Issue
Block a user