Skip to content

Commit 7a90b87

Browse files
committed
added a poll timeout so the loop will terminate when no more responses are needed to be polled
1 parent a8210d7 commit 7a90b87

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

native/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ register_module!(mut ctx, {
1515
RT = Some(Runtime::default());
1616
let _runner = std::thread::spawn(|| {
1717
Runtime::run();
18-
});
18+
});
1919
}
2020

2121
ctx.export_class::<js::JsResponse>("Response")?;

src/txn.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import { READ_ONLY_TXN, ALREADY_FINISHED } from './errors';
55

66
const log = debug('dgraph-js-native:txn');
77

8+
const POLL_TIMEOUT = Number(process.env.DGRAPH_JS_NATIVE_POLL_TIMEOUT || 5000);
9+
810
export type TxnOptions = {
911
readOnly?: boolean;
1012
bestEffort?: boolean;
@@ -15,13 +17,12 @@ export class Txn {
1517
private responses: { [key: string]: [(resp: Response) => void, (err: Error) => void] };
1618
private finished: boolean;
1719
private immediate: NodeJS.Immediate;
20+
private emptyTimestamp: number;
1821

1922
constructor(txn: QueryTxn) {
2023
this.txn = txn;
2124
this.responses = {};
2225
this.finished = false;
23-
24-
this.startPolling();
2526
}
2627

2728
private loop(): void {
@@ -58,9 +59,19 @@ export class Txn {
5859
}
5960

6061
private startPolling(): void {
62+
if (Object.keys(this.responses).length > 0) {
63+
this.emptyTimestamp = Date.now();
64+
}
65+
66+
if (Date.now() - this.emptyTimestamp >= POLL_TIMEOUT) {
67+
log(`no more new responses come in after ${POLL_TIMEOUT}ms, stopping the loop`);
68+
this.finished = true;
69+
}
70+
6171
if (!this.finished) {
6272
this.immediate = setImmediate(this.loop.bind(this));
6373
} else {
74+
log('stopping txn poll');
6475
clearImmediate(this.immediate);
6576
}
6677
}
@@ -176,8 +187,14 @@ export class Txn {
176187
private checkIsFinished(): Promise<void> {
177188
if (this.finished) {
178189
return Promise.reject(ALREADY_FINISHED);
190+
} else {
191+
if (!this.immediate) {
192+
log('starting to poll responses');
193+
this.emptyTimestamp = Date.now();
194+
this.startPolling();
195+
}
196+
return Promise.resolve();
179197
}
180-
return Promise.resolve();
181198
}
182199

183200
private isMutated(txn: QueryTxn | MutateTxn): txn is MutateTxn {

0 commit comments

Comments
 (0)