Skip to content

There can be more than Notion and Miro. AFFiNE(pronounced [ə‘fain]) is a next-gen knowledge base that brings planning, sorting and creating all together. Privacy first, open-source, customizable and ready to use.

feat(infra): op call with signal (#11567)

EYHN62b942283429
diff --git a/packages/common/infra/src/op/client.ts b/packages/common/infra/src/op/client.ts
index 806b681e1a..8034225a2f 100644
--- a/packages/common/infra/src/op/client.ts
+++ b/packages/common/infra/src/op/client.ts
@@ -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');
};
diff --git a/packages/common/infra/src/op/types.ts b/packages/common/infra/src/op/types.ts
index 7de14e03e2..cae15e68bd 100644
--- a/packages/common/infra/src/op/types.ts
+++ b/packages/common/infra/src/op/types.ts
@@ -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>,