1
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+import * as fs from 'node:fs';
3
+import ComposioClient, { APIUserAbortError } from '@composio/client';
4
+import { Files } from '../../src/models/Files.node';
5
+import { ComposioRequestCancelledError } from '../../src/errors/SDKErrors';
6
+
7
+vi.mock('fs', () => ({
8
+ default: {
9
+ readFileSync: vi.fn(),
10
+ writeFileSync: vi.fn(),
11
+ existsSync: vi.fn(() => true),
12
+ mkdirSync: vi.fn(),
13
+ },
14
+ readFileSync: vi.fn(),
15
+ writeFileSync: vi.fn(),
16
+ existsSync: vi.fn(() => true),
17
+ mkdirSync: vi.fn(),
18
+}));
19
+
20
+// The SSRF guard resolves every S3 host before fetching it; resolve the test
21
+// hosts to a public address so no lookup leaves the process.
22
+vi.mock('node:dns/promises', () => ({
23
+ lookup: vi.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
24
+}));
25
+
26
+const mockFetch = vi.fn();
27
+global.fetch = mockFetch;
28
+
29
+/**
30
+ * A transfer that only ends when its signal aborts, rejecting with the
31
+ * signal's reason the way `fetch` does. A call that drops the caller's signal
32
+ * fails at once instead of hanging the test.
33
+ */
34
+const transferUntilAborted = (_url: string, init?: RequestInit): Promise<Response> =>
35
+ new Promise((_resolve, reject) => {
36
+ const signal = init?.signal;
37
+ if (!signal) {
38
+ reject(new Error('fetch was called without the caller signal'));
39
+ return;
40
+ }
41
+ if (signal.aborted) {
42
+ reject(signal.reason);
43
+ return;
44
+ }
45
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
46
+ });
47
+
48
+/**
49
+ * A download whose headers arrive at once but whose body stalls after the
50
+ * first chunk. Like `fetch`, the body stream fails with the signal's reason
51
+ * when the signal aborts. `bodyRead` reports when the SDK has started reading.
52
+ */
53
+const responseWithStalledBody = () => {
54
+ const state = { bodyRead: false };
55
+ const fetchImpl = (_url: string, init?: RequestInit): Promise<Response> => {
56
+ const signal = init?.signal;
57
+ if (!signal) {
58
+ return Promise.reject(new Error('fetch was called without the caller signal'));
59
+ }
60
+ const body = new ReadableStream<Uint8Array>({
61
+ start(controller) {
62
+ signal.addEventListener('abort', () => controller.error(signal.reason), { once: true });
63
+ },
64
+ pull(controller) {
65
+ if (state.bodyRead) {
66
+ return new Promise<void>(() => {});
67
+ }
68
+ state.bodyRead = true;
69
+ controller.enqueue(new Uint8Array(4));
70
+ },
71
+ });
72
+ return Promise.resolve(new Response(body, { status: 200 }));
73
+ };
74
+ return { state, fetchImpl };
75
+};
76
+
77
+const uploadParams = {
78
+ file: new File(['report contents'], 'report.txt', { type: 'text/plain' }),
79
+ toolSlug: 'GOOGLEDRIVE_UPLOAD_FILE',
80
+ toolkitSlug: 'googledrive',
81
+};
82
+
83
+const downloadParams = {
84
+ s3Url: 'https://s3.example.com/report.pdf',
85
+ toolSlug: 'GOOGLEDRIVE_DOWNLOAD_FILE',
86
+ mimeType: 'application/pdf',
87
+};
88
+
89
+describe('Files request cancellation', () => {
90
+ let createPresignedURL: ReturnType<typeof vi.fn>;
91
+ let files: Files;
92
+
93
+ beforeEach(() => {
94
+ vi.clearAllMocks();
95
+ createPresignedURL = vi.fn().mockResolvedValue({
96
+ key: 'uploads/report.txt',
97
+ type: 'new',
98
+ new_presigned_url: 'https://s3.example.com/upload',
99
+ });
100
+ const client = { files: { createPresignedURL } } as unknown as ComposioClient;
101
+ files = new Files(client);
102
+ });
103
+
104
+ afterEach(() => {
105
+ vi.restoreAllMocks();
106
+ });
107
+
108
+ describe('upload', () => {
109
+ it('sends the caller signal with the presigned-URL request and the S3 transfer', async () => {
110
+ const controller = new AbortController();
111
+ mockFetch.mockResolvedValueOnce(new Response(null, { status: 200 }));
112
+
113
+ await expect(files.upload(uploadParams, { signal: controller.signal })).resolves.toEqual({
114
+ name: 'report.txt',
115
+ mimetype: 'text/plain',
116
+ s3key: 'uploads/report.txt',
117
+ });
118
+
119
+ expect(createPresignedURL).toHaveBeenCalledWith(expect.any(Object), {
120
+ signal: controller.signal,
121
+ });
122
+ expect(mockFetch).toHaveBeenCalledWith(
123
+ 'https://s3.example.com/upload',
124
+ expect.objectContaining({ method: 'PUT', signal: controller.signal })
125
+ );
126
+ });
127
+
128
+ it('rejects with ComposioRequestCancelledError when aborted during the S3 transfer', async () => {
129
+ const controller = new AbortController();
130
+ mockFetch.mockImplementationOnce(transferUntilAborted);
131
+
132
+ const upload = files.upload(uploadParams, { signal: controller.signal });
133
+ await vi.waitFor(() => expect(mockFetch).toHaveBeenCalled());
134
+ controller.abort();
135
+
136
+ await expect(upload).rejects.toBeInstanceOf(ComposioRequestCancelledError);
137
+ });
138
+
139
+ it('rejects with ComposioRequestCancelledError when aborted during the presigned-URL request', async () => {
140
+ createPresignedURL.mockRejectedValueOnce(new APIUserAbortError());
141
+
142
+ await expect(
143
+ files.upload(uploadParams, { signal: AbortSignal.abort() })
144
+ ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
145
+ expect(mockFetch).not.toHaveBeenCalled();
146
+ });
147
+
148
+ it('rejects with ComposioRequestCancelledError when an AbortSignal.timeout fires', async () => {
149
+ mockFetch.mockImplementationOnce(transferUntilAborted);
150
+
151
+ await expect(
152
+ files.upload(uploadParams, { signal: AbortSignal.timeout(10) })
153
+ ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
154
+ });
155
+
156
+ it('rejects with ComposioRequestCancelledError when aborted while reading a URL', async () => {
157
+ const controller = new AbortController();
158
+ mockFetch.mockImplementationOnce(transferUntilAborted);
159
+
160
+ const upload = files.upload(
161
+ { ...uploadParams, file: 'https://files.example.com/report.pdf' },
162
+ { signal: controller.signal }
163
+ );
164
+ await vi.waitFor(() =>
165
+ expect(mockFetch).toHaveBeenCalledWith(
166
+ 'https://files.example.com/report.pdf',
167
+ expect.objectContaining({ signal: controller.signal })
168
+ )
169
+ );
170
+ controller.abort();
171
+
172
+ await expect(upload).rejects.toBeInstanceOf(ComposioRequestCancelledError);
173
+ expect(createPresignedURL).not.toHaveBeenCalled();
174
+ });
175
+
176
+ it('keeps a failure that is not an abort as-is', async () => {
177
+ mockFetch.mockResolvedValueOnce(new Response(null, { status: 403, statusText: 'Forbidden' }));
178
+
179
+ await expect(
180
+ files.upload(uploadParams, { signal: new AbortController().signal })
181
+ ).rejects.toThrow('Failed to upload file to S3: Forbidden');
182
+ });
183
+ });
184
+
185
+ describe('download', () => {
186
+ it('rejects with ComposioRequestCancelledError and writes nothing when aborted', async () => {
187
+ const controller = new AbortController();
188
+ mockFetch.mockImplementationOnce(transferUntilAborted);
189
+
190
+ const download = files.download(downloadParams, { signal: controller.signal });
191
+ await vi.waitFor(() => expect(mockFetch).toHaveBeenCalled());
192
+ controller.abort();
193
+
194
+ await expect(download).rejects.toBeInstanceOf(ComposioRequestCancelledError);
195
+ expect(fs.writeFileSync).not.toHaveBeenCalled();
196
+ });
197
+
198
+ it('rejects with ComposioRequestCancelledError when an AbortSignal.timeout fires', async () => {
199
+ mockFetch.mockImplementationOnce(transferUntilAborted);
200
+
201
+ await expect(
202
+ files.download(downloadParams, { signal: AbortSignal.timeout(10) })
203
+ ).rejects.toBeInstanceOf(ComposioRequestCancelledError);
204
+ expect(fs.writeFileSync).not.toHaveBeenCalled();
205
+ });
206
+
207
+ it('rejects with ComposioRequestCancelledError and writes nothing when aborted while reading the body', async () => {
208
+ const controller = new AbortController();
209
+ const { state, fetchImpl } = responseWithStalledBody();
210
+ mockFetch.mockImplementationOnce(fetchImpl);
211
+
212
+ const download = files.download(downloadParams, { signal: controller.signal });
213
+ await vi.waitFor(() => expect(state.bodyRead).toBe(true));
214
+ controller.abort();
215
+
216
+ await expect(download).rejects.toBeInstanceOf(ComposioRequestCancelledError);
217
+ expect(fs.writeFileSync).not.toHaveBeenCalled();
218
+ });
219
+
220
+ it('rejects with ComposioRequestCancelledError when aborted with a custom reason', async () => {
221
+ const controller = new AbortController();
222
+ mockFetch.mockImplementationOnce(transferUntilAborted);
223
+
224
+ const download = files.download(downloadParams, { signal: controller.signal });
225
+ await vi.waitFor(() => expect(mockFetch).toHaveBeenCalled());
226
+ controller.abort('caller gave up');
227
+
228
+ const error = await download.catch((e: unknown) => e);
229
+ expect(error).toBeInstanceOf(ComposioRequestCancelledError);
230
+ expect((error as Error).message).toBe('Request was cancelled by the caller');
231
+ expect((error as Error).cause).toBeUndefined();
232
+ });
233
+
234
+ it('downloads the file when the signal does not abort', async () => {
235
+ mockFetch.mockResolvedValueOnce(new Response(new Uint8Array(8), { status: 200 }));
236
+
237
+ const result = await files.download(downloadParams, {
238
+ signal: new AbortController().signal,
239
+ });
240
+
241
+ expect(result.s3Url).toBe(downloadParams.s3Url);
242
+ expect(fs.writeFileSync).toHaveBeenCalledOnce();
243
+ });
244
+ });
245
+});