|
1 | 1 | import * as path from 'node:path'; |
2 | 2 |
|
3 | 3 | import { ApiGateway } from '../gateways/api-gateway'; |
| 4 | +import { |
| 5 | + RealtimeResultsGateway, |
| 6 | + type RealtimeResultsSubscription, |
| 7 | +} from '../gateways/realtime-gateway'; |
4 | 8 | import { formatDurationSeconds } from '../methods'; |
5 | 9 | import type { AuthContext } from '../types/domain/auth.types'; |
6 | 10 | import { paths } from '../types/generated/schema.types'; |
@@ -65,12 +69,17 @@ export interface PollingResult { |
65 | 69 | */ |
66 | 70 | export class ResultsPollingService { |
67 | 71 | // The run keeps executing in the cloud regardless of whether the CLI can |
68 | | - // poll, so tolerate a long stretch of transient API/network blips (~5 min at |
69 | | - // the 10s base interval) before giving up. Losing a run to a brief hiccup is |
70 | | - // far more costly than waiting a bit longer. |
| 72 | + // poll, so tolerate a long stretch of transient API/network blips before |
| 73 | + // giving up. Losing a run to a brief hiccup is far more costly than waiting a |
| 74 | + // bit longer. |
71 | 75 | private readonly MAX_SEQUENTIAL_FAILURES = 30; |
72 | | - private readonly POLL_INTERVAL_MS = 10_000; |
73 | | - // Cap for the backoff applied between failed polls. |
| 76 | + // Backstop poll cadence. Logged-in (bearer) users also get realtime pushes |
| 77 | + // (see RealtimeResultsGateway), so they only need an occasional reconciling |
| 78 | + // poll; api-key users have no realtime and rely on the faster interval. |
| 79 | + private readonly BEARER_POLL_INTERVAL_MS = 60_000; |
| 80 | + private readonly APIKEY_POLL_INTERVAL_MS = 20_000; |
| 81 | + // Base unit for the backoff applied between *failed* polls, and its cap. |
| 82 | + private readonly ERROR_BACKOFF_BASE_MS = 10_000; |
74 | 83 | private readonly MAX_ERROR_BACKOFF_MS = 30_000; |
75 | 84 |
|
76 | 85 | /** |
@@ -107,70 +116,137 @@ export class ResultsPollingService { |
107 | 116 | let sequentialPollFailures = 0; |
108 | 117 | let previousSummary = ''; |
109 | 118 |
|
| 119 | + const pollIntervalMs = |
| 120 | + auth.mode === 'bearer' |
| 121 | + ? this.BEARER_POLL_INTERVAL_MS |
| 122 | + : this.APIKEY_POLL_INTERVAL_MS; |
| 123 | + |
| 124 | + // "Poke" mechanism: a realtime change resolves the current inter-poll wait |
| 125 | + // early. If a poke lands while we're mid-fetch (not waiting) it's latched |
| 126 | + // and consumed by the next wait, so events are never silently dropped. |
| 127 | + let resolveWake: (() => void) | null = null; |
| 128 | + let pendingPoke = false; |
| 129 | + const poke = () => { |
| 130 | + if (resolveWake) { |
| 131 | + const r = resolveWake; |
| 132 | + resolveWake = null; |
| 133 | + r(); |
| 134 | + } else { |
| 135 | + pendingPoke = true; |
| 136 | + } |
| 137 | + }; |
| 138 | + const waitForNextPoll = (ms: number): Promise<void> => { |
| 139 | + if (pendingPoke) { |
| 140 | + pendingPoke = false; |
| 141 | + return Promise.resolve(); |
| 142 | + } |
| 143 | + return new Promise<void>((resolve) => { |
| 144 | + const timer = setTimeout(() => { |
| 145 | + resolveWake = null; |
| 146 | + resolve(); |
| 147 | + }, ms); |
| 148 | + resolveWake = () => { |
| 149 | + clearTimeout(timer); |
| 150 | + resolve(); |
| 151 | + }; |
| 152 | + }); |
| 153 | + }; |
| 154 | + |
| 155 | + // Realtime is a latency optimisation over the backstop poll; only logged-in |
| 156 | + // (bearer) users can authenticate the socket under RLS. Any failure inside |
| 157 | + // the gateway degrades silently to pure polling. |
| 158 | + let subscription: RealtimeResultsSubscription | undefined; |
| 159 | + if (auth.mode === 'bearer' && auth.accessToken && auth.orgId && auth.env) { |
| 160 | + subscription = RealtimeResultsGateway.subscribe({ |
| 161 | + accessToken: auth.accessToken, |
| 162 | + debug, |
| 163 | + env: auth.env, |
| 164 | + log: logger, |
| 165 | + onChange: poke, |
| 166 | + orgId: auth.orgId, |
| 167 | + uploadId, |
| 168 | + }); |
| 169 | + if (debug && logger) { |
| 170 | + logger( |
| 171 | + `[DEBUG] Realtime enabled; backstop poll every ${pollIntervalMs / 1000}s`, |
| 172 | + ); |
| 173 | + } |
| 174 | + } |
| 175 | + |
110 | 176 | if (debug && logger) { |
111 | 177 | logger(`[DEBUG] Starting polling loop for results`); |
112 | 178 | } |
113 | 179 |
|
114 | | - // Poll in a loop until all tests complete |
115 | | - // eslint-disable-next-line no-constant-condition |
116 | | - while (true) { |
117 | | - try { |
118 | | - const updatedResults = await this.fetchAndLogResults(apiUrl, auth, uploadId, debug, logger); |
119 | | - |
120 | | - const { summary } = this.calculateStatusSummary(updatedResults); |
121 | | - previousSummary = this.updateDisplayStatus( |
122 | | - updatedResults, |
123 | | - quiet, |
124 | | - json, |
125 | | - summary, |
126 | | - previousSummary, |
127 | | - ); |
| 180 | + try { |
| 181 | + // Poll in a loop until all tests complete |
| 182 | + // eslint-disable-next-line no-constant-condition |
| 183 | + while (true) { |
| 184 | + try { |
| 185 | + const updatedResults = await this.fetchAndLogResults(apiUrl, auth, uploadId, debug, logger); |
| 186 | + |
| 187 | + const { summary } = this.calculateStatusSummary(updatedResults); |
| 188 | + previousSummary = this.updateDisplayStatus( |
| 189 | + updatedResults, |
| 190 | + quiet, |
| 191 | + json, |
| 192 | + summary, |
| 193 | + previousSummary, |
| 194 | + ); |
| 195 | + |
| 196 | + const allComplete = updatedResults.every( |
| 197 | + (result) => !['PENDING', 'QUEUED', 'RUNNING'].includes(result.status), |
| 198 | + ); |
| 199 | + |
| 200 | + if (allComplete) { |
| 201 | + return await this.handleCompletedTests(updatedResults, { |
| 202 | + consoleUrl, |
| 203 | + debug, |
| 204 | + json, |
| 205 | + logger, |
| 206 | + testMetadata, |
| 207 | + uploadId, |
| 208 | + }); |
| 209 | + } |
128 | 210 |
|
129 | | - const allComplete = updatedResults.every( |
130 | | - (result) => !['PENDING', 'QUEUED', 'RUNNING'].includes(result.status), |
131 | | - ); |
| 211 | + // Reset failure counter on successful poll |
| 212 | + sequentialPollFailures = 0; |
| 213 | + |
| 214 | + // Wait for the next backstop poll, or a realtime poke, whichever comes |
| 215 | + // first. |
| 216 | + await waitForNextPoll(pollIntervalMs); |
| 217 | + } catch (error) { |
| 218 | + // Re-throw RunFailedError immediately (test failures, not polling errors) |
| 219 | + if (error instanceof RunFailedError) { |
| 220 | + throw error; |
| 221 | + } |
| 222 | + |
| 223 | + sequentialPollFailures++; |
132 | 224 |
|
133 | | - if (allComplete) { |
134 | | - return await this.handleCompletedTests(updatedResults, { |
135 | | - consoleUrl, |
| 225 | + // Handle polling errors (network issues, etc.) |
| 226 | + await this.handlePollingError( |
| 227 | + error, |
| 228 | + sequentialPollFailures, |
136 | 229 | debug, |
137 | | - json, |
138 | 230 | logger, |
139 | | - testMetadata, |
140 | 231 | uploadId, |
141 | | - }); |
| 232 | + ); |
| 233 | + |
| 234 | + // Back off (capped) before retrying so a flaky API gets some breathing |
| 235 | + // room instead of being hammered on every failure. |
| 236 | + await this.sleep( |
| 237 | + Math.min( |
| 238 | + this.ERROR_BACKOFF_BASE_MS * sequentialPollFailures, |
| 239 | + this.MAX_ERROR_BACKOFF_MS, |
| 240 | + ), |
| 241 | + ); |
142 | 242 | } |
143 | | - |
144 | | - // Reset failure counter on successful poll |
145 | | - sequentialPollFailures = 0; |
146 | | - |
147 | | - // Wait before next poll |
148 | | - await this.sleep(this.POLL_INTERVAL_MS); |
149 | | - } catch (error) { |
150 | | - // Re-throw RunFailedError immediately (test failures, not polling errors) |
151 | | - if (error instanceof RunFailedError) { |
152 | | - throw error; |
| 243 | + } |
| 244 | + } finally { |
| 245 | + if (subscription) { |
| 246 | + if (debug && logger) { |
| 247 | + logger('[DEBUG] Closing realtime subscription'); |
153 | 248 | } |
154 | | - |
155 | | - sequentialPollFailures++; |
156 | | - |
157 | | - // Handle polling errors (network issues, etc.) |
158 | | - await this.handlePollingError( |
159 | | - error, |
160 | | - sequentialPollFailures, |
161 | | - debug, |
162 | | - logger, |
163 | | - uploadId, |
164 | | - ); |
165 | | - |
166 | | - // Back off (capped) before retrying so a flaky API gets some breathing |
167 | | - // room instead of being hammered every 10s. |
168 | | - await this.sleep( |
169 | | - Math.min( |
170 | | - this.POLL_INTERVAL_MS * sequentialPollFailures, |
171 | | - this.MAX_ERROR_BACKOFF_MS, |
172 | | - ), |
173 | | - ); |
| 249 | + await subscription.unsubscribe(); |
174 | 250 | } |
175 | 251 | } |
176 | 252 | } |
|
0 commit comments