Skip to content

Commit

Permalink
Handle errors from the initial fileExistsAndHasSize call
Browse files Browse the repository at this point in the history
  • Loading branch information
ravicious authored and github-actions committed Jan 2, 2025
1 parent b9948b2 commit 9200f21
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
17 changes: 17 additions & 0 deletions web/packages/teleterm/src/services/grpcCredentials/files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ afterAll(async () => {
await fs.rm(tempDir, { recursive: true, force: true });
});

beforeEach(() => {
jest.restoreAllMocks();
});

describe('readGrpcCert', () => {
it('reads the file if the file already exists', async () => {
await fs.writeFile(path.join(tempDir, 'already-exists'), 'foobar');
Expand Down Expand Up @@ -64,4 +68,17 @@ describe('readGrpcCert', () => {
message: expect.stringContaining('within the timeout'),
});
});

it('returns an error if stat fails', async () => {
const expectedError = new Error('Something went wrong');
jest.spyOn(fs, 'stat').mockRejectedValue(expectedError);

await expect(
readGrpcCert(
tempDir,
'non-existent',
{ timeoutMs: 100 } // Make sure that the test doesn't hang for 10s on failure.
)
).rejects.toEqual(expectedError);
});
});
16 changes: 13 additions & 3 deletions web/packages/teleterm/src/services/grpcCredentials/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
*/

import path from 'path';
import { watch } from 'fs';
import { type Stats, watch } from 'fs';
import { readFile, writeFile, stat, rename } from 'fs/promises';

import { wait } from 'shared/utils/wait';
Expand Down Expand Up @@ -64,7 +64,17 @@ export async function readGrpcCert(
const abortController = new AbortController();

async function fileExistsAndHasSize(): Promise<boolean> {
return !!(await stat(fullPath)).size;
let stats: Stats;
try {
stats = await stat(fullPath);
} catch (error) {
if (error?.code === 'ENOENT') {
return false;
}
throw error;
}

return !!stats.size;
}

function waitForFile(): Promise<Buffer> {
Expand Down Expand Up @@ -94,7 +104,7 @@ export async function readGrpcCert(

fileExistsAndHasSize().then(
exists => exists && resolve(readFile(fullPath)),
() => {} // Ignore err.
err => reject(err)
);
});
}
Expand Down

0 comments on commit 9200f21

Please sign in to comment.