Skip to content

refactor: update eventsource dependency and clean up code #782

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

Merged
merged 1 commit into from
Jul 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 33 additions & 19 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@
"@aws-sdk/client-lambda": "^3.817.0",
"@inquirer/prompts": "^7.5.3",
"@smartthings/core-sdk": "^8.4.1",
"axios": "1.9.0",
"axios": "1.10.0",
"chalk": "^5.4.1",
"env-paths": "^3.0.0",
"eventsource": "^2.0.2",
"eventsource": "^4.0.0",
"express": "^5.1.0",
"get-port-please": "^3.1.2",
"inquirer": "^9.3.7",
Expand All @@ -78,6 +78,7 @@
"qs": "^6.14.0",
"table": "^6.9.0",
"tslib": "^2.8.1",
"undici": "^7.11.0",
"uuid": "^11.1.0",
"yargs": "^18.0.0"
},
Expand All @@ -88,7 +89,6 @@
"@commitlint/cli": "^19.8.1",
"@commitlint/config-conventional": "^19.8.1",
"@stylistic/eslint-plugin": "^2.8.0",
"@types/eventsource": "^1.1.15",
"@types/express": "^5.0.2",
"@types/inquirer": "^9.0.7",
"@types/jest": "^29.5.14",
Expand Down
168 changes: 2 additions & 166 deletions src/__tests__/lib/live-logging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,10 @@ import { jest } from '@jest/globals'

import type { networkInterfaces } from 'node:os'
import type { inspect } from 'node:util'
import type { PeerCertificate, TLSSocket } from 'node:tls'

import type axios from 'axios'
import { AxiosError } from 'axios'
import stripAnsi from 'strip-ansi'

import type { Authenticator } from '@smartthings/core-sdk'

import type { HostVerifier, DriverInfo, LiveLogClientConfig } from '../../lib/live-logging.js'
import type { LiveLogMessage } from '../../lib/sse-io.js'
import type { fatalError } from '../../lib/util.js'

Expand All @@ -27,8 +22,6 @@ jest.unstable_mockModule('node:util', () => ({
inspect: inspectMock,
}))

const { debugMock, getLoggerMock, isDebugEnabledMock } = await import('../test-lib/logger-mock.js')

