Skip to content

Commit 2b03c5b

Browse files
author
Luca Forstner
committed
beforeExit
1 parent fadc347 commit 2b03c5b

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

packages/node/src/sdk/client.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
1616
public traceProvider: BasicTracerProvider | undefined;
1717
private _tracer: Tracer | undefined;
1818
private _clientReportInterval: NodeJS.Timeout | undefined;
19+
private _clientReportOnExitFlushListener: (() => undefined) | undefined;
1920

2021
public constructor(options: NodeClientOptions) {
2122
const clientOptions: ServerRuntimeClientOptions = {
@@ -35,8 +36,8 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
3536

3637
if (clientOptions.sendClientReports !== false) {
3738
// There is one mild concern here, being that if users periodically and unboundedly create new clients, we will
38-
// create more and more intervals, which may leak memory. In these situations, users are required to
39-
// call `client.close()` in order to dispose of the client resource.
39+
// create more and more intervals and beforeExit listeners, which may leak memory. In these situations, users are
40+
// required to call `client.close()` in order to dispose of the acquired resources.
4041
// Users are already confronted with the same reality with the SessionFlusher at the time of writing this so the
4142
// working theory is that this should be fine.
4243
// Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage
@@ -47,6 +48,12 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
4748
}, CLIENT_REPORT_FLUSH_INTERVAL_MS)
4849
// Unref is critical, otherwise we stop the process from exiting by itself
4950
.unref();
51+
52+
this._clientReportOnExitFlushListener = () => {
53+
this._flushOutcomes();
54+
};
55+
56+
process.on('beforeExit', this._clientReportOnExitFlushListener);
5057
}
5158
}
5259

@@ -86,6 +93,10 @@ export class NodeClient extends ServerRuntimeClient<NodeClientOptions> {
8693
clearInterval(this._clientReportInterval);
8794
}
8895

96+
if (this._clientReportOnExitFlushListener) {
97+
process.off('beforeExit', this._clientReportOnExitFlushListener);
98+
}
99+
89100
return super.close(timeout);
90101
}
91102
}

0 commit comments

Comments
 (0)