Skip to content

Commit

Permalink
chore: last days of websocket server
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Dec 13, 2024
1 parent c2d5c13 commit 657d7b1
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 55 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@
"is-node-process": "^1.2.0",
"outvariant": "^1.4.3",
"path-to-regexp": "^6.3.0",
"socket.io": "^4.6.1",
"socket.io-client": "^4.6.1",
"socket.io": "^4.8.1",
"socket.io-client": "^4.8.1",
"strict-event-emitter": "^0.5.1",
"type-fest": "^4.26.1",
"yargs": "^17.7.2"
Expand Down
32 changes: 13 additions & 19 deletions pnpm-lock.yaml

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

51 changes: 39 additions & 12 deletions src/core/handlers/RemoteRequestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export class RemoteRequestHandler extends RequestHandler<
resolver() {},
})

console.log('[RemoteRequestHandler] constructor', {

Check failure on line 43 in src/core/handlers/RemoteRequestHandler.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement
contextId: args.contextId,
})

this.socket = args.socket
this.contextId = args.contextId
}
Expand Down Expand Up @@ -77,6 +81,21 @@ export class RemoteRequestHandler extends RequestHandler<
responsePromise.resolve(undefined)
})

console.log(

Check failure on line 84 in src/core/handlers/RemoteRequestHandler.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement
'[RemoteRequestHandler] sending request to remote...',
new Date(),
)

// this.socket.send(JSON.stringify({ a: { b: { c: 1 } } }))
// this.socket.emit(
// 'foo',
// JSON.stringify({
// requestId: createRequestId(),
// contextId: this.contextId,
// serializeRequest: await serializeRequest(args.request),
// }),
// )

/**
* @note Remote request handler is special.
* It cannot await the mocked response from the remote process in
Expand All @@ -86,23 +105,31 @@ export class RemoteRequestHandler extends RequestHandler<
* Instead, the remote handler await the mocked response during the
* parsing phase since that's the only async phase before predicate.
*/
this.socket.emit('request', {
requestId: createRequestId(),
serializedRequest: await serializeRequest(args.request),
contextId: this.contextId,
})
debugger
this.socket.emit(
'request',
{
requestId: createRequestId(),
serializedRequest: await serializeRequest(args.request),
contextId: this.contextId,
},
(serializedResponse) => {
// Wait for the remote server to acknowledge this request with
// a response before continuing with the request handling.
responsePromise.resolve(
serializedResponse
? deserializeResponse(serializedResponse)
: undefined,
)
},
)

/**
* @todo Handle timeouts.
* @todo Handle socket errors.
*/
this.socket.on('response', ({ serializedResponse }) => {
responsePromise.resolve(
serializedResponse
? deserializeResponse(serializedResponse)
: undefined,
)
})

console.log('[RemoteRequestHandler] waiting for response from remote...')

Check failure on line 132 in src/core/handlers/RemoteRequestHandler.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement

