@quiesco/core 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  import { EventEmitter } from 'node:events';
10
10
  import type { AddressInfo } from 'node:net';
11
11
 
12
- import { CloseCode, ErrorCode, JsonRpcErrorCode, PROTOCOL_VERSION } from '@quiesco/protocol';
12
+ import { CloseCode, ErrorCode, HOST_TICK, HOST_TICK_MS, JsonRpcErrorCode, PROTOCOL_VERSION } from '@quiesco/protocol';
13
13
  import type { AgentConfig, AgentEvents, AgentMethods, HostMethods, ParamsOf, Platform, ResultOf } from '@quiesco/protocol';
14
14
  import { WebSocketServer } from 'ws';
15
15
  import type { WebSocket } from 'ws';
@@ -36,6 +36,7 @@ export class AgentConnection extends EventEmitter<{
36
36
  private nextId = 1;
37
37
  private readonly pending = new Map<number, Pending>();
38
38
  private _closed = false;
39
+ private ticker: ReturnType<typeof setInterval> | null = null;
39
40
 
40
41
  constructor(
41
42
  private readonly socket: WebSocket,
@@ -72,9 +73,35 @@ export class AgentConnection extends EventEmitter<{
72
73
  }, timeoutMs);
73
74
  this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer, method });
74
75
  this.socket.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }));
76
+ this.startTicks();
75
77
  });
76
78
  }
77
79
 
80
+ /**
81
+ * While a call is pending, a `tick` notification every HOST_TICK_MS: the agent checks its wait for idle
82
+ * again on each one, also when the app's JS timers are paused in the background (issue #66).
83
+ */
84
+ private startTicks(): void {
85
+ if (this.ticker !== null) return;
86
+ this.ticker = setInterval(() => {
87
+ if (this.pending.size === 0 || this._closed) {
88
+ this.stopTicks();
89
+ return;
90
+ }
91
+ try {
92
+ this.socket.send(JSON.stringify({ jsonrpc: '2.0', method: HOST_TICK }));
93
+ } catch {
94
+ // The socket is closing: onClosed rejects the pending calls.
95
+ }
96
+ }, HOST_TICK_MS);
97
+ this.ticker.unref?.();
98
+ }
99
+
100
+ private stopTicks(): void {
101
+ if (this.ticker !== null) clearInterval(this.ticker);
102
+ this.ticker = null;
103
+ }
104
+
78
105
  close(code: number = CloseCode.NORMAL, reason = ''): void {
79
106
  this.socket.close(code, reason);
80
107
  this.onClosed(code, reason);
@@ -99,6 +126,7 @@ export class AgentConnection extends EventEmitter<{
99
126
  onClosed(code: number, reason: string): void {
100
127
  if (this._closed) return;
101
128
  this._closed = true;
129
+ this.stopTicks();
102
130
  for (const [, p] of this.pending) {
103
131
  clearTimeout(p.timer);
104
132
  p.reject(new QuiescoError('AGENT_DISCONNECTED', `The app disconnected while handling ${p.method} (close code ${code})`, { method: p.method, code }));