MCPcopy Create free account
hub / github.com/callstack/agent-device / streamReadableToFile

Function streamReadableToFile

src/daemon/artifact-download.ts:43–108  ·  view source on GitHub ↗
(
  source: NodeJS.ReadableStream,
  destPath: string,
)

Source from the content-addressed store, hash-verified

41}
42
43export function streamReadableToFile(
44 source: NodeJS.ReadableStream,
45 destPath: string,
46): Promise<void> {
47 return new Promise((resolve, reject) => {
48 let settled = false;
49 let bytesWritten = 0;
50 let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
51 const output = fs.createWriteStream(destPath);
52
53 const settle = (error?: unknown) => {
54 if (settled) return;
55 settled = true;
56 if (timeoutHandle) clearTimeout(timeoutHandle);
57 if (error) {
58 void removePartialFile(output, destPath).finally(() => reject(error));
59 return;
60 }
61 resolve();
62 };
63 const armTimeout = () => {
64 if (timeoutHandle) clearTimeout(timeoutHandle);
65 timeoutHandle = setTimeout(() => {
66 const error = new AppError(
67 'COMMAND_FAILED',
68 'Artifact transfer timed out due to inactivity',
69 {
70 timeoutMs: REQUEST_IDLE_TIMEOUT_MS,
71 },
72 );
73 if ('destroy' in source && typeof source.destroy === 'function') {
74 source.destroy(error);
75 }
76 byteLimit.destroy(error);
77 settle(error);
78 }, REQUEST_IDLE_TIMEOUT_MS);
79 };
80
81 const byteLimit = new Transform({
82 transform(chunk: Buffer | string, encoding, callback) {
83 armTimeout();
84 const size = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk, encoding);
85 bytesWritten += size;
86 if (bytesWritten > MAX_ARTIFACT_BYTES) {
87 callback(
88 new AppError(
89 'INVALID_ARGS',
90 `Upload exceeds maximum size of ${MAX_ARTIFACT_BYTES} bytes`,
91 ),
92 );
93 return;
94 }
95 callback(null, chunk);
96 },
97 });
98
99 source.on('aborted', () => {
100 settle(new AppError('COMMAND_FAILED', 'Artifact transfer was interrupted'));

Callers 3

receiveUploadFunction · 0.90
upload.test.tsFile · 0.90

Calls 2

armTimeoutFunction · 0.85
settleFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…