return {
...parsedResult,
Expand Down
4 changes: 2 additions & 2 deletions src/core/utils/request/serializeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ export interface SerializedRequest {
method: string
url: string
headers: Array<[string, string]>
body?: ArrayBuffer
body: ArrayBuffer | undefined
}

export interface SerializedResponse {
__serializedType: 'response'
status: number
statusText?: string
headers: Array<[string, string]>
body?: ArrayBuffer
body: ArrayBuffer | undefined
}

/**
Expand Down
8 changes: 5 additions & 3 deletions src/node/SetupServerApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,6 @@ export class SetupServerApi
this.handlersController.currentHandlers,
{
apply: (target, thisArg, args) => {
console.log('.currentHandlers()...')

return Array.prototype.concat(
new RemoteRequestHandler({
socket,
Expand All @@ -176,6 +174,8 @@ export class SetupServerApi
return
}

console.log('[setupSever] beforeRequest', request.method, request.url)

Check failure on line 177 in src/node/SetupServerApi.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement

// Before the first request gets handled, await the sync server connection.
// This way we ensure that all the requests go through the `RemoteRequestHandler`.
await Promise.race([
Expand All @@ -185,10 +185,12 @@ export class SetupServerApi
setTimeout(resolve, 1000)
}),
])

console.log('[setupServer] beforeRequest COMPLETE!')

Check failure on line 189 in src/node/SetupServerApi.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement
}

// Forward all life-cycle events from this process to the remote.
this.forwardLifeCycleEvents()
// this.forwardLifeCycleEvents()
}
}

Expand Down
64 changes: 47 additions & 17 deletions src/node/setupRemoteServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,16 @@ export interface SetupRemoteServer {
}

export interface SyncServerEventsMap {
request: (args: {
serializedRequest: SerializedRequest
requestId: string
contextId?: string
}) => Promise<void> | void
request: (
args: {
serializedRequest: SerializedRequest
requestId: string
contextId?: string
},
callback: (serializedResponse: SerializedResponse | undefined) => void,
) => void

response: (args: {
serializedResponse?: SerializedResponse
}) => Promise<void> | void
foo: (data: string) => void

lifeCycleEventForward: <Type extends keyof SerializedLifeCycleEventsMap>(
type: Type,
Expand Down Expand Up @@ -140,12 +141,38 @@ export class SetupRemoteServerApi
.once('SIGTERM', () => closeSyncServer(server))
.once('SIGINT', () => closeSyncServer(server))

server.on('close', () => console.log('SERVER CLOSE'))

Check failure on line 144 in src/node/setupRemoteServer.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement
server.on('error', () => console.log('SERVER ERROR'))

Check failure on line 145 in src/node/setupRemoteServer.ts

View workflow job for this annotation

GitHub Actions / test (unit)

Unexpected console statement

server.on('connection', async (socket) => {
console.log('[setupRemoteServer] ws client connected!')

socket.on('error', (error) => {
console.log('[setupRemoteServer] ws client ERROR!', error)
})

socket.addListener('message', (data) => console.log('ANY DATA:', data))

console.log('ADD REQUEST LISTENER', new Date())

socket.on('foo', (data) => {
console.log('FOO RECEIVED!', data)
})

socket.on(
'request',
async ({ requestId, serializedRequest, contextId }) => {
async ({ contextId, requestId, serializedRequest }, callback) => {
console.log('[setupRemoteServer] REQUEST event')

const request = deserializeRequest(serializedRequest)

console.log(
'[setupRemoteServer] REQUEST',
request.method,
request.url,
{ contextId },
)

// By default, get the handlers from the current context.
let allHandlers = this.handlersController.currentHandlers()

Expand Down Expand Up @@ -173,23 +200,22 @@ export class SetupRemoteServerApi
const context = getContext()
allHandlers = context.handlers
}
const handlers = allHandlers.filter(isHandlerKind('RequestHandler'))

const response = await handleRequest(
request,
requestId,
allHandlers.filter(isHandlerKind('RequestHandler')),
handlers,
/**
* @todo Support resolve options from the `.listen()` call.
*/
{ onUnhandledRequest() {} },
dummyEmitter,
)

socket.emit('response', {
serializedResponse: response
? await serializeResponse(response)
: undefined,
})
console.log({ handlers, response })

callback(response ? await serializeResponse(response) : undefined)
},
)

Expand Down Expand Up @@ -255,6 +281,7 @@ async function createSyncServer(
const httpServer = http.createServer()
const ws = new WebSocketServer<SyncServerEventsMap>(httpServer, {
transports: ['websocket'],
httpCompression: false,
cors: {
/**
* @todo Set the default `origin` to localhost for security reasons.
Expand Down Expand Up @@ -330,7 +357,7 @@ export async function createSyncClient(args: { port: number }) {
// the user is expected to enable remote interception
// before the actual application with "setupServer".
timeout: 500,
reconnection: true,
reconnection: false,
extraHeaders: {
// Bypass the internal WebSocket connection requests
// to exclude them from the request lookup altogether.
Expand All @@ -339,11 +366,14 @@ export async function createSyncClient(args: { port: number }) {
},
})

socket.on('connect', () => {
socket.once('connect', () => {
console.log('[setupServer] ws client connected!', new Date())

connectionPromise.resolve(socket)
})

socket.io.once('error', (error) => {
console.log('[setupServer] ws client error!', error)
connectionPromise.reject(error)
})

Expand Down

0 comments on commit 657d7b1

Please sign in to comment.