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

Add pause/resume methods for cloudflare socket polyfill #976

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
29 changes: 27 additions & 2 deletions cf/polyfills.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,13 @@ function Socket() {
write,
end,
destroy,
read
read,
pause,
resume
})

let pauseState = null

return tcp

async function connect(port, host) {
Expand Down Expand Up @@ -183,6 +187,7 @@ function Socket() {
return true
}


function end(data) {
return data
? tcp.write(data, () => tcp.raw.close())
Expand All @@ -198,8 +203,12 @@ function Socket() {
try {
let done
, value
while (({ done, value } = await tcp.reader.read(), !done))
while (({ done, value } = await tcp.reader.read(), !done)) {
if (pauseState) {
await pauseState.promise
}
tcp.emit('data', Buffer.from(value))
}
} catch (err) {
error(err)
}
Expand All @@ -210,6 +219,22 @@ function Socket() {
tcp.emit('data', Buffer.from(value))
}


function pause() {
if (pauseState) return
pauseState = { }
pauseState.promise = new Promise((resolve) => {
pauseState.resolve = resolve
})
}

function resume() {
if (!pauseState) return
const s = pauseState
pauseState = null
s.resolve()
}

function error(err) {
tcp.emit('error', err)
tcp.emit('close')
Expand Down