Skip to content

Commit 3bf8ec1

Browse files
committed
fix(backups): integrate PR #883 with bounded SFTP failure cleanup
2 parents 505b91e + 95bb99c commit 3bf8ec1

3 files changed

Lines changed: 382 additions & 31 deletions

File tree

Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
import { PassThrough, Readable, Writable } from "node:stream";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { BackupDestinationRow } from "../types";
4+
5+
const fake = vi.hoisted(() => ({
6+
mode: "success" as
7+
| "success"
8+
| "stream-failure"
9+
| "rename-failure"
10+
| "rename-hang"
11+
| "stream-close",
12+
sftp: undefined as unknown,
13+
unlinked: [] as string[],
14+
renamed: [] as Array<[string, string]>,
15+
cleanupHang: null as null | "handshake" | "unlink",
16+
unlinkError: null as (Error & { code?: number }) | null,
17+
clients: [] as Array<{ emit(event: string, error?: Error): boolean; ended: boolean }>,
18+
}));
19+
20+
vi.mock("ssh2", async () => {
21+
const { EventEmitter } = await import("node:events");
22+
return {
23+
Client: class extends EventEmitter {
24+
ended = false;
25+
constructor() {
26+
super();
27+
fake.clients.push(this);
28+
}
29+
30+
connect() {
31+
if (fake.cleanupHang === "handshake" && fake.clients.length > 1) return this;
32+
queueMicrotask(() => this.emit("ready"));
33+
return this;
34+
}
35+
36+
sftp(callback: (error: Error | undefined, sftp: unknown) => void) {
37+
callback(undefined, fake.sftp);
38+
}
39+
40+
end() {
41+
this.ended = true;
42+
this.emit("close");
43+
}
44+
},
45+
};
46+
});
47+
48+
import "./sftp";
49+
import { resolveDestination } from "../registry";
50+
51+
type TestWriteStream = Writable & { bytesWritten: number };
52+
53+
function makeSftp() {
54+
const sftp = {
55+
mkdir: vi.fn((_path: string, callback: (error?: Error | null) => void) => callback(null)),
56+
stat: vi.fn(),
57+
createWriteStream: vi.fn((_path: string) => {
58+
let stream: TestWriteStream;
59+
stream = new Writable({
60+
write(chunk: Buffer, _encoding, callback) {
61+
if (fake.mode === "stream-failure") {
62+
callback(new Error("upload failed"));
63+
return;
64+
}
65+
if (fake.mode === "stream-close") {
66+
stream.destroy();
67+
return;
68+
}
69+
stream.bytesWritten += chunk.byteLength;
70+
callback();
71+
},
72+
}) as TestWriteStream;
73+
stream.bytesWritten = 0;
74+
return stream;
75+
}),
76+
unlink: vi.fn((path: string, callback: (error?: Error | null) => void) => {
77+
fake.unlinked.push(path);
78+
if (fake.cleanupHang !== "unlink") callback(fake.unlinkError);
79+
}),
80+
rename: vi.fn((from: string, to: string, callback: (error?: Error | null) => void) => {
81+
fake.renamed.push([from, to]);
82+
if (fake.mode === "rename-hang") return;
83+
callback(fake.mode === "rename-failure" ? new Error("rename failed") : null);
84+
}),
85+
};
86+
fake.sftp = sftp;
87+
return sftp;
88+
}
89+
90+
const row: BackupDestinationRow = {
91+
id: "dest_1",
92+
organizationId: "org_1",
93+
name: "Backup SFTP",
94+
kind: "sftp",
95+
endpoint: null,
96+
region: null,
97+
bucket: null,
98+
pathPrefix: "/backups",
99+
sshHost: "backup.example.test",
100+
sshPort: 22,
101+
sshUser: "backup",
102+
accessKeyIdEnc: null,
103+
secretAccessKeyEnc: null,
104+
sftpPasswordEnc: "password",
105+
sftpPrivateKeyEnc: null,
106+
sftpKeyPassphraseEnc: null,
107+
};
108+
109+
beforeEach(() => {
110+
fake.mode = "success";
111+
fake.unlinked = [];
112+
fake.renamed = [];
113+
fake.cleanupHang = null;
114+
fake.unlinkError = null;
115+
fake.clients = [];
116+
vi.spyOn(console, "warn").mockImplementation(() => {});
117+
makeSftp();
118+
});
119+
120+
afterEach(() => {
121+
vi.useRealTimers();
122+
vi.restoreAllMocks();
123+
});
124+
125+
describe("SFTP destination temporary upload cleanup", () => {
126+
it("removes the temporary file when the stream fails", async () => {
127+
fake.mode = "stream-failure";
128+
129+
await expect(
130+
resolveDestination(row).put(
131+
"openship/project/service/run/artifact.tar.zst",
132+
Readable.from(["payload"]),
133+
{},
134+
),
135+
).rejects.toThrow("upload failed");
136+
137+
expect(fake.renamed).toEqual([]);
138+
expect(fake.unlinked).toHaveLength(1);
139+
expect(fake.unlinked[0]).toMatch(/\.uploading-[0-9a-f]{8}$/);
140+
});
141+
142+
it("removes the temporary file when finalization fails", async () => {
143+
fake.mode = "rename-failure";
144+
145+
await expect(
146+
resolveDestination(row).put(
147+
"openship/project/service/run/artifact.tar.zst",
148+
Readable.from(["payload"]),
149+
{},
150+
),
151+
).rejects.toThrow("rename failed");
152+
153+
expect(fake.renamed).toHaveLength(2);
154+
expect(fake.unlinked).toEqual([fake.renamed[0]![1], fake.renamed[0]![0]]);
155+
});
156+
157+
it("renames the temporary file and keeps it on success", async () => {
158+
const result = await resolveDestination(row).put(
159+
"openship/project/service/run/artifact.tar.zst",
160+
Readable.from(["payload"]),
161+
{},
162+
);
163+
164+
expect(result.bytesWritten).toBe(7);
165+
expect(fake.renamed).toHaveLength(1);
166+
expect(fake.renamed[0]?.[0]).toMatch(/\.uploading-[0-9a-f]{8}$/);
167+
expect(fake.renamed[0]?.[1]).toBe("/backups/openship/project/service/run/artifact.tar.zst");
168+
expect(fake.unlinked).toEqual([]);
169+
expect(fake.clients).toHaveLength(1);
170+
});
171+
172+
it.each(["error", "close"])(
173+
"reconnects to clean up after the upload SSH connection emits %s",
174+
async (event) => {
175+
vi.useFakeTimers();
176+
const body = new PassThrough();
177+
let failure: unknown;
178+
const put = resolveDestination(row)
179+
.put("artifact.zst", body, {})
180+
.catch((error) => {
181+
failure = error;
182+
});
183+
await vi.advanceTimersByTimeAsync(1);
184+
fake.clients[0]!.emit(event, new Error("SSH disconnected"));
185+
await put;
186+
187+
expect(failure).toBeInstanceOf(Error);
188+
expect(fake.unlinked[0]).toMatch(/artifact\.zst\.uploading-[0-9a-f]{8}$/);
189+
expect(fake.clients).toHaveLength(2);
190+
expect(fake.clients.every((client) => client.ended)).toBe(true);
191+
expect(body.destroyed).toBe(true);
192+
expect(vi.getTimerCount()).toBe(0);
193+
},
194+
);
195+
196+
it.each(["handshake", "unlink"] as const)(
197+
"bounds cleanup when the %s callback never arrives",
198+
async (stage) => {
199+
vi.useFakeTimers();
200+
fake.mode = "stream-failure";
201+
fake.cleanupHang = stage;
202+
let failure: unknown;
203+
const put = resolveDestination(row)
204+
.put("artifact.zst", Readable.from(["payload"]), {})
205+
.catch((error) => {
206+
failure = error;
207+
});
208+
await vi.advanceTimersByTimeAsync(10_001);
209+
210+
expect(failure).toMatchObject({ message: "upload failed" });
211+
await put;
212+
expect(fake.clients.every((client) => client.ended)).toBe(true);
213+
expect(vi.getTimerCount()).toBe(0);
214+
},
215+
);
216+
217+
it("cleans up and fails when final rename never acknowledges", async () => {
218+
vi.useFakeTimers();
219+
fake.mode = "rename-hang";
220+
let failure: unknown;
221+
const put = resolveDestination(row)
222+
.put("artifact.zst", Readable.from(["payload"]), {})
223+
.catch((error) => {
224+
failure = error;
225+
});
226+
await vi.advanceTimersByTimeAsync(10_001);
227+
228+
expect(failure).toMatchObject({ message: "SFTP upload finalization timed out" });
229+
await put;
230+
expect(fake.unlinked).toEqual([fake.renamed[0]![0]]);
231+
});
232+
233+
it("does not finalize a prematurely closed write stream", async () => {
234+
fake.mode = "stream-close";
235+
await expect(
236+
resolveDestination(row).put("artifact.zst", Readable.from(["payload"]), {}),
237+
).rejects.toThrow("closed before all bytes were written");
238+
expect(fake.renamed).toEqual([]);
239+
expect(fake.unlinked).toHaveLength(1);
240+
});
241+
242+
it("preserves source failures and treats an already absent temporary file as cleaned", async () => {
243+
fake.unlinkError = Object.assign(new Error("No such file"), { code: 2 });
244+
const body = new Readable({
245+
read() {
246+
this.destroy(new Error("source failed"));
247+
},
248+
});
249+
await expect(resolveDestination(row).put("artifact.zst", body, {})).rejects.toThrow(
250+
"source failed",
251+
);
252+
expect(fake.unlinked).toHaveLength(1);
253+
expect(console.warn).not.toHaveBeenCalled();
254+
});
255+
});

0 commit comments

Comments
 (0)