@@ -5,6 +5,8 @@ import { READ_ONLY_TXN, ALREADY_FINISHED } from './errors';
55
66const log = debug ( 'dgraph-js-native:txn' ) ;
77
8+ const POLL_TIMEOUT = Number ( process . env . DGRAPH_JS_NATIVE_POLL_TIMEOUT || 5000 ) ;
9+
810export 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