Skip to content
Open
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
12 changes: 11 additions & 1 deletion packages/pg-cloudflare/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export class CloudflareSocket extends EventEmitter {

private _upgrading = false
private _upgraded = false
private _ending = false
private _cfSocket: Socket | null = null
private _cfWriter: WritableStreamDefaultWriter | null = null
private _cfReader: ReadableStreamDefaultReader | null = null
Expand Down Expand Up @@ -65,7 +66,15 @@ export class CloudflareSocket extends EventEmitter {
// eslint-disable-next-line no-constant-condition
while (true) {
log('awaiting receive from CF socket')
const { done, value } = await this._cfReader!.read()
let result: ReadableStreamReadResult<Uint8Array>
try {
result = await this._cfReader!.read()
} catch (e) {
// closing the socket in end() rejects the read that is still pending
if (this._ending) break
throw e
}
const { done, value } = result
log('CF socket received:', done, value)
if (done) {
log('done')
Expand Down Expand Up @@ -110,6 +119,7 @@ export class CloudflareSocket extends EventEmitter {

end(data = Buffer.alloc(0), encoding: BufferEncoding = 'utf8', callback: (...args: unknown[]) => void = () => {}) {
log('ending CF socket')
this._ending = true
this.write(data, encoding, (err) => {
const socket = this._cfSocket
const closePromise = socket?.close()
Expand Down
19 changes: 19 additions & 0 deletions packages/pg-esm-test/pg-cloudflare.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,23 @@ describe('pg-cloudflare', () => {
socket.end()
})
})

it('should stop listening without an error when end() closes the socket', async () => {
const socket = new CloudflareSocket()
let rejectRead
socket._cfReader = {
read: () =>
new Promise((resolve, reject) => {
rejectRead = reject
}),
}
socket._cfSocket = {
close: async () => rejectRead(new TypeError('This socket has been closed.')),
}

const listening = socket._listen()
socket.end()

await listening
})
})
Loading