const requestMock = jest.fn<typeof axios.request>()
jest.unstable_mockModule('axios', () => ({
default: {
Expand All @@ -46,20 +39,20 @@ const {
handleConnectionErrors,
liveLogMessageFormatter,
logLevels,
newLiveLogClient,
parseIpAndPort,
} = await import('../../lib/live-logging.js')


/* eslint-disable @typescript-eslint/naming-convention */
describe('liveLogMessageFormatter', () => {
/* eslint-disable @typescript-eslint/naming-convention */
const errorEvent: LiveLogMessage = {
timestamp: 'event timestamp',
driver_id: 'driver-id',
driver_name: 'Driver',
log_level: logLevels.error.value,
message: 'Something bad happened.',
}
/* eslint-enable @typescript-eslint/naming-convention */

it('returns timestamp in event format', () => {
const format = liveLogMessageFormatter(errorEvent)
Expand Down Expand Up @@ -138,160 +131,3 @@ describe('handleConnectionErrors', () => {
expect(() => handleConnectionErrors('192.168.0.1', error)).not.toThrow()
})
})

describe('newLiveLogClient', () => {
const authority = '192.168.222.1:9495'
const authHeaders = { 'Auth-Header': 'header-value' }
const authenticateMock = jest.fn<Authenticator['authenticate']>().mockResolvedValue(authHeaders)
const authenticatorMock = { authenticate: authenticateMock } as unknown as Authenticator
const baseConfig: LiveLogClientConfig = {
authority,
authenticator: authenticatorMock,
timeout: 1000,
userAgent: 'user-agent',
}

const driver1: DriverInfo = { driver_id: 'driver-id-1', driver_name: 'Driver 1', status: 'some-status' }
const driver2: DriverInfo = { driver_id: 'driver-id-2', driver_name: 'Driver 2', status: 'other-status' }
const hubDriverList = [driver1, driver2]
const certificate = { valid_from: 'yesterday about 3 a.m.' } as PeerCertificate

it('generates populated LiveLogClient', () => {
expect(newLiveLogClient(baseConfig)).toStrictEqual({
getDrivers: expect.any(Function),
getLogSource: expect.any(Function),
})

expect(getLoggerMock).toHaveBeenCalledExactlyOnceWith('cli')
})

describe('getDrivers', () => {
it('returns driver list', async () => {
const client = newLiveLogClient(baseConfig)
requestMock.mockResolvedValueOnce({ data: hubDriverList })

expect(await client.getDrivers()).toBe(hubDriverList)

expect(authenticateMock).toHaveBeenCalledExactlyOnceWith()

expect(requestMock).toHaveBeenCalledExactlyOnceWith({
url: 'https://192.168.222.1:9495/drivers',
method: 'GET',
httpsAgent: expect.anything(), // TODO
timeout: 1000,
headers: { 'User-Agent': 'user-agent', ...authHeaders },
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: true,
},
})

expect(isDebugEnabledMock).not.toHaveBeenCalled()
expect(debugMock).not.toHaveBeenCalled()
})

it('verifies once an only once', async () => {
const verifierMock = jest.fn<HostVerifier>()
const config = { ...baseConfig, verifier: verifierMock }
const client = newLiveLogClient(config)
const getPeerCertificateMock = jest.fn<typeof TLSSocket.prototype.getPeerCertificate>().mockReturnValue(certificate)
requestMock.mockResolvedValue({ data: hubDriverList, request: { socket: { getPeerCertificate: getPeerCertificateMock } } })

expect(await client.getDrivers()).toBe(hubDriverList)
expect(verifierMock).toHaveBeenCalledExactlyOnceWith(certificate)
expect(getPeerCertificateMock).toHaveBeenCalledExactlyOnceWith()
expect(requestMock).toHaveBeenCalledTimes(1)

// Still once even though another request has been made!
expect(await client.getDrivers()).toBe(hubDriverList)
expect(verifierMock).toHaveBeenCalledExactlyOnceWith(certificate)
expect(getPeerCertificateMock).toHaveBeenCalledExactlyOnceWith()
expect(requestMock).toHaveBeenCalledTimes(2)
})

it.each([
{ code: 'ECONNREFUSED', message: 'Unable to connect to 192.168.222.1:9495' },
{ code: 'EHOSTUNREACH', message: 'Unable to connect to 192.168.222.1:9495' },
{ code: 'ETIMEDOUT', message: 'Connection to 192.168.222.1:9495 timed out' },
{ code: 'EHOSTDOWN', message: 'The host at 192.168.222.1:9495 is down' },
])('handles %s axios error with user facing message', async ({ code, message }) => {
const axiosError = { code, isAxiosError: true } as AxiosError
const client = newLiveLogClient(baseConfig)
requestMock.mockRejectedValueOnce(axiosError)

await expect(client.getDrivers()).rejects.toThrow(`${message}. Ensure hub address is correct and try again`)
})

const jsonError = {
request: {
headers: {
Authorization: 'Bearer 8a25775d-0e67-4dce-bbc9-0601ba6589ca',
},
},
}
it('logs axios error at debug level, scrubbing auth token', async () => {
isDebugEnabledMock.mockReturnValueOnce(true)
const toJSONMock = jest.fn<typeof AxiosError.prototype.toJSON>().mockReturnValue(jsonError)
const axiosError = { code: 'ECONNREFUSED', isAxiosError: true } as AxiosError
axiosError.toJSON = toJSONMock
const client = newLiveLogClient(baseConfig)
requestMock.mockRejectedValueOnce(axiosError)
inspectMock.mockReturnValueOnce('inspected axios.toJSON Bearer 8a25775d-0e67-4dce-bbc9-0601ba6589ca')
inspectMock.mockReturnValueOnce('inspected network interfaces')

await expect(client.getDrivers()).rejects.toThrow()

expect(isDebugEnabledMock).toHaveBeenCalledExactlyOnceWith()
expect(inspectMock).toHaveBeenCalledTimes(2)
expect(inspectMock).toHaveBeenCalledWith(jsonError)
expect(inspectMock).toHaveBeenCalledWith(interfaces)
expect(debugMock).toHaveBeenCalledWith('Error connecting to live-logging: inspected axios.toJSON' +
' Bearer 8a25775d-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n\n' +
'Local network interfaces: inspected network interfaces')
})

it('scrubs alternate auth token format', async () => {
isDebugEnabledMock.mockReturnValueOnce(true)
const toJSONMock = jest.fn<typeof AxiosError.prototype.toJSON>().mockReturnValue(jsonError)
const axiosError = { code: 'ECONNREFUSED', isAxiosError: true } as AxiosError
axiosError.toJSON = toJSONMock
const client = newLiveLogClient(baseConfig)
requestMock.mockRejectedValueOnce(axiosError)
inspectMock.mockReturnValueOnce('inspected axios.toJSON Authorization: some-other-token-format')
inspectMock.mockReturnValueOnce('inspected network interfaces')

await expect(client.getDrivers()).rejects.toThrow()

expect(isDebugEnabledMock).toHaveBeenCalledExactlyOnceWith()
expect(inspectMock).toHaveBeenCalledTimes(2)
expect(inspectMock).toHaveBeenCalledWith(jsonError)
expect(inspectMock).toHaveBeenCalledWith(interfaces)
expect(debugMock).toHaveBeenCalledWith('Error connecting to live-logging: inspected axios.toJSON' +
' Authorization: (redacted)\n\n' +
'Local network interfaces: inspected network interfaces')
})

it('rethrows non-axios errors unchanged', async () => {
const error = Error('other error')
const client = newLiveLogClient(baseConfig)
requestMock.mockRejectedValueOnce(error)

await expect(client.getDrivers()).rejects.toThrow(error)
})
})

describe('getLogSource', () => {
const client = newLiveLogClient(baseConfig)

it('returns URL with no query parameters for all drivers', () => {
expect(client.getLogSource()).toBe('https://192.168.222.1:9495/drivers/logs')
})

it('includes query parameter for a specific driver', () => {
expect(client.getLogSource('my-driver-id'))
.toBe('https://192.168.222.1:9495/drivers/logs?driver_id=my-driver-id')
})
})
})
/* eslint-enable @typescript-eslint/naming-convention */
14 changes: 0 additions & 14 deletions src/__tests__/lib/sse-util.test.ts

This file was deleted.

12 changes: 12 additions & 0 deletions src/__tests__/lib/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
clipToMaximum,
delay,
fatalError,
handleSignals,
sanitize,
terminationSignals,
stringFromUnknown,
} from '../../lib/util.js'

Expand Down Expand Up @@ -113,3 +115,13 @@ describe('asTextBulletedList', () => {
expect(asTextBulletedList(['one', 'two', 'three'])).toBe('\n - one\n - two\n - three')
})
})

test('handleSignals adds handler for all required Signals', () => {
const handler = jest.fn()

handleSignals(handler)

terminationSignals.forEach(signal => {
expect(process.listeners(signal)).toContain(handler)
})
})
Loading