Skip to content
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

feat: add net.Socket-based interceptor #375

Closed
wants to merge 4 commits into from
Closed
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
171 changes: 171 additions & 0 deletions test/modules/http/socket.impl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import net from 'net'
import { Interceptor } from '../../../src'

// net.createConnection()
// Socket.connect()
// lookup
// emitLookup
// socket._handle.connect()
// -> afterComplete
// socket.push(null), socket.read(), socket.emit('connect'), socket.emit('ready')

export interface SocketEventMap {
connection: () => void
}

export class SocketInterceptor extends Interceptor<SocketEventMap> {
static interceptorSymbol = Symbol('SocketInterceptor')

constructor() {
super(SocketInterceptor.interceptorSymbol)
}

protected setup(): void {
const pureNetCreateConnection = net.createConnection
this.subscriptions.push(() => {
net.createConnection = pureNetCreateConnection
})
}
}

class MockSocket extends net.Socket {
private _handle?: SocketHandle

constructor(options?: net.SocketConstructorOpts) {
super(options)
this.connect(options)
}

connect(...args: unknown[]): this {
const [_, callback] = normalizeCreateConnectionArgs(...args)

/**
* @note Setting "_handle" is mandatory. Without it,
* Node considers the socket closed.
* The handle is set during ".connect()" method.
*/
this._handle = new SocketHandle()

if (callback) {
this.once('connect', callback)
}

/**
* @note Skip the DNS lookup and the actual connection
* and treat the socket as connected.
*
* @todo We should still perform the connection, swallow
* connection errors, and replay them.
*/
this.emit('connect')
this.emit('ready')

return this
}

write(
chunk: string,
encoding?: BufferEncoding,
callback?: (error?: Error) => void
) {
console.log('MockSocket.write', chunk, encoding, callback)

/**
* @note Two empty lines at the end of a socket message
* indicate the end of the message.
*/
if (chunk.endsWith('\r\n\r\n')) {
process.nextTick(() => {
this.push('HTTP/1.1 301 Moved Permanently\r\nConnection:close\r\n')
this.push('\r\n')
})
}

return super.write(chunk, encoding, callback)
}
}

interface TcpWrap {
address: string
port: number
localAddress?: number
localPort?: number
oncomplete(
status: number,
handle: SocketHandle,
tcpWrap: TcpWrap,
readable?: boolean,
writable?: boolean
): number
}

class SocketHandle {
connect(tcpWrap: TcpWrap, ip: string, port: number) {
return 0
}

connect6() {
return 0
}

readStart() {}

readStop() {}

setNoDelay() {}

writeLatin1String() {
return 0
}

writeUtf8String() {
return 0
}

close() {}

shutdown() {
return 0
}
}

function normalizeCreateConnectionArgs(
...args:
| [options: net.NetConnectOpts, callback?: () => void]
| [port: number, host?: string, callback?: () => void]
| [path: string, callback?: () => void]
): [options: net.NetConnectOpts, callback?: () => void] {
if (typeof args[0] === 'number') {
if (typeof args[1] === 'string') {
return [{ port: args[0], host: args[1] }, args[2]]
}

return [{ port: args[0] }, args[1]]
}

if (typeof args[0] === 'string') {
return [{ path: args[0] }, args[1]]
}

return args
}

net.createConnection = new Proxy(net.createConnection, {
apply(target, thisArg, args: any[]) {
const [options] = normalizeCreateConnectionArgs(...args)
console.log('net.createConnection()', args)

/**
* @note You can provide a custom "lookup" function to the
* network connection that the Socket will use to resolve
* the given host to an IP address and family.
* This is how we can suppress DNS lookup for non-existing hosts.
*/
// args[0].lookup = function (host, dnsOptions, emitLookup) {
// console.log('net.lookup:', host, dnsOptions, emitLookup)
// // emitLookup(null, '127.0.0.1', 4)
// }

return new MockSocket(options)
},
})
29 changes: 29 additions & 0 deletions test/modules/http/socket.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import './socket.impl'

import net from 'net'
import http from 'http'
import { it, expect } from 'vitest'

it('supports HTTP requests on the Socket level', async () => {
await new Promise<void>((resolve, reject) => {
http
.get('http://api.example.com/resource', (response) => {
console.log(response.statusCode, response.statusMessage)
expect(response.statusCode).toBe(301)
expect(response.statusMessage).toBe('Moved Permanently')
resolve()
})
.on('error', reject)
})
})

it('supports SMTP requests at the Socket level', async () => {
const socket = net.createConnection(25, 'gmail-smtp-in.l.google.com')
socket.write('FROM: <[email protected]>\r\n')
socket.write('TO: <[email protected]>\r\n')
socket.write('SUBJECT: Greeting\r\n')
socket.write('Hello, world!\r\n')
socket.write('.\r\n')

socket.on('error', console.error)
})