generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 56
feat(toolkit-lib): network detector #926
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
Open
kaizencc
wants to merge
12
commits into
main
Choose a base branch
from
conroy/ping
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
7ee3f4d
feat: add network detector that uses notices endpoint
kaizencc 7718108
feat(toolkit-lib): network detector
kaizencc 91d3441
chore: refactor network detector to ping once an hour and write to disk
kaizencc 51ffbf6
Merge branch 'main' into conroy/ping
kaizencc d7dcdc6
update funnle test
kaizencc f69b420
mock network detector in notices
kaizencc f7cd018
chore: self mutation
invalid-email-address d0d4e93
merge
kaizencc ec0768f
chore: self mutation
invalid-email-address 60f2c12
udpate tests
kaizencc c342cc2
skip network check property
kaizencc 671b1ee
update network-detector
kaizencc 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
89 changes: 89 additions & 0 deletions
89
packages/@aws-cdk/toolkit-lib/lib/util/network-detector.ts
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,89 @@ | ||
| import * as https from 'node:https'; | ||
| import * as path from 'path'; | ||
| import * as fs from 'fs-extra'; | ||
| import { cdkCacheDir } from './'; | ||
|
|
||
| interface CachedConnectivity { | ||
| expiration: number; | ||
| hasConnectivity: boolean; | ||
| } | ||
|
|
||
| const TIME_TO_LIVE_SUCCESS = 60 * 60 * 1000; // 1 hour | ||
| const CACHE_FILE_PATH = path.join(cdkCacheDir(), 'connection.json'); | ||
|
|
||
| /** | ||
| * Detects internet connectivity by making a lightweight request to the notices endpoint | ||
| */ | ||
| export class NetworkDetector { | ||
| /** | ||
| * Check if internet connectivity is available | ||
| */ | ||
| public static async hasConnectivity(agent?: https.Agent): Promise<boolean> { | ||
| const cachedData = await this.load(); | ||
| const expiration = cachedData.expiration ?? 0; | ||
|
|
||
| if (Date.now() > expiration) { | ||
| try { | ||
| const connected = await this.ping(agent); | ||
| const updatedData = { | ||
| expiration: Date.now() + TIME_TO_LIVE_SUCCESS, | ||
| hasConnectivity: connected, | ||
| }; | ||
| await this.save(updatedData); | ||
| return connected; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } else { | ||
| return cachedData.hasConnectivity; | ||
| } | ||
| } | ||
|
|
||
| private static readonly TIMEOUT_MS = 500; | ||
|
|
||
| private static async load(): Promise<CachedConnectivity> { | ||
| const defaultValue = { | ||
| expiration: 0, | ||
| hasConnectivity: false, | ||
| }; | ||
|
|
||
| try { | ||
| return fs.existsSync(CACHE_FILE_PATH) | ||
| ? await fs.readJSON(CACHE_FILE_PATH) as CachedConnectivity | ||
| : defaultValue; | ||
| } catch { | ||
| return defaultValue; | ||
| } | ||
| } | ||
|
|
||
| private static async save(cached: CachedConnectivity): Promise<void> { | ||
| try { | ||
| await fs.ensureFile(CACHE_FILE_PATH); | ||
| await fs.writeJSON(CACHE_FILE_PATH, cached); | ||
| } catch { | ||
| // Silently ignore cache save errors | ||
| } | ||
| } | ||
|
|
||
| private static ping(agent?: https.Agent): Promise<boolean> { | ||
| return new Promise((resolve) => { | ||
| const req = https.request({ | ||
| hostname: 'cli.cdk.dev-tools.aws.dev', | ||
| path: '/notices.json', | ||
| method: 'HEAD', | ||
| agent, | ||
| timeout: this.TIMEOUT_MS, | ||
| }, (res) => { | ||
| resolve(res.statusCode !== undefined && res.statusCode < 500); | ||
| }); | ||
|
|
||
| req.on('error', () => resolve(false)); | ||
| req.on('timeout', () => { | ||
| req.destroy(); | ||
| resolve(false); | ||
| }); | ||
|
|
||
| req.end(); | ||
| }); | ||
| } | ||
| } |
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
169 changes: 169 additions & 0 deletions
169
packages/@aws-cdk/toolkit-lib/test/util/network-detector.test.ts
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,169 @@ | ||
| import * as https from 'node:https'; | ||
| import * as fs from 'fs-extra'; | ||
| import { NetworkDetector } from '../../lib/util/network-detector'; | ||
|
|
||
| // Mock the https module | ||
| jest.mock('node:https'); | ||
| const mockHttps = https as jest.Mocked<typeof https>; | ||
|
|
||
| // Mock fs-extra | ||
| jest.mock('fs-extra'); | ||
| const mockFs = fs as jest.Mocked<typeof fs>; | ||
|
|
||
| // Mock cdkCacheDir | ||
| jest.mock('../../lib/util', () => ({ | ||
| cdkCacheDir: jest.fn(() => '/mock/cache/dir'), | ||
| })); | ||
|
|
||
| describe('NetworkDetector', () => { | ||
| let mockRequest: jest.Mock; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockRequest = jest.fn(); | ||
| mockHttps.request.mockImplementation(mockRequest); | ||
| }); | ||
|
|
||
| test('returns true when server responds with success status', async () => { | ||
| const mockReq = { | ||
| on: jest.fn(), | ||
| end: jest.fn(), | ||
| destroy: jest.fn(), | ||
| }; | ||
|
|
||
| mockRequest.mockImplementation((_options, callback) => { | ||
| callback({ statusCode: 200 }); | ||
| return mockReq; | ||
| }); | ||
|
|
||
| mockFs.existsSync.mockReturnValue(false); | ||
| (mockFs.ensureFile as jest.Mock).mockResolvedValue(undefined); | ||
| (mockFs.writeJSON as jest.Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
| expect(result).toBe(true); // Should return true for successful HTTP response | ||
| }); | ||
|
|
||
| test('returns false when server responds with server error', async () => { | ||
| const mockReq = { | ||
| on: jest.fn(), | ||
| end: jest.fn(), | ||
| destroy: jest.fn(), | ||
| }; | ||
|
|
||
| mockRequest.mockImplementation((_options, callback) => { | ||
| callback({ statusCode: 500 }); | ||
| return mockReq; | ||
| }); | ||
|
|
||
| mockFs.existsSync.mockReturnValue(false); | ||
| (mockFs.ensureFile as jest.Mock).mockResolvedValue(undefined); | ||
| (mockFs.writeJSON as jest.Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
| expect(result).toBe(false); // Should return false for server error status codes | ||
| }); | ||
|
|
||
| test('returns false on network error', async () => { | ||
| const mockReq = { | ||
| on: jest.fn((event, handler) => { | ||
| if (event === 'error') { | ||
| setTimeout(() => handler(new Error('Network error')), 0); | ||
| } | ||
| }), | ||
| end: jest.fn(), | ||
| destroy: jest.fn(), | ||
| }; | ||
|
|
||
| mockRequest.mockReturnValue(mockReq); | ||
| mockFs.existsSync.mockReturnValue(false); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
| expect(result).toBe(false); // Should return false when network request fails | ||
| }); | ||
|
|
||
| test('returns cached result from disk when not expired', async () => { | ||
| const cachedData = { | ||
| expiration: Date.now() + 30000, // 30 seconds in future | ||
| hasConnectivity: true, | ||
| }; | ||
|
|
||
| mockFs.existsSync.mockReturnValue(true); | ||
| (mockFs.readJSON as jest.Mock).mockResolvedValue(cachedData); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
|
|
||
| expect(result).toBe(true); // Should return cached connectivity result | ||
| expect(mockRequest).not.toHaveBeenCalled(); // Should not make network request when cache is valid | ||
| }); | ||
|
|
||
| test('performs ping when disk cache is expired', async () => { | ||
| const expiredData = { | ||
| expiration: Date.now() - 1000, // 1 second ago | ||
| hasConnectivity: true, | ||
| }; | ||
|
|
||
| const mockReq = { | ||
| on: jest.fn(), | ||
| end: jest.fn(), | ||
| destroy: jest.fn(), | ||
| }; | ||
|
|
||
| mockRequest.mockImplementation((_options, callback) => { | ||
| callback({ statusCode: 200 }); | ||
| return mockReq; | ||
| }); | ||
|
|
||
| mockFs.existsSync.mockReturnValue(true); | ||
| (mockFs.readJSON as jest.Mock).mockResolvedValue(expiredData); | ||
| (mockFs.ensureFile as jest.Mock).mockResolvedValue(undefined); | ||
| (mockFs.writeJSON as jest.Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
|
|
||
| expect(result).toBe(true); // Should return fresh connectivity result | ||
| expect(mockRequest).toHaveBeenCalledTimes(1); // Should make network request when cache is expired | ||
| }); | ||
|
|
||
| test('handles cache save errors gracefully', async () => { | ||
| const mockReq = { | ||
| on: jest.fn(), | ||
| end: jest.fn(), | ||
| destroy: jest.fn(), | ||
| }; | ||
|
|
||
| mockRequest.mockImplementation((_options, callback) => { | ||
| callback({ statusCode: 200 }); | ||
| return mockReq; | ||
| }); | ||
|
|
||
| mockFs.existsSync.mockReturnValue(false); | ||
| (mockFs.ensureFile as jest.Mock).mockRejectedValue(new Error('Disk full')); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
|
|
||
| expect(result).toBe(true); // Should still return connectivity result despite cache save failure | ||
| }); | ||
|
|
||
| test('handles cache load errors gracefully', async () => { | ||
| const mockReq = { | ||
| on: jest.fn(), | ||
| end: jest.fn(), | ||
| destroy: jest.fn(), | ||
| }; | ||
|
|
||
| mockRequest.mockImplementation((_options, callback) => { | ||
| callback({ statusCode: 200 }); | ||
| return mockReq; | ||
| }); | ||
|
|
||
| mockFs.existsSync.mockReturnValue(true); | ||
| (mockFs.readJSON as jest.Mock).mockRejectedValue(new Error('Read failed')); | ||
| (mockFs.ensureFile as jest.Mock).mockResolvedValue(undefined); | ||
| (mockFs.writeJSON as jest.Mock).mockResolvedValue(undefined); | ||
|
|
||
| const result = await NetworkDetector.hasConnectivity(); | ||
|
|
||
| expect(result).toBe(true); // Should still return connectivity result despite cache load failure | ||
| }); | ||
| }); |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is throwing the right thing here? Is that error caught elsewhere? Asking because Notices should just silently fail. A comment might help.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is the right thing to do here. we are throwing errors in
web-data-sourceon failures and expecting to swallow them elsewhere (which we do)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[non-blocking] Since this pattern will be very common (get the result, check whether it's true and throw an error if not), we could also have a method that takes a callback and does this for you: