# recouse/eventsource architecture

> Architecture diagram of the GitHub repository recouse/eventsource, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-26). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/recouse/eventsource
- Repository: https://github.com/recouse/eventsource

## Overview

1. **What this repo is**
   - A single Swift Package named `EventSource`.
   - It is a client-side library for consuming Server-Sent Events over a persistent HTTP connection.
   - There is no app, server, or UI layer here; the whole repo is the library plus a small test suite.

2. **Public entry point**
   - The main API is the `EventSource` type in `Sources/EventSource/EventSource.swift`.
   - Consumers create an `EventSource`, build a data task from a `URLRequest`, and iterate over an async event stream.
   - The README shows two operating modes: standard SSE mode and `.dataOnly` mode for streaming APIs that send plain data chunks.

3. **Networking boundary**
   - The actual network connection is built on `URLSession`.
   - `SessionDelegate.swift` is the bridge between `URLSession` callbacks and the library’s internal event pipeline.
   - This is the key boundary between Apple networking APIs and the package’s higher-level SSE model.

4. **Streaming data pipeline**
   - Incoming bytes from the HTTP response are parsed incrementally, not buffered as a full response.
   - `EventParser.swift` converts streamed text lines into logical server events.
   - Parsed events are turned into `ServerEvent` values and forwarded to the consumer through the async interface.

5. **SSE model objects**
   - `ServerEvent.swift` represents a parsed event from the stream.
   - `Headers.swift` likely encapsulates SSE headers or request/response header handling needed by the connection setup.
   - `EventSourceError.swift` defines the package’s domain-specific failure cases.

6. **Parsing and normalization helpers**
   - `Data+Trim.swift` and `Extensions.swift` are supporting utilities used during parsing and stream handling.
   - These helpers exist to normalize raw input into SSE-compliant fields, such as trimming line endings or converting raw bytes into strings.
   - This keeps parsing logic focused and makes the parser easier to reason about.

7. **Concurrency and synchronization**
   - The package explicitly supports Swift concurrency and claims Swift 6 data-race safety.
   - `Mutex.swift` provides synchronization for shared mutable state inside the streaming/session machinery.
   - This is important because URLSession callbacks, parser state, and async event delivery all interact across concurrency boundaries.

8. **Event delivery contract**
   - The consumer-facing data flow is: `URLRequest` -> `EventSource` -> `dataTask` -> async event sequence.
   - Events surfaced to the caller include connection lifecycle states such as open, error, event payload, and closed, as shown in the README.
   - Cancellation is externalized through the enclosing `Task`; cancellation stops the stream and suppresses the final closed event.

9. **Data-only mode**
   - A notable architectural feature is `.dataOnly` mode.
   - In this mode, the library treats the stream more like a generic incremental text/data transport than a strict SSE event envelope.
   - That makes the package suitable for streaming APIs that reuse SSE framing but primarily send payload data chunks.

10. **Package shape and scope**
   - `Package.swift` defines a lightweight, dependency-free package.
   - There are no third-party runtime dependencies, which keeps the architecture small and portable.
   - The supported platforms listed in the README reflect that this is an Apple-platform Swift concurrency library.

11. **Testing focus**
   - The test target currently contains parser tests: `EventParserTests.swift`.
   - That suggests the parser is the most critical correctness boundary in the system.
   - The tests likely validate line folding, field parsing, event assembly, and edge cases in stream formatting.

12. **Operational boundaries to draw**
   - If you’re drawing an architecture diagram, the most important boxes are:
     - the caller/application
     - `EventSource` public API
     - `URLSession`/`SessionDelegate`
     - `EventParser`
     - `ServerEvent` / `EventSourceError`
     - the async event stream returned to the caller
   - The primary data flow is one-way from network bytes to parsed events, with cancellation and errors flowing back to the consumer.

