|
| 1 | +import { SocketOptions, Socket, TlsOptions } from 'cloudflare:sockets' |
| 2 | +import { EventEmitter } from 'events' |
| 3 | + |
| 4 | +/** |
| 5 | + * Wrapper around the Cloudflare built-in socket that can be used by the `Connection`. |
| 6 | + */ |
| 7 | +export class CloudflareSocket extends EventEmitter { |
| 8 | + writable = false |
| 9 | + destroyed = false |
| 10 | + |
| 11 | + private _upgrading = false |
| 12 | + private _upgraded = false |
| 13 | + private _cfSocket: Socket | null = null |
| 14 | + private _cfWriter: WritableStreamDefaultWriter | null = null |
| 15 | + private _cfReader: ReadableStreamDefaultReader | null = null |
| 16 | + |
| 17 | + constructor(readonly ssl: boolean) { |
| 18 | + super() |
| 19 | + } |
| 20 | + |
| 21 | + setNoDelay() { |
| 22 | + return this |
| 23 | + } |
| 24 | + setKeepAlive() { |
| 25 | + return this |
| 26 | + } |
| 27 | + ref() { |
| 28 | + return this |
| 29 | + } |
| 30 | + unref() { |
| 31 | + return this |
| 32 | + } |
| 33 | + |
| 34 | + async connect(port: number, host: string, connectListener?: (...args: unknown[]) => void) { |
| 35 | + try { |
| 36 | + log('connecting') |
| 37 | + if (connectListener) this.once('connect', connectListener) |
| 38 | + |
| 39 | + const options: SocketOptions = this.ssl ? { secureTransport: 'starttls' } : {} |
| 40 | + const { connect } = await import('cloudflare:sockets') |
| 41 | + this._cfSocket = connect(`${host}:${port}`, options) |
| 42 | + this._cfWriter = this._cfSocket.writable.getWriter() |
| 43 | + this._addClosedHandler() |
| 44 | + |
| 45 | + this._cfReader = this._cfSocket.readable.getReader() |
| 46 | + if (this.ssl) { |
| 47 | + this._listenOnce().catch((e) => this.emit('error', e)) |
| 48 | + } else { |
| 49 | + this._listen().catch((e) => this.emit('error', e)) |
| 50 | + } |
| 51 | + |
| 52 | + await this._cfWriter!.ready |
| 53 | + log('socket ready') |
| 54 | + this.writable = true |
| 55 | + this.emit('connect') |
| 56 | + |
| 57 | + return this |
| 58 | + } catch (e) { |
| 59 | + this.emit('error', e) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + async _listen() { |
| 64 | + while (true) { |
| 65 | + log('awaiting receive from CF socket') |
| 66 | + const { done, value } = await this._cfReader!.read() |
| 67 | + log('CF socket received:', done, value) |
| 68 | + if (done) { |
| 69 | + log('done') |
| 70 | + break |
| 71 | + } |
| 72 | + this.emit('data', Buffer.from(value)) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + async _listenOnce() { |
| 77 | + log('awaiting first receive from CF socket') |
| 78 | + const { done, value } = await this._cfReader!.read() |
| 79 | + log('First CF socket received:', done, value) |
| 80 | + this.emit('data', Buffer.from(value)) |
| 81 | + } |
| 82 | + |
| 83 | + write( |
| 84 | + data: Uint8Array | string, |
| 85 | + encoding: BufferEncoding = 'utf8', |
| 86 | + callback: (...args: unknown[]) => void = () => {} |
| 87 | + ) { |
| 88 | + if (data.length === 0) return callback() |
| 89 | + if (typeof data === 'string') data = Buffer.from(data, encoding) |
| 90 | + |
| 91 | + log('sending data direct:', data) |
| 92 | + this._cfWriter!.write(data).then( |
| 93 | + () => { |
| 94 | + log('data sent') |
| 95 | + callback() |
| 96 | + }, |
| 97 | + (err) => { |
| 98 | + log('send error', err) |
| 99 | + callback(err) |
| 100 | + } |
| 101 | + ) |
| 102 | + return true |
| 103 | + } |
| 104 | + |
| 105 | + end(data = Buffer.alloc(0), encoding: BufferEncoding = 'utf8', callback: (...args: unknown[]) => void = () => {}) { |
| 106 | + log('ending CF socket') |
| 107 | + this.write(data, encoding, (err) => { |
| 108 | + this._cfSocket!.close() |
| 109 | + if (callback) callback(err) |
| 110 | + }) |
| 111 | + return this |
| 112 | + } |
| 113 | + |
| 114 | + destroy(reason: string) { |
| 115 | + log('destroying CF socket', reason) |
| 116 | + this.destroyed = true |
| 117 | + return this.end() |
| 118 | + } |
| 119 | + |
| 120 | + startTls(options: TlsOptions) { |
| 121 | + if (this._upgraded) { |
| 122 | + // Don't try to upgrade again. |
| 123 | + this.emit('error', 'Cannot call `startTls()` more than once on a socket') |
| 124 | + return |
| 125 | + } |
| 126 | + this._cfWriter!.releaseLock() |
| 127 | + this._cfReader!.releaseLock() |
| 128 | + this._upgrading = true |
| 129 | + this._cfSocket = this._cfSocket!.startTls(options) |
| 130 | + this._cfWriter = this._cfSocket.writable.getWriter() |
| 131 | + this._cfReader = this._cfSocket.readable.getReader() |
| 132 | + this._addClosedHandler() |
| 133 | + this._listen().catch((e) => this.emit('error', e)) |
| 134 | + } |
| 135 | + |
| 136 | + _addClosedHandler() { |
| 137 | + this._cfSocket!.closed.then(() => { |
| 138 | + if (!this._upgrading) { |
| 139 | + log('CF socket closed') |
| 140 | + this._cfSocket = null |
| 141 | + this.emit('close') |
| 142 | + } else { |
| 143 | + this._upgrading = false |
| 144 | + this._upgraded = true |
| 145 | + } |
| 146 | + }).catch((e) => this.emit('error', e)) |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +const debug = false |
| 151 | + |
| 152 | +function dump(data: unknown) { |
| 153 | + if (data instanceof Uint8Array || data instanceof ArrayBuffer) { |
| 154 | + const hex = Buffer.from(data).toString('hex') |
| 155 | + const str = new TextDecoder().decode(data) |
| 156 | + return `\n>>> STR: "${str.replace(/\n/g, '\\n')}"\n>>> HEX: ${hex}\n` |
| 157 | + } else { |
| 158 | + return data |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +function log(...args: unknown[]) { |
| 163 | + debug && console.log(...args.map(dump)) |
| 164 | +} |
0 commit comments