-
-
Notifications
You must be signed in to change notification settings - Fork 315
fix(remote): renew the lease while an artifact upload runs (#2946) #2990
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
f1d3c54
fix(lease): renew a heartbeat with no ttl for the window the lease al…
thymikee d7ba497
fix(remote): renew the lease while an artifact upload runs on the cal…
thymikee 3b243c5
fix(lease): renew an admitted request for the window its lease carries
thymikee 284f114
fix(remote): beat to the lease's own window and stop the upload with it
thymikee 5ad1893
chore(gates): ack the upload wire digests the abort signal moved
thymikee d248f35
fix(remote): treat a beat the daemon rejects on its own terms as term…
thymikee 690a9ef
test(remote): drop the connection-close wait that hung the cancellati…
thymikee 2599af0
fix(remote): reject an aborted upload with the reason it was aborted
thymikee 0ac97d2
chore(gates): ack the two upload digests the abort-reason fix moved
thymikee 998a894
fix(remote): give each lease beat a budget and prove the beat on the …
thymikee 7add99f
refactor(remote): move the lease beat to its own module
thymikee 361f2c5
chore(gates): record the lease-beat module's type-only read of the wi…
thymikee 3f245ba
docs(leases): state what the first beat actually buys, and what an ab…
thymikee 64c279d
test(remote): let the caller release the stalled upload, so the outco…
thymikee f48bd0a
refactor(remote): fold the beat's thin wrappers into the one factory …
thymikee b18ed63
fix(remote): budget each beat from the window it protects, not the ca…
thymikee 4961801
fix(remote): load the lease beat only for the request that can use it
thymikee d626124
test(remote): give the slow-beat scenario the lane's parallel-scenari…
thymikee 0f7293b
test(remote): center the slow-beat number and un-detach the window doc
thymikee 4ca3281
test(remote): state the beat's transport cap, and fail the slow case …
thymikee ba9dad1
test(remote): settle the slow-beat count on arrivals instead of a wal…
thymikee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| // Ending an artifact upload when the work it serves is over (#2946). | ||
| // | ||
| // A beat that finds the device's lease gone aborts the upload protecting that lease. An upload is a | ||
| // piped `node:http` request, so the only way to stop bytes already in flight is the request's own | ||
| // abort signal — a rejection the caller swallows would keep streaming a full app bundle to a device | ||
| // nobody owns. Kept out of `upload-client.test.ts`, which is already over the test-file size | ||
| // tripwire and may not grow (docs/agents/testing.md). | ||
|
|
||
| import { afterEach, test } from 'vitest'; | ||
| import assert from 'node:assert/strict'; | ||
| import { createHash } from 'node:crypto'; | ||
| import fs from 'node:fs'; | ||
| import http, { type IncomingMessage, type ServerResponse } from 'node:http'; | ||
| import path from 'node:path'; | ||
| import { once } from 'node:events'; | ||
| import { uploadArtifact } from '../remote/upload-client.ts'; | ||
| import { mkdtempForTestSync } from './test-utils/tmp-dir.ts'; | ||
|
|
||
| const TEST_TOKEN = 'agent-device-upload-cancel-token'; | ||
| const tempDirs: string[] = []; | ||
|
|
||
| afterEach(async () => { | ||
| for (const dir of tempDirs) { | ||
| await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => {}); | ||
| } | ||
| tempDirs.length = 0; | ||
| }); | ||
|
|
||
| test('an aborted signal ends a legacy upload mid-stream instead of finishing the bytes', async () => { | ||
| // Two megabytes is well past what a paused read lets through: the assertions below are about the | ||
| // stream stopping, and a smaller payload keeps that off the CPU in a loaded lane. | ||
| const content = Buffer.alloc(2 * 1024 * 1024, 'x'); | ||
| const artifactPath = createTempFile('app.apk', content); | ||
| const control = new AbortController(); | ||
| let sawBytes = 0; | ||
|
|
||
| // Preflight reports itself unsupported so the upload takes the legacy stream, the one path that | ||
| // pipes a file at the daemon and keeps going for as long as the daemon drains it. | ||
| const server = await startServer(async (req, res) => { | ||
| if (req.method === 'POST' && req.url === '/upload/preflight') { | ||
| await readRequestBody(req); | ||
| res.statusCode = 404; | ||
| res.end('not found'); | ||
| return; | ||
| } | ||
| if (req.method === 'POST' && req.url === '/upload') { | ||
| req.on('data', (chunk: Buffer) => { | ||
| sawBytes += chunk.length; | ||
| // The lease dies once bytes are genuinely in flight — not before the request starts. | ||
| // Stopping the read applies backpressure so the rest of the file cannot race through | ||
| // loopback and make "stopped early" a matter of timing. | ||
| req.pause(); | ||
| if (!control.signal.aborted) control.abort(); | ||
| }); | ||
| return; | ||
| } | ||
| res.statusCode = 404; | ||
| res.end('not found'); | ||
| }); | ||
|
|
||
| try { | ||
| await assert.rejects( | ||
| async () => | ||
| await uploadArtifact({ | ||
| localPath: artifactPath, | ||
| baseUrl: server.baseUrl, | ||
| token: TEST_TOKEN, | ||
| signal: control.signal, | ||
| }), | ||
| isAbortError, | ||
| ); | ||
|
thymikee marked this conversation as resolved.
|
||
| assert.ok(sawBytes > 0, 'the upload had started streaming before the abort'); | ||
| assert.ok(sawBytes < content.length, `the stream stopped early, at ${sawBytes} bytes`); | ||
| } finally { | ||
| await server.close(); | ||
| } | ||
| }); | ||
|
|
||
| test('an aborted signal before preflight refuses to ask the daemon for a ticket', async () => { | ||
| const artifactPath = createTempFile('app.apk', 'payload'); | ||
| const control = new AbortController(); | ||
| control.abort(); | ||
| const requests: string[] = []; | ||
|
|
||
| const server = await startServer(async (req, res) => { | ||
| requests.push(`${req.method} ${req.url}`); | ||
| res.statusCode = 404; | ||
| res.end('not found'); | ||
| }); | ||
|
|
||
| try { | ||
| await assert.rejects( | ||
| async () => | ||
| await uploadArtifact({ | ||
| localPath: artifactPath, | ||
| baseUrl: server.baseUrl, | ||
| token: TEST_TOKEN, | ||
| signal: control.signal, | ||
| }), | ||
| isAbortError, | ||
| ); | ||
| assert.deepEqual(requests, [], 'an upload nobody waits for never reaches the daemon'); | ||
| } finally { | ||
| await server.close(); | ||
| } | ||
| }); | ||
|
|
||
| test('an upload with no signal behaves exactly as before', async () => { | ||
| const content = 'unprotected-payload'; | ||
| const artifactPath = createTempFile('app.apk', content); | ||
| const expectedHash = createHash('sha256').update(content).digest('hex'); | ||
|
|
||
| const server = await startServer(async (req, res) => { | ||
| if (req.method === 'POST' && req.url === '/upload/preflight') { | ||
| await readRequestBody(req); | ||
| res.statusCode = 404; | ||
| res.end('not found'); | ||
| return; | ||
| } | ||
| if (req.method === 'POST' && req.url === '/upload') { | ||
| assert.equal(req.headers['x-artifact-hash'], expectedHash); | ||
| await readRequestBody(req); | ||
| sendJson(res, { ok: true, uploadId: 'upload-uncancelled' }); | ||
| return; | ||
| } | ||
| res.statusCode = 404; | ||
| res.end('not found'); | ||
| }); | ||
|
|
||
| try { | ||
| const uploadId = await uploadArtifact({ | ||
| localPath: artifactPath, | ||
| baseUrl: server.baseUrl, | ||
| token: TEST_TOKEN, | ||
| }); | ||
| assert.equal(uploadId, 'upload-uncancelled'); | ||
| } finally { | ||
| await server.close(); | ||
| } | ||
| }); | ||
|
|
||
| function isAbortError(error: unknown): boolean { | ||
| // The contract on `signal` is that an aborted upload rejects with the signal's own reason. Any | ||
| // other rejection — a transport failure, the server-error fallback — means the upload stopped for | ||
| // a reason this test is not about and would let the abort path regress while staying green. | ||
| return error instanceof DOMException && error.name === 'AbortError'; | ||
| } | ||
|
|
||
| function createTempFile(filename: string, content: string | Buffer): string { | ||
| const dir = mkdtempForTestSync('agent-device-upload-cancel-'); | ||
| tempDirs.push(dir); | ||
| const filePath = path.join(dir, filename); | ||
| fs.writeFileSync(filePath, content); | ||
| return filePath; | ||
| } | ||
|
|
||
| async function startServer( | ||
| handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>, | ||
| ): Promise<{ baseUrl: string; close: () => Promise<void> }> { | ||
| const server = http.createServer((req, res) => { | ||
| void handler(req, res).catch(() => { | ||
| res.statusCode = 500; | ||
| res.end(); | ||
| }); | ||
| }); | ||
| // A canceled upload leaves its socket in a state `closeAllConnections` can race; without a bound | ||
| // idle keep-alive, `close` would then wait out Node's five-second default. | ||
| server.keepAliveTimeout = 100; | ||
| server.listen(0, '127.0.0.1'); | ||
| server.unref(); | ||
| await once(server, 'listening'); | ||
| const address = server.address(); | ||
| assert.ok(address && typeof address === 'object'); | ||
| return { | ||
| baseUrl: `http://127.0.0.1:${address.port}`, | ||
| close: async () => { | ||
| // A canceled upload leaves its socket half-open and a pooled keep-alive one behind; without | ||
| // dropping them, `close` would wait out the server's five-second keep-alive timeout. | ||
| server.closeAllConnections(); | ||
| await new Promise<void>((resolve, reject) => { | ||
| server.close((error) => (error ? reject(error) : resolve())); | ||
| }); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| async function readRequestBody(req: IncomingMessage): Promise<Buffer> { | ||
| const chunks: Buffer[] = []; | ||
| for await (const chunk of req) { | ||
| chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); | ||
| } | ||
| return Buffer.concat(chunks); | ||
| } | ||
|
|
||
| function sendJson(res: ServerResponse, body: unknown): void { | ||
| res.statusCode = 200; | ||
| res.setHeader('content-type', 'application/json'); | ||
| res.end(JSON.stringify(body)); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.