(delayMs)
| 123 | } |
| 124 | |
| 125 | _scheduleInbound(delayMs) { |
| 126 | if (!this._running) return; |
| 127 | this._inTimer = setTimeout(async () => { |
| 128 | // Same defence-in-depth pattern as _scheduleOutbound: a throw |
| 129 | // from inbound.pull / ackDelivered / _isIdle used to escape the |
| 130 | // setTimeout callback and silently park the inbound loop. |
| 131 | let nextDelay = DEFAULT_POLL_INTERVAL_ACTIVE; |
| 132 | let hubRetryAfterMs = 0; |
| 133 | try { |
| 134 | if (!this._running) return; |
| 135 | try { |
| 136 | const result = await this.inbound.pull(); |
| 137 | if (result.retryAfterMs > 0) { |
| 138 | hubRetryAfterMs = result.retryAfterMs; |
| 139 | } else if (result.received > 0) { |
| 140 | this._lastActivity = Date.now(); |
| 141 | if (typeof this.onInboundReceived === 'function') { |
| 142 | try { this.onInboundReceived(result.received); } catch (e) { |
| 143 | this.logger.warn?.('[sync] onInboundReceived callback failed:', e.message); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | if (!hubRetryAfterMs) { |
| 148 | const ack = await this.inbound.ackDelivered(); |
| 149 | if (ack.retryAfterMs > 0) hubRetryAfterMs = ack.retryAfterMs; |
| 150 | } |
| 151 | } catch (err) { |
| 152 | if (err instanceof AuthError) { |
| 153 | await this._handleAuthError('inbound'); |
| 154 | } else { |
| 155 | this.logger.error(`[sync] inbound error: ${err.message}`); |
| 156 | } |
| 157 | } |
| 158 | if (hubRetryAfterMs > 0) { |
| 159 | nextDelay = Math.max(1_000, hubRetryAfterMs); |
| 160 | } else { |
| 161 | try { |
| 162 | nextDelay = this._isIdle() |
| 163 | ? DEFAULT_POLL_INTERVAL_IDLE |
| 164 | : DEFAULT_POLL_INTERVAL_ACTIVE; |
| 165 | } catch (err) { |
| 166 | this.logger.error(`[sync] _isIdle threw (non-fatal): ${err && err.message}`); |
| 167 | } |
| 168 | } |
| 169 | } catch (err) { |
| 170 | this.logger.error(`[sync] inbound tick threw (non-fatal): ${err && err.message}`); |
| 171 | } finally { |
| 172 | if (this._running) this._scheduleInbound(nextDelay); |
| 173 | } |
| 174 | }, delayMs); |
| 175 | if (this._inTimer.unref) this._inTimer.unref(); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | module.exports = { SyncEngine, DEFAULT_OUTBOUND_INTERVAL }; |
no test coverage detected