aboutsummaryrefslogtreecommitdiffstats
path: root/packages/plugins/queue-restate/src/service.ts
blob: f27fd200fb63f773d4188e774c01663d22a9609a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import * as restate from "@restatedev/restate-sdk";

import type {
  Queue,
  QueueOptions,
  RunnerFuncs,
  RunnerOptions,
} from "@karakeep/shared/queueing";
import { QueueRetryAfterError } from "@karakeep/shared/queueing";
import { tryCatch } from "@karakeep/shared/tryCatch";

import { RestateSemaphore } from "./semaphore";

export function buildRestateService<T, R>(
  queue: Queue<T>,
  funcs: RunnerFuncs<T, R>,
  opts: RunnerOptions<T>,
  queueOpts: QueueOptions,
) {
  const NUM_RETRIES = queueOpts.defaultJobArgs.numRetries;
  return restate.service({
    name: queue.name(),
    options: {
      inactivityTimeout: {
        seconds: opts.timeoutSecs,
      },
      retryPolicy: {
        maxAttempts: NUM_RETRIES,
        initialInterval: {
          seconds: 5,
        },
        maxInterval: {
          minutes: 1,
        },
      },
      journalRetention: {
        days: 3,
      },
    },
    handlers: {
      run: async (
        ctx: restate.Context,
        data: {
          payload: T;
          queuedIdempotencyKey?: string;
          priority: number;
          groupId?: string;
        },
      ) => {
        const id = ctx.rand.uuidv4();
        let payload = data.payload;
        if (opts.validator) {
          const res = opts.validator.safeParse(data.payload);
          if (!res.success) {
            throw new restate.TerminalError(res.error.message, {
              errorCode: 400,
            });
          }
          payload = res.data;
        }

        const priority = data.priority ?? 0;

        const semaphore = new RestateSemaphore(
          ctx,
          `queue:${queue.name()}`,
          opts.concurrency,
        );

        let lastError: Error | undefined;
        let runNumber = 0;
        while (runNumber <= NUM_RETRIES) {
          const acquired = await semaphore.acquire(
            priority,
            data.groupId,
            data.queuedIdempotencyKey,
          );
          if (!acquired) {
            return;
          }
          const res = await runWorkerLogic(ctx, funcs, {
            id,
            data: payload,
            priority,
            runNumber,
            numRetriesLeft: NUM_RETRIES - runNumber,
            abortSignal: AbortSignal.timeout(opts.timeoutSecs * 1000),
          });
          await semaphore.release();

          if (res.type === "rate_limit") {
            // Handle rate limit retries without counting against retry attempts
            await ctx.sleep(res.delayMs, "rate limit retry");
            // Don't increment runNumber - retry without counting against attempts
            continue;
          }

          if (res.type === "error") {
            if (res.error instanceof restate.CancelledError) {
              throw res.error;
            }
            lastError = res.error;
            // TODO: add backoff
            await ctx.sleep(1000, "error retry");
            runNumber++;
          } else {
            // Success
            break;
          }
        }
        if (lastError) {
          throw new restate.TerminalError(lastError.message, {
            errorCode: 500,
            cause: "cause" in lastError ? lastError.cause : undefined,
          });
        }
      },
    },
  });
}

type RunResult<R> =
  | { type: "success"; value: R }
  | { type: "rate_limit"; delayMs: number }
  | { type: "error"; error: Error };

async function runWorkerLogic<T, R>(
  ctx: restate.Context,
  { run, onError, onComplete }: RunnerFuncs<T, R>,
  data: {
    id: string;
    data: T;
    priority: number;
    runNumber: number;
    numRetriesLeft: number;
    abortSignal: AbortSignal;
  },
): Promise<RunResult<R>> {
  const res = await tryCatch(
    ctx.run(
      `main logic`,
      async () => {
        const res = await tryCatch(run(data));
        if (res.error) {
          if (res.error instanceof QueueRetryAfterError) {
            return { type: "rate_limit" as const, delayMs: res.error.delayMs };
          }
          throw res.error; // Rethrow
        }
        return { type: "success" as const, value: res.data };
      },
      {
        maxRetryAttempts: 1,
      },
    ),
  );

  if (res.error) {
    await tryCatch(
      ctx.run(
        `onError`,
        async () =>
          onError?.({
            ...data,
            error: res.error,
          }),
        {
          maxRetryAttempts: 1,
        },
      ),
    );
    return { type: "error", error: res.error };
  }

  const result = res.data;

  if (result.type === "rate_limit") {
    // Don't call onError or onComplete for rate limit retries
    return result;
  }

  // Success case - call onComplete
  await tryCatch(
    ctx.run("onComplete", async () => await onComplete?.(data, result.value), {
      maxRetryAttempts: 1,
    }),
  );
  return result;
}