Skip to content

Commit bde4ffc

Browse files
authored
Add abort controller signal for efficient resource cleanup (#507)
This commit adds a new field to `ctx.request`, that allows to subscribe to attempt cleanup AbortSignal signals. Use this to cleanup any externally held resources, like database connections, etc'.
1 parent ca12811 commit bde4ffc

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

packages/restate-sdk/src/context.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ export interface Request {
6868
* Care should be taken to use them deterministically.
6969
*/
7070
readonly extraArgs: unknown[];
71+
72+
/**
73+
* This is a signal that is aborted when the current attempt has been completed either successful or unsuccessfully.
74+
* When the signal is aborted, the current attempt has been completed and the handler should not perform any more work, other
75+
* than cleanup any external resources that might be shared across attempts (e.g. database connections).
76+
*/
77+
readonly attemptCompletedSignal: AbortSignal;
7178
}
7279

7380
/* eslint-disable @typescript-eslint/no-explicit-any */

packages/restate-sdk/src/endpoint/handlers/generic.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,8 @@ export class GenericHandler implements RestateHandler {
277277
// Get input
278278
const input = coreVm.sys_input();
279279

280+
const abortController = new AbortController();
281+
280282
const invocationRequest: Request = {
281283
id: input.invocation_id,
282284
headers: input.headers.reduce((headers, { key, value }) => {
@@ -294,6 +296,7 @@ export class GenericHandler implements RestateHandler {
294296
),
295297
body: input.input,
296298
extraArgs,
299+
attemptCompletedSignal: abortController.signal,
297300
};
298301

299302
// Prepare logger
@@ -395,6 +398,11 @@ export class GenericHandler implements RestateHandler {
395398
inputReader.cancel().catch(() => {});
396399
})
397400
.finally(() => {
401+
try {
402+
abortController.abort();
403+
} catch (e) {
404+
// suppressed
405+
}
398406
invocationLoggers.delete(loggerId);
399407
})
400408
.catch(() => {});

0 commit comments

Comments
 (0)