Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2650"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AsyncServerSentEvents"
BuildableName = "AsyncServerSentEvents"
BlueprintName = "AsyncServerSentEvents"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AsyncServerSentEventsTests"
BuildableName = "AsyncServerSentEventsTests"
BlueprintName = "AsyncServerSentEventsTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES"
queueDebuggingEnableBacktraceRecording = "Yes">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "AsyncServerSentEvents"
BuildableName = "AsyncServerSentEvents"
BlueprintName = "AsyncServerSentEvents"
ReferencedContainer = "container:">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Zac White

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
35 changes: 35 additions & 0 deletions PLAN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Improve the SSE Parser for 0.2.0

## Summary

Extract the parsing logic into `SSEParser`, a synchronous, value-semantic incremental parser, and rebuild the async APIs as thin wrappers over it. Everything that exists in 0.1.0 keeps compiling and behaving identically; the new surface is small and non-throwing.

## Public API Additions

- `SSEParser`, a `Sendable` **struct** (value semantics, no locking):
- `mutating func consume(_ byte: UInt8) -> ServerSentEvent?`
- `mutating func consume(_ bytes: some Sequence<UInt8>) -> [ServerSentEvent]`
- `mutating func finish()` — end of stream: applies an unterminated trailing field line (so a trailing `retry` still counts, matching 0.1.0), discards the incomplete block per spec, and resets for a new stream (BOM stripped again) while retaining reconnect state.
- `private(set) var lastEventId: String?` and `retryInterval: Int?` — the committed reconnect state.
- `static func parse(_ bytes: some Sequence<UInt8>) -> [ServerSentEvent]` for fully buffered input.
- Nothing throws: per spec, invalid UTF-8 decodes with replacement characters and malformed lines are ignored, so parsing is total.
- Generic `AsyncSequence where Element == UInt8` extension providing `.sse()`, replacing (source-compatibly) the concrete `SSEByteStream` and Darwin-only `URLSession.AsyncBytes` extensions.

## Deliberately cut from the other plan

- `ServerSentEventBlock` — its `data == nil` sentinel duplicated `ServerSentEvent` awkwardly; block-level state consumers just read `lastEventId`/`retryInterval` off the parser.
- `SSEParser.Limits` and throwing `consume` — speculative; can be added additively in a later release if ever needed.
- `.sseBlocks()` adapters — no consumer.

## Implementation Changes

- New `SSEParser.swift`: internal `SSELineSplitter` (byte → line state machine, CR/LF/CRLF, leading BOM) + `SSEParser` (field parsing directly from bytes, decoding only recognized values; no `String.split`).
- `AsyncServerSentEvents.AsyncIterator` becomes a loop feeding bytes to an `SSEParser`, mirroring committed state into the existing public `SSEState` actor only when it changes.
- `EventSource` reads reconnect state synchronously from its iterator's parser instead of awaiting the `SSEState` actor.
- Behavioral compatibility pinned: id commits only at blank line; retry applies per line (including an unterminated final line at EOF); state-only blocks observable; comment-only blocks silent; per-stream last-event-ID buffer resets across reconnects while the committed value persists.

## Test Plan

- All 63 existing tests pass unchanged (line-splitting tests port to the sync splitter, same assertions).
- New `SSEParserTests`: every existing fixture parsed sync vs async with identical events and final state; chunk-boundary invariance (sizes 1/2/3/7/16/1024); emission timing; state-only blocks; `finish()` reuse incl. BOM re-strip; trailing unterminated `retry` line.
- Clean `swift build` and `swift test`.
10 changes: 5 additions & 5 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import PackageDescription
let package = Package(
name: "AsyncServerSentEvents",
platforms: [
.iOS(.v17),
.tvOS(.v17),
.macOS(.v14),
.watchOS(.v9),
.macCatalyst(.v17),
.iOS(.v13),
.tvOS(.v13),
.macOS(.v10_15),
.watchOS(.v6),
.macCatalyst(.v13),
.visionOS(.v1)
],
products: [
Expand Down
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,36 @@ for try await event in bytes.sse() {

### Parsing any byte stream

The parser is generic over `AsyncSequence` with `UInt8` elements, so it isn't tied to `URLSession`:
The parser is generic over `AsyncSequence` with `UInt8` elements, so it isn't tied to `URLSession`. Any byte sequence can be wrapped directly or via the `.sse()` convenience:

```swift
let events = AsyncServerSentEvents(bytes: someByteSequence)
// or equivalently:
for try await event in someByteSequence.sse() { ... }
```

Parsing is lazy and driven by iteration: bytes are only consumed as you request events, errors from the byte stream are rethrown to the consumer, and cancelling the consuming task stops the parse.

### Incremental and buffered parsing (no async required)

`SSEParser` is the synchronous core the async APIs are built on. Use it directly when bytes arrive through something other than an `AsyncSequence` — a delegate callback, a WebSocket frame — or when you already have the whole payload:

```swift
// Incremental: feed chunks as they arrive.
var parser = SSEParser()
for event in parser.consume(chunk) {
print(event.type, event.data)
}
// At end of stream: discards an incomplete trailing block (per spec) and
// resets for a new stream, keeping lastEventId/retryInterval for reconnection.
parser.finish()

// Buffered: parse a complete payload in one call.
let events = SSEParser.parse(data)
```

`SSEParser` is a value type, never throws (malformed input is handled by the spec's own rules), and exposes `lastEventId` and `retryInterval` for implementing reconnection.

## Events

Each `ServerSentEvent` carries:
Expand All @@ -72,6 +94,7 @@ Each `ServerSentEvent` carries:

## Supported Features

- [x] Synchronous incremental parsing (`SSEParser`) usable without async sequences
- [x] WHATWG-compliant line parsing (`CR`, `LF`, `CRLF`)
- [x] UTF-8 decoding with replacement characters and leading BOM removal
- [x] Strict field parsing (`data`, `id`, `event`, `retry`) with single-space value trim
Expand Down
Loading
Loading