Skip to content

Commit

Permalink
Properly close connections in Deno
Browse files Browse the repository at this point in the history
  • Loading branch information
porsager committed Apr 19, 2022
1 parent 408a2fb commit 13950af
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions deno/polyfills.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ export const net = {
const socket = {
error,
success,
readyState: 'closed',
readyState: 'open',
connect: (port, hostname) => {
socket.raw = null
socket.readyState = 'connecting'
typeof port === 'string'
? Deno.connect({ transport: 'unix', path: socket.path = port }).then(success, error)
: Deno.connect({ transport: 'tcp', port: socket.port = port, hostname: socket.hostname = hostname || 'localhost' }).then(success, error) // eslint-disable-line
Expand Down Expand Up @@ -72,15 +73,21 @@ export const net = {
return false
},
destroy: () => close(true),
end: close
end: (x) => {
x && socket.write(x)
close()
}
}

return socket

async function success(raw) {
if (socket.readyState !== 'connecting')
return raw.close()

const encrypted = socket.encrypted
socket.readyState = 'open'
socket.raw = raw
socket.readyState = 'open'
socket.encrypted
? call(socket.events.secureConnect)
: call(socket.events.connect)
Expand Down Expand Up @@ -115,10 +122,10 @@ export const net = {
}

function closed() {
socket.break = socket.encrypted = false
if (socket.readyState !== 'open')
if (socket.readyState === 'closed')
return

socket.break = socket.encrypted = false
call(socket.events.close)
socket.readyState = 'closed'
}
Expand All @@ -139,6 +146,7 @@ export const net = {
export const tls = {
connect({ socket, ...options }) {
socket.encrypted = true
socket.readyState = 'connecting'
Deno.startTls(socket.raw, { hostname: socket.hostname, ...options })
.then(socket.success, socket.error)
socket.raw = null
Expand Down

0 comments on commit 13950af

Please sign in to comment.