Main entry points: [`Sources/EventSource/EventSource.swift`](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventSource.swift) (EventSource), [`Sources/EventSource/EventParser.swift`](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventParser.swift) (EventParser), [`Tests/EventSourceTests/EventParserTests.swift`](https://github.com/recouse/eventsource/blob/main/Tests/EventSourceTests/EventParserTests.swift) (Parser tests), [`Sources/EventSource/SessionDelegate.swift`](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/SessionDelegate.swift) (SessionDelegate)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_public_api["Public API"]
  node_caller["Caller<br/>consumer"]
  node_eventsource["EventSource<br/>api<br/>[EventSource.swift]"]
  node_stream["Event stream<br/>async seq"]
  node_sse_mode(("SSE mode"))
  node_dataonly_mode(("Data-only mode"))
end

subgraph group_networking["Networking"]
  node_urlsession["URLSession<br/>apple net"]
  node_delegate["SessionDelegate<br/>bridge"]
end

subgraph group_parsing["Parsing"]
  node_parser["EventParser<br/>[EventParser.swift]"]
end

subgraph group_domain["Domain"]
  node_mutex{{"Mutex<br/>sync<br/>[Mutex.swift]"}}
  node_server_event["ServerEvent<br/>model<br/>[ServerEvent.swift]"]
  node_event_error["EventError"]
  node_headers["Headers<br/>http util<br/>[Headers.swift]"]
  node_trim["Data trim<br/>bytes util<br/>[Data+Trim.swift]"]
  node_extensions["Extensions<br/>helpers<br/>[Extensions.swift]"]
  node_package["Package.swift<br/>[Package.swift]"]
end

subgraph group_tests["Tests"]
  node_tests["Parser tests"]
end

node_caller -->|"create"| node_eventsource
node_eventsource -->|"build task"| node_urlsession
node_urlsession -->|"callbacks"| node_delegate
node_delegate -->|"guard state"| node_mutex
node_delegate -->|"bytes in"| node_parser
node_parser -->|"use"| node_headers
node_parser -->|"normalize"| node_trim
node_trim -->|"support"| node_extensions
node_parser -->|"emit"| node_server_event
node_parser -->|"fail"| node_event_error
node_server_event -->|"deliver"| node_stream
node_event_error -->|"surface"| node_stream
node_eventsource -->|"supports"| node_sse_mode
node_eventsource -->|"supports"| node_dataonly_mode
node_eventsource -->|"returns"| node_stream
node_tests -->|"verify"| node_parser
node_tests -->|"assert"| node_server_event
node_tests -->|"assert"| node_event_error
node_package -->|"defines"| node_eventsource

click node_eventsource "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventSource.swift"
click node_delegate "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/SessionDelegate.swift"
click node_mutex "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Mutex.swift"
click node_parser "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventParser.swift"
click node_server_event "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/ServerEvent.swift"
click node_event_error "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventSourceError.swift"
click node_headers "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Headers.swift"
click node_trim "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Data+Trim.swift"
click node_extensions "https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Extensions.swift"
click node_package "https://github.com/recouse/eventsource/blob/main/Package.swift"
click node_tests "https://github.com/recouse/eventsource/blob/main/Tests/EventSourceTests/EventParserTests.swift"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_caller,node_eventsource,node_stream,node_sse_mode,node_dataonly_mode toneBlue
class node_urlsession,node_delegate toneAmber
class node_parser toneMint
class node_mutex,node_server_event,node_event_error,node_headers,node_trim,node_extensions,node_package toneRose
class node_tests toneIndigo
```

## Components

### Public API

Consumer-facing entry points and delivery contract.

- **Caller**: consumer · Application code that creates and consumes an EventSource.
- [EventSource](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventSource.swift): api · Public entry point for building a data task from a URLRequest and starting stream consumption. · `Sources/EventSource/EventSource.swift`
- **Event stream**: async seq · Async delivery surface used by callers to iterate over connection states and parsed items.
- **SSE mode**: mode · Standard server-sent events framing and event delivery.
- **Data-only mode**: mode · Streaming mode for plain incremental data chunks rather than strict SSE envelopes.

### Networking

URLSession bridge and connection lifecycle.

- **URLSession**: apple net · Underlying HTTP transport used for the persistent connection.
- [SessionDelegate](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/SessionDelegate.swift): bridge · Callback bridge from URLSession into the library's internal stream pipeline. · `Sources/EventSource/SessionDelegate.swift`

### Parsing

Incremental stream parsing and normalization.

- [EventParser](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventParser.swift): parser · Incremental parser that turns streamed text lines into logical events. · `Sources/EventSource/EventParser.swift`

### Domain

Stream model types, errors, and shared utilities.

- [Mutex](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Mutex.swift): sync · Synchronization for shared mutable state across callbacks and async delivery. · `Sources/EventSource/Mutex.swift`
- [ServerEvent](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/ServerEvent.swift): model · Parsed event value surfaced to consumers. · `Sources/EventSource/ServerEvent.swift`
- [EventError](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/EventSourceError.swift): error · Domain-specific failure cases for connection and parsing. · `Sources/EventSource/EventSourceError.swift`
- [Headers](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Headers.swift): http util · Header handling used during connection setup and stream interpretation. · `Sources/EventSource/Headers.swift`
- [Data trim](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Data+Trim.swift): bytes util · Byte-level normalization helper for line endings and field extraction. · `Sources/EventSource/Data+Trim.swift`
- [Extensions](https://github.com/recouse/eventsource/blob/main/Sources/EventSource/Extensions.swift): helpers · Support extensions used by parsing and stream handling. · `Sources/EventSource/Extensions.swift`
- [Package.swift](https://github.com/recouse/eventsource/blob/main/Package.swift): package · Dependency-free Swift package definition and platform metadata. · `Package.swift`

### Tests

Parser-focused verification boundary.

- [Parser tests](https://github.com/recouse/eventsource/blob/main/Tests/EventSourceTests/EventParserTests.swift): test · Parser-focused test suite covering event assembly and edge cases. · `Tests/EventSourceTests/EventParserTests.swift`

## Connections

- Caller → EventSource: create · Consumer constructs the library entry point.
- EventSource → URLSession: build task · Public API creates a URLSession-backed data task.
- URLSession → SessionDelegate: callbacks · Network callbacks are delivered into the package bridge.
- SessionDelegate → Mutex: guard state · Shared stream state is synchronized across callback and async contexts.
- SessionDelegate → EventParser: bytes in · Incoming response bytes are fed into the incremental parser.
- EventParser → Headers: use · Parser relies on header-aware stream interpretation.
- EventParser → Data trim: normalize · Raw input is trimmed and normalized before field parsing.
- Data trim → Extensions: support · Low-level normalization uses shared helper extensions.
- EventParser → ServerEvent: emit · Parsed stream lines are assembled into ServerEvent values.
- EventParser → EventError: fail · Parsing and stream handling can surface domain errors.
- ServerEvent → Event stream: deliver · Parsed events are forwarded through the async event stream.
- EventError → Event stream: surface · Failures propagate back through the consumer-facing stream contract.
- EventSource → SSE mode: supports · Default behavior is standard SSE event consumption.
- EventSource → Data-only mode: supports · Alternative mode treats the stream as incremental data chunks.
- EventSource → Event stream: returns · The main API exposes an async stream to iterate over.
- Parser tests → EventParser: verify · Tests focus on parser correctness and event assembly behavior.
- Parser tests → ServerEvent: assert · Tests validate the parsed event model produced by the parser.
- Parser tests → EventError: assert · Tests cover parser and stream failure cases.
- Package.swift → EventSource: defines · The manifest packages the library target.
