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

Improve performance for large messages across many chunks #130

Merged
merged 1 commit into from Jan 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/eventsource.js
Expand Up @@ -174,6 +174,8 @@ function EventSource (url, eventSourceInitDict) {
// Source/WebCore/page/EventSource.cpp
var isFirst = true
var buf
var startingPos = 0
var startingFieldLength = -1
res.on('data', function (chunk) {
buf = buf ? Buffer.concat([buf, chunk]) : chunk
if (isFirst && hasBom(buf)) {
Expand All @@ -193,10 +195,10 @@ function EventSource (url, eventSourceInitDict) {
}

var lineLength = -1
var fieldLength = -1
var fieldLength = startingFieldLength
var c

for (var i = pos; lineLength < 0 && i < length; ++i) {
for (var i = startingPos; lineLength < 0 && i < length; ++i) {
c = buf[i]
if (c === colon) {
if (fieldLength < 0) {
Expand All @@ -211,7 +213,12 @@ function EventSource (url, eventSourceInitDict) {
}

if (lineLength < 0) {
startingPos = length - pos
startingFieldLength = fieldLength
break
} else {
startingPos = 0
startingFieldLength = -1
}

parseEventStreamLine(buf, pos, fieldLength, lineLength)
Expand Down
20 changes: 20 additions & 0 deletions test/eventsource_test.js
Expand Up @@ -466,6 +466,26 @@ describe('Parser', function () {
}
})
})

it('parses a relatively huge message across many chunks efficiently', function (done) {
this.timeout(1000)

createServer(function (err, server) {
if (err) return done(err)

var longMessageContent = new Array(100000).join('a')
var longMessage = 'data: ' + longMessageContent + '\n\n'
var longMessageChunks = longMessage.match(/[\s\S]{1,10}/g) // Split the message into chunks of 10 characters
server.on('request', writeEvents(longMessageChunks))

var es = new EventSource(server.url)

es.onmessage = function (m) {
assert.equal(longMessageContent, m.data)
server.close(done)
rexxars marked this conversation as resolved.
Show resolved Hide resolved
}
})
})
})

describe('HTTP Request', function () {
Expand Down