From 0c31ee13546da06a48f8bc282cb5434fa26c5906 Mon Sep 17 00:00:00 2001 From: Brahim Hadriche Date: Mon, 19 Oct 2026 11:37:27 -0400 Subject: [PATCH] Simplify lounge --- .../LoungeService/LoungeBackchannel.bs | 55 +++++---- .../Services/LoungeService/LoungeBytes.bs | 19 ---- .../Services/LoungeService/LoungeFraming.bs | 43 ------- .../Services/LoungeService/LoungeService.bs | 11 +- .../LoungeService/LoungeService.types.bs | 1 - .../tests/LoungeBackchannel.spec.bs | 52 ++++++++- .../components/tests/LoungeBytes.spec.bs | 41 ------- .../components/tests/LoungeFraming.spec.bs | 105 ------------------ .../components/tests/LoungeSession.spec.bs | 6 +- 9 files changed, 88 insertions(+), 245 deletions(-) delete mode 100644 playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs delete mode 100644 playlet-lib/src/components/Services/LoungeService/LoungeFraming.bs delete mode 100644 playlet-lib/src/source/components/tests/LoungeBytes.spec.bs delete mode 100644 playlet-lib/src/source/components/tests/LoungeFraming.spec.bs diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs b/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs index 8925f39e..c736ce38 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs +++ b/playlet-lib/src/components/Services/LoungeService/LoungeBackchannel.bs @@ -1,6 +1,6 @@ -import "pkg:/components/Services/LoungeService/LoungeFraming.bs" import "pkg:/components/Services/LoungeService/LoungeService.types.bs" import "pkg:/source/services/HttpClient.bs" +import "pkg:/source/utils/ByteArrayUtils.bs" import "pkg:/source/utils/Logging.bs" import "pkg:/source/utils/StringUtils.bs" import "pkg:/source/utils/Types.bs" @@ -71,10 +71,6 @@ class LoungeBackchannel m.closeReason = LoungeCloseReason.NotSent return [] end if - if m.statusCode < 0 - m.closeReason = LoungeCloseReason.Curl - return [] - end if if m.statusCode < 200 or m.statusCode >= 300 m.closeReason = LoungeCloseReason.Http return [] @@ -97,25 +93,42 @@ class LoungeBackchannel return commands end function - function CloseLabel() as string - if m.closeReason = LoungeCloseReason.Curl or m.closeReason = LoungeCloseReason.Http - return `${m.closeReason}_${Abs(m.statusCode)}` - end if - return m.closeReason - end function - + ' Frame = `\n`, the length counted in BYTES. The answer is complete, so a malformed or cut-off + ' frame ends the extraction: no later read can complete it. private function ExtractFrames(text as string) as object body = CreateObject("roByteArray") body.FromAsciiString(text) - result = LoungeFraming.Extract(body, 0) - if result.nextPos < body.Count() - LogTelemetryEvent({ - level: "warning" - message: `Lounge answer ended mid-frame, ${body.Count() - result.nextPos} bytes left: ${text}` - fingerprint: "lounge-partial-frame" - }) - end if - return result.frames + frames = [] + count = body.Count() + cursor = 0 + while cursor < count + if body[cursor] = 10 or body[cursor] = 13 + cursor += 1 + continue while + end if + frameStart = cursor + frameLength = 0 + ' Stops once the length exceeds the body: a frame that long can't be whole, and the integer can't overflow. + while cursor < count and body[cursor] >= 48 and body[cursor] <= 57 and frameLength <= count + frameLength = frameLength * 10 + body[cursor] - 48 + cursor += 1 + end while + if cursor < count and body[cursor] = 13 + cursor += 1 + end if + if cursor >= count or body[cursor] <> 10 or frameLength = 0 or count - cursor - 1 < frameLength + LogTelemetryEvent({ + level: "warning" + message: `Lounge answer has a malformed or cut-off frame at byte ${frameStart} of ${count}: ${text}` + fingerprint: "lounge-partial-frame" + }) + exit while + end if + dataStart = cursor + 1 + frames.Push(ByteArrayUtils.Slice(body, dataStart, dataStart + frameLength).ToAsciiString()) + cursor = dataStart + frameLength + end while + return frames end function private function Receive(frames as object) as LoungeCommand[] diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs b/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs deleted file mode 100644 index 0e171c21..00000000 --- a/playlet-lib/src/components/Services/LoungeService/LoungeBytes.bs +++ /dev/null @@ -1,19 +0,0 @@ -import "pkg:/source/utils/ByteArrayUtils.bs" - -namespace LoungeBytes - - function RangeToString(bytes as object, fromIndex as integer, toIndex as integer) as string - return ByteArrayUtils.Slice(bytes, fromIndex, toIndex).ToAsciiString() - end function - - function IndexOfByte(bytes as object, fromIndex as integer, value as integer) as integer - last = bytes.Count() - 1 - for i = fromIndex to last - if bytes[i] = value - return i - end if - end for - return -1 - end function - -end namespace diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeFraming.bs b/playlet-lib/src/components/Services/LoungeService/LoungeFraming.bs deleted file mode 100644 index fe73753d..00000000 --- a/playlet-lib/src/components/Services/LoungeService/LoungeFraming.bs +++ /dev/null @@ -1,43 +0,0 @@ -import "pkg:/components/Services/LoungeService/LoungeBytes.bs" - -namespace LoungeFraming - - ' Frame = `\n`, the length counted in BYTES. An incomplete trailing frame - ' is left unconsumed (nextPos marks its start). - function Extract(body as object, startPos as integer) as object - frames = [] - cursor = startPos - count = body.Count() - - while true - while cursor < count and (body[cursor] = 13 or body[cursor] = 10) - cursor += 1 - end while - if cursor >= count - exit while - end if - - lf = LoungeBytes.IndexOfByte(body, cursor, 10) - if lf = -1 - exit while - end if - - frameLength = Int(Val(LoungeBytes.RangeToString(body, cursor, lf).Trim(), 10)) - if frameLength <= 0 - cursor = lf + 1 - continue while - end if - - dataStart = lf + 1 - if count - dataStart < frameLength - exit while - end if - - frames.Push(LoungeBytes.RangeToString(body, dataStart, dataStart + frameLength)) - cursor = dataStart + frameLength - end while - - return { frames: frames, nextPos: cursor } - end function - -end namespace diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeService.bs b/playlet-lib/src/components/Services/LoungeService/LoungeService.bs index b425e098..a3bf7db3 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeService.bs +++ b/playlet-lib/src/components/Services/LoungeService/LoungeService.bs @@ -151,21 +151,20 @@ function RunSession(api as LoungeApi, messagePort as object) as boolean continue while end if - closeLabel = backchannel.CloseLabel() - LogDebug("Backchannel closed:", closeLabel, "next:", nextStep) + LogDebug("Backchannel closed:", backchannel.closeReason, backchannel.statusCode, "next:", nextStep) if nextStep = LoungeSessionStep.Drop LogTelemetryEvent({ level: "error" - message: `Lounge session dropped: no poll delivered for ${sinceDelivered.TotalSeconds()} s, last close: ${closeLabel}` - fingerprint: ["lounge-session-dropped", closeLabel] + message: `Lounge session dropped: no poll delivered for ${sinceDelivered.TotalSeconds()} s, last close: ${backchannel.closeReason} ${backchannel.statusCode}` + fingerprint: ["lounge-session-dropped", backchannel.closeReason, backchannel.statusCode] }) return false end if if nextStep = LoungeSessionStep.Retry and backchannel.closeReason <> LoungeCloseReason.Timeout LogTelemetryEvent({ level: "warning" - message: "Lounge backchannel failure: " + closeLabel - fingerprint: "lounge-backchannel-" + closeLabel + message: `Lounge backchannel failure: ${backchannel.closeReason} ${backchannel.statusCode}` + fingerprint: ["lounge-backchannel", backchannel.closeReason, backchannel.statusCode] }) end if diff --git a/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs b/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs index ba0807ed..8650fc41 100644 --- a/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs +++ b/playlet-lib/src/components/Services/LoungeService/LoungeService.types.bs @@ -4,7 +4,6 @@ enum LoungeCloseReason Stalled = "stalled" Timeout = "timeout" NotSent = "not_sent" - Curl = "curl" Http = "http" end enum diff --git a/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs b/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs index 7c029093..23c6539f 100644 --- a/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs +++ b/playlet-lib/src/source/components/tests/LoungeBackchannel.spec.bs @@ -75,7 +75,7 @@ namespace Tests m.assertEqual(backchannel.closeReason, LoungeCloseReason.Empty) end function - @it("returns the commands of the whole frames of an answer that ends mid-frame, and reports what is left") + @it("returns the commands of the whole frames of an answer that ends mid-frame, and reports where") function _() backchannel = new LoungeBackchannel() commands = m.PollOnce(backchannel, "/lounge/partial", { status: 200, body: m.Frame(`[[7,["noop"]]]`) + `40\n[[8,` }) @@ -84,7 +84,49 @@ namespace Tests m.assertEqual(backchannel.closeReason, LoungeCloseReason.Complete) event = m.global.telemetry.LogEvent m.assertEqual(event.fingerprint, "lounge-partial-frame") - m.assertTrue(event.message.InStr("7 bytes left") <> -1, event.message) + m.assertTrue(event.message.InStr("at byte 17 of 24") <> -1, event.message) + end function + + @it("counts a frame's length in bytes, so a multi-byte character does not shift the next frame") + function _() + backchannel = new LoungeBackchannel() + titleBytes = CreateObject("roByteArray") + titleBytes.FromHexString("636166C3A9") + title = titleBytes.ToAsciiString() + commands = backchannel.StartSession(m.Frame(`[[0,["setTitle","${title}"]]]`) + m.Frame(`[[1,["noop"]]]`)) + m.assertEqual(commands.Count(), 2) + m.assertEqual(commands[0].args, title) + m.assertEqual(commands[1].type, "noop") + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + @it("reads a length line that ends in CR LF") + function _() + backchannel = new LoungeBackchannel() + commands = backchannel.StartSession(`\r\n14\r\n[[0,["noop"]]]`) + m.assertEqual(commands.Count(), 1) + m.assertEqual(commands[0].type, "noop") + m.assertEmpty(m.global.telemetry.LogEvent) + end function + + @it("stops at a frame without a valid length, keeps the frames before it, and reports it") + function _() + for each badFrame in [`0\n`, `x\n[[1,["noop"]]]`, `14 [[1,["noop"]]]`, `99999999999999999999\n[[1,["noop"]]]`] + m.global.telemetry.LogEvent = {} + backchannel = new LoungeBackchannel() + commands = backchannel.StartSession(m.Frame(`[[0,["noop"]]]`) + badFrame + m.Frame(`[[2,["noop"]]]`)) + m.assertEqual(commands.Count(), 1, badFrame) + m.assertEqual(commands[0].index, 0, badFrame) + m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-partial-frame", badFrame) + end for + end function + + @it("ends a 2xx answer that is not framed as empty, and reports it") + function _() + backchannel = new LoungeBackchannel() + m.assertEmpty(m.PollOnce(backchannel, "/lounge/unframed", { status: 200, body: "" })) + m.assertEqual(backchannel.closeReason, LoungeCloseReason.Empty) + m.assertEqual(m.global.telemetry.LogEvent.fingerprint, "lounge-partial-frame") end function @it("skips the commands it already received") @@ -145,16 +187,14 @@ namespace Tests backchannel = new LoungeBackchannel() m.assertEmpty(m.PollOnce(backchannel, "/lounge/unknownsid", { status: 400, body: "Unknown SID" })) m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http) - m.assertEqual(backchannel.CloseLabel(), "http_400") m.assertEqual(backchannel.statusCode, 400) end function - @it("ends a poll the server drops with its curl code") + @it("ends a poll the server drops with the status the OS returns") function _() backchannel = new LoungeBackchannel() m.assertEmpty(m.PollOnce(backchannel, "/lounge/dropped", { drop: true })) - m.assertEqual(backchannel.closeReason, LoungeCloseReason.Curl) - m.assertEqual(backchannel.CloseLabel(), "curl_52") + m.assertEqual(backchannel.closeReason, LoungeCloseReason.Http) m.assertEqual(backchannel.statusCode, HttpClient.CurlErrors.CURLE_GOT_NOTHING) end function diff --git a/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs b/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs deleted file mode 100644 index 9013e113..00000000 --- a/playlet-lib/src/source/components/tests/LoungeBytes.spec.bs +++ /dev/null @@ -1,41 +0,0 @@ -import "pkg:/components/Services/LoungeService/LoungeBytes.bs" - -namespace Tests - - @suite - class LoungeBytesTests extends Rooibos.BaseTestSuite - - @describe("LoungeBytes byte helpers") - - @it("converts a byte range to a string, byte-exact across a UTF-8 boundary") - function rangeToString() - ' "Xcafé" where é is 2 bytes; extract "café" = bytes [1, end). - cafe = "caf" + m.Utf8(&hC3, &hA9) - bytes = m.Bytes("X" + cafe) - m.assertEqual(LoungeBytes.RangeToString(bytes, 1, bytes.Count()), cafe) - end function - - @it("finds the first byte value at or after a position, or -1") - function indexOfByte() - bytes = m.Bytes("a,b,c") - m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc(",")), 1) - m.assertEqual(LoungeBytes.IndexOfByte(bytes, 2, Asc(",")), 3) - m.assertEqual(LoungeBytes.IndexOfByte(bytes, 0, Asc("z")), -1) - end function - - function Bytes(text as string) as object - bytes = CreateObject("roByteArray") - bytes.FromAsciiString(text) - return bytes - end function - - function Utf8(b1 as integer, b2 as integer) as string - bytes = CreateObject("roByteArray") - bytes.Push(b1) - bytes.Push(b2) - return bytes.ToAsciiString() - end function - - end class - -end namespace diff --git a/playlet-lib/src/source/components/tests/LoungeFraming.spec.bs b/playlet-lib/src/source/components/tests/LoungeFraming.spec.bs deleted file mode 100644 index c03f87b5..00000000 --- a/playlet-lib/src/source/components/tests/LoungeFraming.spec.bs +++ /dev/null @@ -1,105 +0,0 @@ -import "pkg:/components/Services/LoungeService/LoungeFraming.bs" - -namespace Tests - - @suite - class LoungeFramingTests extends Rooibos.BaseTestSuite - - @describe("LoungeFraming.Extract") - - @it("extracts a single complete frame and reports the consumed position") - function singleFrame() - result = LoungeFraming.Extract(m.Bytes(`5\nhello`), 0) - m.assertEqual(result.frames.Count(), 1) - m.assertEqual(result.frames[0], "hello") - m.assertEqual(result.nextPos, 7) - end function - - @it("extracts multiple consecutive frames in one pass") - function multipleFrames() - result = LoungeFraming.Extract(m.Bytes(`5\nhello3\nfoo`), 0) - m.assertEqual(result.frames, ["hello", "foo"]) - end function - - @it("skips leading CR/LF between frames") - function leadingNewlines() - result = LoungeFraming.Extract(m.Bytes(`\r\n5\nhello`), 0) - m.assertEqual(result.frames, ["hello"]) - end function - - ' The bug that motivated the rewrite: the length prefix is a BYTE count, but the old - ' parser sliced with character-based string ops, so any multi-byte payload shifted every - ' subsequent frame. A char-based slice of 5 from "café2..." keeps 5 characters ("café2") - ' and desyncs; a byte-accurate slice keeps "café" (5 bytes) and frame 2 still lines up. - @it("slices payloads by byte length so multi-byte UTF-8 does not desync the stream") - function utf8ByteAccurate() - cafe = "caf" + m.Utf8(&hC3, &hA9) ' é is 2 bytes -> "café" is 5 bytes, 4 characters - body = m.Bytes(Str(m.ByteLen(cafe)).Trim() + Chr(10) + cafe + Str(m.ByteLen("ok")).Trim() + Chr(10) + "ok") - - result = LoungeFraming.Extract(body, 0) - m.assertEqual(result.frames.Count(), 2, "a character-based slice would mis-split frame 2") - m.assertEqual(result.frames[0], cafe) - m.assertEqual(result.frames[1], "ok") - end function - - @it("leaves a whole frame unconsumed when its payload has not fully arrived") - function partialPayload() - result = LoungeFraming.Extract(m.Bytes(`5\nhel`), 0) - m.assertEqual(result.frames.Count(), 0) - m.assertEqual(result.nextPos, 0) - end function - - @it("consumes complete frames but retains an incomplete trailing frame") - function partialAfterComplete() - result = LoungeFraming.Extract(m.Bytes(`5\nhello2\nh`), 0) - m.assertEqual(result.frames, ["hello"]) - m.assertEqual(result.nextPos, 7) - end function - - @it("waits when the length line is not yet terminated") - function partialLengthLine() - result = LoungeFraming.Extract(m.Bytes("12"), 0) - m.assertEqual(result.frames.Count(), 0) - m.assertEqual(result.nextPos, 0) - end function - - @it("resumes extraction from a caller-supplied position") - function resumeFromPosition() - ' Index 7 is the start of the second frame ("3\nfoo"). - result = LoungeFraming.Extract(m.Bytes(`5\nhello3\nfoo`), 7) - m.assertEqual(result.frames, ["foo"]) - end function - - @it("skips a non-positive length line instead of stalling") - function malformedLength() - result = LoungeFraming.Extract(m.Bytes(`0\n5\nhello`), 0) - m.assertEqual(result.frames, ["hello"]) - end function - - @it("returns no frames for an empty body") - function emptyBody() - result = LoungeFraming.Extract(m.Bytes(""), 0) - m.assertEqual(result.frames.Count(), 0) - m.assertEqual(result.nextPos, 0) - end function - - function Bytes(text as string) as object - bytes = CreateObject("roByteArray") - bytes.FromAsciiString(text) - return bytes - end function - - function ByteLen(text as string) as integer - return m.Bytes(text).Count() - end function - - function Utf8(b1 as integer, b2 as integer) as string - bytes = CreateObject("roByteArray") - bytes.Push(b1) - bytes.Push(b2) - return bytes.ToAsciiString() - end function - - end class - -end namespace diff --git a/playlet-lib/src/source/components/tests/LoungeSession.spec.bs b/playlet-lib/src/source/components/tests/LoungeSession.spec.bs index adde14dd..f4ce312e 100644 --- a/playlet-lib/src/source/components/tests/LoungeSession.spec.bs +++ b/playlet-lib/src/source/components/tests/LoungeSession.spec.bs @@ -14,7 +14,7 @@ namespace Tests @it("retries a failed poll") function _() - m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, 1000), LoungeSessionStep.Retry) + m.assertEqual(m.Step(LoungeCloseReason.Http, -7, 0, false, false, 1000), LoungeSessionStep.Retry) m.assertEqual(m.Step(LoungeCloseReason.Timeout, 0, 0, false, false, 40000), LoungeSessionStep.Retry) m.assertEqual(m.Step(LoungeCloseReason.Http, 503, 0, false, false, 1000), LoungeSessionStep.Retry) m.assertEqual(m.Step(LoungeCloseReason.Empty, 200, 0, false, false, 1000), LoungeSessionStep.Retry) @@ -42,11 +42,11 @@ namespace Tests @it("drops a session that delivered no poll for the give-up time, whatever the failure") function _() - m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop) + m.assertEqual(m.Step(LoungeCloseReason.Http, -7, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop) m.assertEqual(m.Step(LoungeCloseReason.Http, 400, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop) m.assertEqual(m.Step(LoungeCloseReason.Http, 401, 0, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop) m.assertEqual(m.Step(LoungeCloseReason.Stalled, 200, 3, false, false, LoungeSession.GIVE_UP_MS), LoungeSessionStep.Drop) - m.assertEqual(m.Step(LoungeCloseReason.Curl, -7, 0, false, false, LoungeSession.GIVE_UP_MS - 1), LoungeSessionStep.Retry) + m.assertEqual(m.Step(LoungeCloseReason.Http, -7, 0, false, false, LoungeSession.GIVE_UP_MS - 1), LoungeSessionStep.Retry) end function @it("never drops a session whose poll just delivered")