├── .github ├── CODEOWNERS ├── FUNDING.yml ├── ISSUE_TEMPLATE │ └── bug_report.md └── workflows │ └── ci.yml ├── .gitignore ├── .swiftpm └── xcode │ └── package.xcworkspace │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Package.swift ├── Package@swift-6.0.swift ├── README.md ├── Sources └── EventSource │ ├── EventParser.swift │ ├── EventSource.swift │ ├── EventSourceError.swift │ ├── Extensions.swift │ ├── Headers.swift │ ├── Mutex.swift │ ├── ServerEvent.swift │ └── SessionDelegate.swift └── Tests └── EventSourceTests └── EventParserTests.swift /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @Recouse 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: Recouse 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Something isn't working as expected. 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Description** 11 | A short description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | - Platform: [e.g. iOS 17.3] 20 | - EventSource version: [e.g. 0.0.6] 21 | 22 | **Additional context** 23 | Add any other context about the problem here. 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | paths-ignore: 7 | - '**/README.md' 8 | - 'CONTRIBUTING.md' 9 | - 'CODE_OF_CONDUCT.md' 10 | pull_request: 11 | branches: [ "main" ] 12 | paths-ignore: 13 | - '**/README.md' 14 | - 'CONTRIBUTING.md' 15 | - 'CODE_OF_CONDUCT.md' 16 | 17 | 18 | jobs: 19 | macos-14: 20 | name: Build macOS 14 (Swift 5.10) 21 | runs-on: macos-14 22 | steps: 23 | - name: Checkout 24 | uses: actions/checkout@v4 25 | - name: Build 26 | run: swift build -v 27 | macos-15: 28 | name: Build macOS 15 (Swift 6.0) 29 | runs-on: macos-15 30 | steps: 31 | - name: Checkout 32 | uses: actions/checkout@v4 33 | - name: Build 34 | run: swift build -v 35 | - name: Run tests 36 | run: swift test -v 37 | ios-15: 38 | name: Build on iOS 15 39 | runs-on: macos-15 40 | steps: 41 | - name: Checkout 42 | uses: actions/checkout@v4 43 | - name: Create Downloads directory 44 | run: mkdir -p ~/Downloads 45 | - name: Restore cached iOS simulator runtime 46 | id: cache-restore 47 | uses: actions/cache@v4 48 | with: 49 | path: ~/Downloads 50 | key: ios-runtime-15.5-${{ runner.os }}-${{ hashFiles('**/ci.yml') }} 51 | restore-keys: | 52 | ios-runtime-15.5-${{ runner.os }}- 53 | ios-runtime-15.5- 54 | - name: Set up iOS 15 simulator runtime 55 | run: sudo xcodes runtimes install "iOS 15.5" --directory ~/Downloads --keep-archive 56 | - name: Build 57 | run: xcodebuild build -scheme EventSource -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 13 Pro,OS=15.5' 58 | - name: Run tests 59 | run: xcodebuild test -scheme EventSource -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 13 Pro,OS=15.5' 60 | ubuntu: 61 | name: Build Linux 62 | runs-on: ubuntu-latest 63 | container: 64 | image: swift:latest 65 | steps: 66 | - uses: actions/checkout@v4 67 | - name: Build 68 | run: swift build -v 69 | - name: Run tests 70 | run: swift test -v 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | xcuserdata/ 6 | DerivedData/ 7 | .swiftpm/config/registries.json 8 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 9 | .netrc 10 | Package.resolved 11 | .nova/ 12 | .vscode 13 | -------------------------------------------------------------------------------- /.swiftpm/xcode/package.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | https://recouse.me. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | ## Reporting Issues 4 | - Check existing issues before opening a new one. 5 | - Provide a clear and descriptive title. 6 | - Include steps to reproduce the issue, if applicable. 7 | 8 | ## Feature Requests 9 | - Before suggesting a new feature, discuss it in an issue first. 10 | - Clearly explain the feature and why it's needed. 11 | 12 | ## Pull Requests 13 | - Fork the repository and create a new branch for your changes. 14 | - Write clean, readable code that follows Swift best practices. 15 | - Include tests for any new functionality. 16 | - Keep commits concise and focused. 17 | - Ensure all tests pass before submitting your pull request. 18 | - Use meaningful commit messages. 19 | 20 | ## Code Style 21 | - Follow Swift's official [API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/). 22 | 23 | ## License 24 | - By contributing, you agree that your contributions will be licensed under the same license as the project. 25 | 26 | Thank you for contributing! Your help is greatly appreciated. 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2023 Firdavs Khaydarov 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 4 | associated documentation files (the “Software”), to deal in the Software without restriction, including 5 | without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 6 | copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the 7 | following conditions: 8 | 9 | The above copyright notice and this permission notice shall be included in all copies or substantial 10 | portions of the Software. 11 | 12 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 13 | LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 14 | NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 15 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 16 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 17 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.10 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "EventSource", 7 | platforms: [ 8 | .macOS(.v10_15), 9 | .iOS(.v13), 10 | .tvOS(.v13), 11 | .watchOS(.v6), 12 | .visionOS(.v1) 13 | ], 14 | products: [ 15 | .library( 16 | name: "EventSource", 17 | targets: ["EventSource"]), 18 | ], 19 | targets: [ 20 | .target( 21 | name: "EventSource", 22 | swiftSettings: [.enableExperimentalFeature("StrictConcurrency")]), 23 | .testTarget( 24 | name: "EventSourceTests", 25 | dependencies: ["EventSource"]), 26 | ] 27 | ) 28 | -------------------------------------------------------------------------------- /Package@swift-6.0.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 6.0 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "EventSource", 7 | platforms: [ 8 | .macOS(.v10_15), 9 | .iOS(.v13), 10 | .tvOS(.v13), 11 | .watchOS(.v6), 12 | .visionOS(.v1) 13 | ], 14 | products: [ 15 | .library( 16 | name: "EventSource", 17 | targets: ["EventSource"]), 18 | ], 19 | targets: [ 20 | .target( 21 | name: "EventSource"), 22 | .testTarget( 23 | name: "EventSourceTests", 24 | dependencies: ["EventSource"]), 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EventSource 2 | 3 | [![CI](https://github.com/Recouse/EventSource/actions/workflows/ci.yml/badge.svg)](https://github.com/Recouse/EventSource/actions/workflows/ci.yml) 4 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FRecouse%2FEventSource%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/Recouse/EventSource) 5 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FRecouse%2FEventSource%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/Recouse/EventSource) 6 | 7 | EventSource is a Swift package that provides a simple implementation of a client for [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html) (SSE). It allows you to easily receive real-time updates from a server over a persistent HTTP connection, using a simple and efficient interface. 8 | 9 | It also leverages Swift concurrency features to provide a more expressive and intuitive way to handle asynchronous operations. 10 | 11 | > [!Note] 12 | > Please note that this package was originally developed to be used in conjunction with another package, and as such, it may not cover all specification details. Please be aware of this limitation when evaluating whether EventSource is suitable for your specific use case. 13 | 14 | ## Features 15 | 16 | - [x] Simple Swift API for SSE 17 | - [x] Supports data-only mode 18 | - [x] Data race safety with Swift 6 19 | 20 | ## Installation 21 | 22 | The module name of the package is `EventSource`. Choose one of the instructions below to install and add the following import statement to your source code. 23 | 24 | ```swift 25 | import EventSource 26 | ``` 27 | 28 | #### [Xcode Package Dependency](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app) 29 | 30 | From Xcode menu: `File` > `Swift Packages` > `Add Package Dependency` 31 | 32 | ```text 33 | https://github.com/Recouse/EventSource 34 | ``` 35 | 36 | #### [Swift Package Manager](https://www.swift.org/documentation/package-manager/) 37 | 38 | In your `Package.swift` file, first add the following to the package `dependencies`: 39 | 40 | ```swift 41 | .package(url: "https://github.com/Recouse/EventSource.git"), 42 | ``` 43 | 44 | And then, include "EventSource" as a dependency for your target: 45 | 46 | ```swift 47 | .target(name: "", dependencies: [ 48 | .product(name: "EventSource", package: "EventSource"), 49 | ]), 50 | ``` 51 | 52 | ## Usage 53 | 54 | Using EventSource is easy. Simply create a new data task from an instance of EventSource with the URLRequest of the SSE endpoint you want to connect to, and await for events: 55 | ```swift 56 | import EventSource 57 | 58 | Task { 59 | let eventSource = EventSource() 60 | let dataTask = eventSource.dataTask(for: urlRequest) 61 | 62 | for await event in dataTask.events() { 63 | switch event { 64 | case .open: 65 | print("Connection was opened.") 66 | case .error(let error): 67 | print("Received an error:", error.localizedDescription) 68 | case .event(let event): 69 | print("Received an event", event.data ?? "") 70 | case .closed: 71 | print("Connection was closed.") 72 | } 73 | } 74 | } 75 | ``` 76 | 77 | Use `dataTask.cancel()` to explicitly close the connection. However, in that case `.closed` event won't be emitted. 78 | 79 | ### Data-only mode 80 | 81 | EventSource can be used in data-only mode, making it suitable for popular APIs like [OpenAI](https://platform.openai.com/docs/overview). Below is an example using OpenAI's [completions](https://platform.openai.com/docs/guides/text-generation) API: 82 | ```swift 83 | Task { 84 | var urlRequest = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!) 85 | urlRequest.allHTTPHeaderFields = [ 86 | "Content-Type": "application/json", 87 | "Authorization": "Bearer \(accessToken)" 88 | ] 89 | urlRequest.httpMethod = "POST" 90 | urlRequest.httpBody = """ 91 | { 92 | "model": "gpt-4o-mini", 93 | "messages": [ 94 | {"role": "user", "content": "Why is the sky blue?"} 95 | ], 96 | "stream": true 97 | } 98 | """.data(using: .utf8)! 99 | 100 | let eventSource = EventSource(mode: .dataOnly) 101 | let dataTask = eventSource.dataTask(for: urlRequest) 102 | 103 | var response: String = "" 104 | 105 | for await event in dataTask.events() { 106 | switch event { 107 | case .event(let event): 108 | if let data = eventDevent.data?.data(using: .utf8) { 109 | let chunk = try? JSONDecoder().decode(ChatCompletionChunk.self, from: data) 110 | let string = chunk?.choices.first?.delta.content ?? "" 111 | response += string 112 | } 113 | default: 114 | break 115 | } 116 | } 117 | 118 | print(response) 119 | } 120 | ``` 121 | 122 | ## Compatibility 123 | 124 | * macOS 10.15+ 125 | * iOS 13.0+ 126 | * tvOS 13.0+ 127 | * watchOS 6.0+ 128 | * visionOS 1.0+ 129 | 130 | ## Dependencies 131 | 132 | No dependencies. 133 | 134 | ## Contributing 135 | 136 | Contributions to are always welcomed! For more details see [CONTRIBUTING.md](CONTRIBUTING.md). 137 | 138 | ## Credits 139 | 140 | * Mutex backport from [swift-sharing](https://github.com/pointfreeco/swift-sharing) 141 | 142 | ## License 143 | 144 | EventSource is released under the MIT License. See [LICENSE](LICENSE) for more information. 145 | -------------------------------------------------------------------------------- /Sources/EventSource/EventParser.swift: -------------------------------------------------------------------------------- 1 | // 2 | // EventParser.swift 3 | // EventSource 4 | // 5 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 6 | // Licensed under the MIT License. 7 | // 8 | 9 | import Foundation 10 | 11 | public protocol EventParser: Sendable { 12 | mutating func parse(_ data: Data) -> [EVEvent] 13 | } 14 | 15 | /// ``ServerEventParser`` is used to parse text data into ``ServerEvent``. 16 | struct ServerEventParser: EventParser { 17 | private let mode: EventSource.Mode 18 | private var buffer = Data() 19 | 20 | init(mode: EventSource.Mode = .default) { 21 | self.mode = mode 22 | } 23 | 24 | static let lf: UInt8 = 0x0A 25 | static let colon: UInt8 = 0x3A 26 | 27 | mutating func parse(_ data: Data) -> [EVEvent] { 28 | let (separatedMessages, remainingData) = splitBuffer(for: buffer + data) 29 | buffer = remainingData 30 | return parseBuffer(for: separatedMessages) 31 | } 32 | 33 | private func parseBuffer(for rawMessages: [Data]) -> [EVEvent] { 34 | // Parse data to ServerMessage model 35 | let messages: [ServerEvent] = rawMessages.compactMap { ServerEvent.parse(from: $0, mode: mode) } 36 | 37 | return messages 38 | } 39 | 40 | private func splitBuffer(for data: Data) -> (completeData: [Data], remainingData: Data) { 41 | let separator: [UInt8] = [Self.lf, Self.lf] 42 | var rawMessages = [Data]() 43 | 44 | // If event separator is not present do not parse any unfinished messages 45 | guard let lastSeparator = data.lastRange(of: separator) else { return ([], data) } 46 | 47 | let bufferRange = data.startIndex.. [Data] { 67 | var chunks: [Data] = [] 68 | var pos = startIndex 69 | // Find next occurrence of separator after current position 70 | while let r = self[pos...].range(of: Data(separator)) { 71 | // Append if non-empty 72 | if r.lowerBound > pos { 73 | chunks.append(self[pos.. EventParser 44 | 45 | public var timeoutInterval: TimeInterval 46 | 47 | public init(mode: Mode = .default, timeoutInterval: TimeInterval = 300) { 48 | self.init(mode: mode, eventParser: ServerEventParser(mode: mode), timeoutInterval: timeoutInterval) 49 | } 50 | 51 | public init( 52 | mode: Mode = .default, 53 | eventParser: @autoclosure @escaping @Sendable () -> EventParser, 54 | timeoutInterval: TimeInterval = 300 55 | ) { 56 | self.mode = mode 57 | self.eventParser = eventParser 58 | self.timeoutInterval = timeoutInterval 59 | } 60 | 61 | public func dataTask(for urlRequest: URLRequest) -> DataTask { 62 | DataTask( 63 | urlRequest: urlRequest, 64 | eventParser: eventParser(), 65 | timeoutInterval: timeoutInterval 66 | ) 67 | } 68 | } 69 | 70 | public extension EventSource { 71 | /// An EventSource task that handles connecting to the URLRequest and creating an event stream. 72 | /// 73 | /// Creation of a task is exclusively handled by ``EventSource``. A new task can be created by calling 74 | /// ``EventSource/EventSource/dataTask(for:)`` method on the EventSource instance. After creating a task, 75 | /// it can be started by iterating event stream returned by ``DataTask/events()``. 76 | final class DataTask: Sendable { 77 | private let _readyState: Mutex = Mutex(.none) 78 | 79 | /// A value representing the state of the connection. 80 | public var readyState: ReadyState { 81 | get { 82 | _readyState.withLock { $0 } 83 | } 84 | set { 85 | _readyState.withLock { $0 = newValue } 86 | } 87 | } 88 | 89 | private let _lastMessageId: Mutex = Mutex("") 90 | 91 | /// Last event's ID string value. 92 | /// 93 | /// Sent in a HTTP request header and used when a user is to reestablish the connection. 94 | public var lastMessageId: String { 95 | get { 96 | _lastMessageId.withLock { $0 } 97 | } 98 | set { 99 | _lastMessageId.withLock { $0 = newValue } 100 | } 101 | } 102 | 103 | /// A URLRequest of the events source. 104 | public let urlRequest: URLRequest 105 | 106 | private let _eventParser: Mutex 107 | 108 | private var eventParser: EventParser { 109 | get { 110 | _eventParser.withLock { $0 } 111 | } 112 | set { 113 | _eventParser.withLock { $0 = newValue } 114 | } 115 | } 116 | 117 | private let timeoutInterval: TimeInterval 118 | 119 | private let _httpResponseErrorStatusCode: Mutex = Mutex(nil) 120 | 121 | private var httpResponseErrorStatusCode: Int? { 122 | get { 123 | _httpResponseErrorStatusCode.withLock { $0 } 124 | } 125 | set { 126 | _httpResponseErrorStatusCode.withLock { $0 = newValue } 127 | } 128 | } 129 | 130 | private let _consumed: Mutex = Mutex(false) 131 | 132 | private var consumed: Bool { 133 | get { 134 | _consumed.withLock { $0 } 135 | } 136 | set { 137 | _consumed.withLock { $0 = newValue } 138 | } 139 | } 140 | 141 | private var urlSessionConfiguration: URLSessionConfiguration { 142 | let configuration = URLSessionConfiguration.default 143 | configuration.httpAdditionalHeaders = [ 144 | HTTPHeaderField.accept: Accept.eventStream, 145 | HTTPHeaderField.cacheControl: CacheControl.noStore, 146 | HTTPHeaderField.lastEventID: lastMessageId 147 | ] 148 | configuration.timeoutIntervalForRequest = self.timeoutInterval 149 | configuration.timeoutIntervalForResource = self.timeoutInterval 150 | return configuration 151 | } 152 | 153 | internal init( 154 | urlRequest: URLRequest, 155 | eventParser: EventParser, 156 | timeoutInterval: TimeInterval 157 | ) { 158 | self.urlRequest = urlRequest 159 | self._eventParser = Mutex(eventParser) 160 | self.timeoutInterval = timeoutInterval 161 | } 162 | 163 | /// Creates and returns event stream. 164 | public func events() -> AsyncStream { 165 | if consumed { 166 | return AsyncStream { continuation in 167 | continuation.yield(.error(EventSourceError.alreadyConsumed)) 168 | continuation.finish() 169 | } 170 | } 171 | 172 | return AsyncStream { continuation in 173 | let sessionDelegate = SessionDelegate() 174 | let urlSession = URLSession( 175 | configuration: urlSessionConfiguration, 176 | delegate: sessionDelegate, 177 | delegateQueue: nil 178 | ) 179 | let urlSessionDataTask = urlSession.dataTask(with: urlRequest) 180 | 181 | let sessionDelegateTask = Task { [weak self] in 182 | for await event in sessionDelegate.eventStream { 183 | guard let self else { return } 184 | 185 | switch event { 186 | case let .didCompleteWithError(error): 187 | handleSessionError(error, stream: continuation, urlSession: urlSession) 188 | case let .didReceiveResponse(response, completionHandler): 189 | handleSessionResponse( 190 | response, 191 | stream: continuation, 192 | urlSession: urlSession, 193 | completionHandler: completionHandler 194 | ) 195 | case let .didReceiveData(data): 196 | parseMessages(from: data, stream: continuation, urlSession: urlSession) 197 | } 198 | } 199 | } 200 | 201 | #if compiler(>=6.0) 202 | continuation.onTermination = { @Sendable [weak self] _ in 203 | sessionDelegateTask.cancel() 204 | Task { self?.close(stream: continuation, urlSession: urlSession) } 205 | } 206 | #else 207 | continuation.onTermination = { @Sendable _ in 208 | sessionDelegateTask.cancel() 209 | Task { [weak self] in 210 | await self?.close(stream: continuation, urlSession: urlSession) 211 | } 212 | } 213 | #endif 214 | 215 | urlSessionDataTask.resume() 216 | readyState = .connecting 217 | consumed = true 218 | } 219 | } 220 | 221 | private func handleSessionError( 222 | _ error: Error?, 223 | stream continuation: AsyncStream.Continuation, 224 | urlSession: URLSession 225 | ) { 226 | guard readyState != .closed else { 227 | close(stream: continuation, urlSession: urlSession) 228 | return 229 | } 230 | 231 | // Send error event 232 | if let error { 233 | sendErrorEvent(with: error, stream: continuation) 234 | } 235 | 236 | // Close connection 237 | close(stream: continuation, urlSession: urlSession) 238 | } 239 | 240 | private func handleSessionResponse( 241 | _ response: URLResponse, 242 | stream continuation: AsyncStream.Continuation, 243 | urlSession: URLSession, 244 | completionHandler: @escaping (URLSession.ResponseDisposition) -> Void 245 | ) { 246 | guard readyState != .closed else { 247 | completionHandler(.cancel) 248 | return 249 | } 250 | 251 | guard let httpResponse = response as? HTTPURLResponse else { 252 | completionHandler(.cancel) 253 | return 254 | } 255 | 256 | // Stop connection when 204 response code, otherwise keep open 257 | guard httpResponse.statusCode != 204 else { 258 | completionHandler(.cancel) 259 | close(stream: continuation, urlSession: urlSession) 260 | return 261 | } 262 | 263 | if 200...299 ~= httpResponse.statusCode { 264 | if readyState != .open { 265 | setOpen(stream: continuation) 266 | } 267 | } else { 268 | httpResponseErrorStatusCode = httpResponse.statusCode 269 | } 270 | 271 | completionHandler(.allow) 272 | } 273 | 274 | /// Closes the connection, if one was made, 275 | /// and sets the `readyState` property to `.closed`. 276 | /// - Returns: State before closing. 277 | private func close(stream continuation: AsyncStream.Continuation, urlSession: URLSession) { 278 | let previousState = self.readyState 279 | if previousState != .closed { 280 | continuation.yield(.closed) 281 | continuation.finish() 282 | } 283 | cancel(urlSession: urlSession) 284 | } 285 | 286 | private func parseMessages( 287 | from data: Data, 288 | stream continuation: AsyncStream.Continuation, 289 | urlSession: URLSession 290 | ) { 291 | if let httpResponseErrorStatusCode { 292 | self.httpResponseErrorStatusCode = nil 293 | handleSessionError( 294 | EventSourceError.connectionError(statusCode: httpResponseErrorStatusCode, response: data), 295 | stream: continuation, 296 | urlSession: urlSession 297 | ) 298 | return 299 | } 300 | 301 | let events = eventParser.parse(data) 302 | 303 | // Update last message ID 304 | if let lastMessageWithId = events.last(where: { $0.id != nil }) { 305 | lastMessageId = lastMessageWithId.id ?? "" 306 | } 307 | 308 | events.forEach { 309 | continuation.yield(.event($0)) 310 | } 311 | } 312 | 313 | private func setOpen(stream continuation: AsyncStream.Continuation) { 314 | readyState = .open 315 | continuation.yield(.open) 316 | } 317 | 318 | private func sendErrorEvent(with error: Error, stream continuation: AsyncStream.Continuation) { 319 | continuation.yield(.error(error)) 320 | } 321 | 322 | /// Cancels the task. 323 | /// 324 | /// ## Notes: 325 | /// The event stream supports cooperative task cancellation. However, it should be noted that 326 | /// canceling the parent Task only cancels the underlying `URLSessionDataTask` of 327 | /// ``EventSource/EventSource/DataTask``; this does not actually stop the ongoing request. 328 | public func cancel(urlSession: URLSession) { 329 | readyState = .closed 330 | lastMessageId = "" 331 | urlSession.invalidateAndCancel() 332 | } 333 | } 334 | } 335 | -------------------------------------------------------------------------------- /Sources/EventSource/EventSourceError.swift: -------------------------------------------------------------------------------- 1 | // 2 | // EventSourceError.swift 3 | // EventSource 4 | // 5 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 6 | // Licensed under the MIT License. 7 | // 8 | 9 | import Foundation 10 | 11 | public enum EventSourceError: LocalizedError { 12 | case undefinedConnectionError 13 | 14 | case connectionError(statusCode: Int, response: Data) 15 | 16 | /// The ``EventSource/EventSource/DataTask`` event stream is already being consumed by another task. 17 | /// A stream can only be consumed by one task at a time. 18 | case alreadyConsumed 19 | 20 | public var errorDescription: String? { 21 | switch self { 22 | case .alreadyConsumed: 23 | "The `DataTask` events stream is already being consumed by another task." 24 | default: 25 | nil 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Sources/EventSource/Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Extensions.swift 3 | // EventSource 4 | // 5 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 6 | // Licensed under the MIT License. 7 | // 8 | 9 | extension Sequence { 10 | func asyncForEach( 11 | _ operation: (Element) async throws -> Void 12 | ) async rethrows { 13 | for element in self { 14 | try await operation(element) 15 | } 16 | } 17 | } 18 | 19 | extension Task where Success == Never, Failure == Never { 20 | static func sleep(duration: Double) async throws { 21 | try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000)) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Sources/EventSource/Headers.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Headers.swift 3 | // EventSource 4 | // 5 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 6 | // Licensed under the MIT License. 7 | // 8 | 9 | enum HTTPHeaderField { 10 | static let lastEventID = "Last-Event-ID" 11 | static let accept = "Accept" 12 | static let cacheControl = "Cache-Control" 13 | } 14 | 15 | struct Accept { 16 | static let eventStream = "text/event-stream" 17 | } 18 | 19 | struct CacheControl { 20 | static let noStore = "no-store" 21 | } 22 | -------------------------------------------------------------------------------- /Sources/EventSource/Mutex.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Mutex.swift 3 | // EventSource 4 | // 5 | // Created by Firdavs Khaydarov on 12/03/2025. 6 | // 7 | 8 | import Foundation 9 | 10 | #if compiler(>=6) 11 | /// A synchronization primitive that protects shared mutable state via mutual exclusion. 12 | /// 13 | /// A back-port of Swift's `Mutex` type for wider platform availability. 14 | #if hasFeature(StaticExclusiveOnly) 15 | @_staticExclusiveOnly 16 | #endif 17 | package struct Mutex: ~Copyable { 18 | private let _lock = NSLock() 19 | private let _box: Box 20 | 21 | /// Initializes a value of this mutex with the given initial state. 22 | /// 23 | /// - Parameter initialValue: The initial value to give to the mutex. 24 | package init(_ initialValue: consuming sending Value) { 25 | _box = Box(initialValue) 26 | } 27 | 28 | private final class Box { 29 | var value: Value 30 | init(_ initialValue: consuming sending Value) { 31 | value = initialValue 32 | } 33 | } 34 | } 35 | 36 | extension Mutex: @unchecked Sendable where Value: ~Copyable {} 37 | 38 | extension Mutex where Value: ~Copyable { 39 | /// Calls the given closure after acquiring the lock and then releases ownership. 40 | borrowing package func withLock( 41 | _ body: (inout sending Value) throws(E) -> sending Result 42 | ) throws(E) -> sending Result { 43 | _lock.lock() 44 | defer { _lock.unlock() } 45 | return try body(&_box.value) 46 | } 47 | 48 | /// Attempts to acquire the lock and then calls the given closure if successful. 49 | borrowing package func withLockIfAvailable( 50 | _ body: (inout sending Value) throws(E) -> sending Result 51 | ) throws(E) -> sending Result? { 52 | guard _lock.try() else { return nil } 53 | defer { _lock.unlock() } 54 | return try body(&_box.value) 55 | } 56 | } 57 | #else 58 | package struct Mutex { 59 | private let _lock = NSLock() 60 | private let _box: Box 61 | 62 | package init(_ initialValue: consuming Value) { 63 | _box = Box(initialValue) 64 | } 65 | 66 | private final class Box { 67 | var value: Value 68 | init(_ initialValue: consuming Value) { 69 | value = initialValue 70 | } 71 | } 72 | } 73 | 74 | extension Mutex: @unchecked Sendable {} 75 | 76 | extension Mutex { 77 | borrowing package func withLock( 78 | _ body: (inout Value) throws -> Result 79 | ) rethrows -> Result { 80 | _lock.lock() 81 | defer { _lock.unlock() } 82 | return try body(&_box.value) 83 | } 84 | 85 | borrowing package func withLockIfAvailable( 86 | _ body: (inout Value) throws -> Result 87 | ) rethrows -> Result? { 88 | guard _lock.try() else { return nil } 89 | defer { _lock.unlock() } 90 | return try body(&_box.value) 91 | } 92 | } 93 | #endif 94 | 95 | extension Mutex where Value == Void { 96 | borrowing package func _unsafeLock() { 97 | _lock.lock() 98 | } 99 | 100 | borrowing package func _unsafeTryLock() -> Bool { 101 | _lock.try() 102 | } 103 | 104 | borrowing package func _unsafeUnlock() { 105 | _lock.unlock() 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /Sources/EventSource/ServerEvent.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ServerEvent.swift 3 | // EventSource 4 | // 5 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 6 | // Licensed under the MIT License. 7 | // 8 | 9 | import Foundation 10 | 11 | /// Protocol for defining a basic event structure. It is used by the ``EventParser`` 12 | /// and should be implemented as a custom type when a custom ``EventParser`` is required. 13 | public protocol EVEvent: Sendable { 14 | var id: String? { get } 15 | var event: String? { get } 16 | var data: String? { get } 17 | var other: [String: String]? { get } 18 | var time: String? { get } 19 | } 20 | 21 | public extension EVEvent { 22 | /// Checks if all event fields are empty. 23 | var isEmpty: Bool { 24 | if let id, !id.isEmpty { 25 | return false 26 | } 27 | 28 | if let event, !event.isEmpty { 29 | return false 30 | } 31 | 32 | if let data, !data.isEmpty { 33 | return false 34 | } 35 | 36 | if let other, !other.isEmpty { 37 | return false 38 | } 39 | 40 | if let time, !time.isEmpty { 41 | return false 42 | } 43 | 44 | return true 45 | } 46 | } 47 | 48 | /// Default implementation of ``EventSourceEvent`` used in the package. 49 | public struct ServerEvent: EVEvent { 50 | public var id: String? 51 | public var event: String? 52 | public var data: String? 53 | public var other: [String: String]? 54 | public var time: String? 55 | 56 | init( 57 | id: String? = nil, 58 | event: String? = nil, 59 | data: String? = nil, 60 | other: [String: String]? = nil, 61 | time: String? = nil 62 | ) { 63 | self.id = id 64 | self.event = event 65 | self.data = data 66 | self.other = other 67 | self.time = time 68 | } 69 | 70 | public static func parse(from data: Data, mode: EventSource.Mode = .default) -> ServerEvent? { 71 | let rows: [Data] = switch mode { 72 | case .default: 73 | data.split(separator: ServerEventParser.lf) // Separate event fields 74 | case .dataOnly: 75 | [data] // Do not split data in data-only mode 76 | } 77 | 78 | var message = ServerEvent() 79 | 80 | for row in rows { 81 | // Skip the line if it is empty or it starts with a colon character 82 | if row.isEmpty || row.first == ServerEventParser.colon { 83 | continue 84 | } 85 | 86 | let keyValue = row.split(separator: ServerEventParser.colon, maxSplits: 1) 87 | let key = keyValue[0].utf8String 88 | 89 | // If value starts with a SPACE character, remove it from value 90 | let valueString = keyValue[safe: 1]?.utf8String 91 | let value = if let valueString, valueString.hasPrefix(" ") { 92 | String(valueString.dropFirst()) 93 | } else { 94 | valueString 95 | } 96 | 97 | switch key { 98 | case "id": 99 | message.id = value 100 | case "event": 101 | message.event = value 102 | case "data": 103 | if let existingData = message.data { 104 | message.data = existingData + "\n" + (value ?? "") 105 | } else { 106 | message.data = value 107 | } 108 | case "time": 109 | message.time = value 110 | default: 111 | // If the line is not empty but does not contain a colon character 112 | // add it to the other fields using the whole line as the field name, 113 | // and the empty string as the field value. 114 | if row.contains(ServerEventParser.colon) == false { 115 | let string = row.utf8String 116 | if var other = message.other { 117 | other[string] = "" 118 | message.other = other 119 | } else { 120 | message.other = [string: ""] 121 | } 122 | } 123 | } 124 | } 125 | 126 | if message.isEmpty { 127 | return nil 128 | } 129 | 130 | return message 131 | } 132 | } 133 | 134 | fileprivate extension Data { 135 | var utf8String: String { 136 | String(decoding: self, as: UTF8.self) 137 | } 138 | } 139 | 140 | package extension Array { 141 | subscript(safe index: Int) -> Element? { 142 | guard index >= 0, index < endIndex else { 143 | return nil 144 | } 145 | return self[index] 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Sources/EventSource/SessionDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SessionDelegate.swift 3 | // EventSource 4 | // 5 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 6 | // Licensed under the MIT License. 7 | // 8 | 9 | import Foundation 10 | #if canImport(FoundationNetworking) 11 | import FoundationNetworking 12 | #endif 13 | 14 | final class SessionDelegate: NSObject, URLSessionDataDelegate { 15 | enum Event: Sendable { 16 | case didCompleteWithError(Error?) 17 | case didReceiveResponse(URLResponse, @Sendable (URLSession.ResponseDisposition) -> Void) 18 | case didReceiveData(Data) 19 | } 20 | 21 | private let internalStream = AsyncStream.makeStream() 22 | 23 | var eventStream: AsyncStream { internalStream.stream } 24 | 25 | func urlSession( 26 | _ session: URLSession, 27 | task: URLSessionTask, 28 | didCompleteWithError error: Error? 29 | ) { 30 | internalStream.continuation.yield(.didCompleteWithError(error)) 31 | } 32 | 33 | func urlSession( 34 | _ session: URLSession, 35 | dataTask: URLSessionDataTask, 36 | didReceive response: URLResponse, 37 | completionHandler: @Sendable @escaping (URLSession.ResponseDisposition) -> Void 38 | ) { 39 | internalStream.continuation.yield(.didReceiveResponse(response, completionHandler)) 40 | } 41 | 42 | func urlSession( 43 | _ session: URLSession, 44 | dataTask: URLSessionDataTask, 45 | didReceive data: Data 46 | ) { 47 | internalStream.continuation.yield(.didReceiveData(data)) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Tests/EventSourceTests/EventParserTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright © 2023 Firdavs Khaydarov (Recouse). All rights reserved. 3 | // Licensed under the MIT License. 4 | // 5 | 6 | import Foundation 7 | import Testing 8 | @testable import EventSource 9 | 10 | struct EventParserTests { 11 | @Test func eventParsing() async throws { 12 | var parser = ServerEventParser() 13 | 14 | let text = """ 15 | data: test 1 16 | 17 | data: test 2 18 | data: continued 19 | 20 | event: add 21 | data: test 3 22 | 23 | event: remove 24 | data: test 4 25 | 26 | id: 5 27 | event: ping 28 | data: test 5 29 | 30 | 31 | """ 32 | let data = Data(text.utf8) 33 | 34 | let events = parser.parse(data) 35 | 36 | #expect(events.count == 5) 37 | 38 | let event0Data = try #require(events[safe: 0]?.data) 39 | #expect(event0Data == "test 1") 40 | 41 | let event1Data = try #require(events[safe: 1]?.data) 42 | #expect(event1Data == "test 2\ncontinued") 43 | 44 | let event2Event = try #require(events[safe: 2]?.event) 45 | let event2Data = try #require(events[safe: 2]?.data) 46 | #expect(event2Event == "add") 47 | #expect(event2Data == "test 3") 48 | 49 | let event3Event = try #require(events[safe: 3]?.event) 50 | let event3Data = try #require(events[safe: 3]?.data) 51 | #expect(event3Event == "remove") 52 | #expect(event3Data == "test 4") 53 | 54 | let event4ID = try #require(events[safe: 4]?.id) 55 | let event4Event = try #require(events[safe: 4]?.event) 56 | let event4Data = try #require(events[safe: 4]?.data) 57 | #expect(event4ID == "5") 58 | #expect(event4Event == "ping") 59 | #expect(event4Data == "test 5") 60 | } 61 | 62 | @Test func emptyData() async { 63 | var parser = ServerEventParser() 64 | 65 | let text = """ 66 | 67 | 68 | """ 69 | let data = Data(text.utf8) 70 | 71 | let events = parser.parse(data) 72 | 73 | #expect(events.isEmpty) 74 | } 75 | 76 | @Test func otherEventFormats() async throws { 77 | var parser = ServerEventParser() 78 | 79 | let text = """ 80 | data : test 1 81 | 82 | id : 2 83 | data : test 2 84 | 85 | event : add 86 | data : test 3 87 | 88 | id : 4 89 | event : ping 90 | data : test 4 91 | 92 | test 5 93 | 94 | message 6 95 | message 6-1 96 | 97 | : 98 | 99 | """ 100 | let data = Data(text.utf8) 101 | 102 | let events = parser.parse(data) 103 | 104 | // Due to extra spaces in the field names, the first four events failed to be interpreted correctly; 105 | // therefore, only two events should be parsed 106 | #expect(events.count == 2) 107 | 108 | let event1Other = try #require(events[safe: 0]?.other?["test 5"]) 109 | #expect(event1Other == "") 110 | 111 | let event2Other1 = try #require(events[safe: 1]?.other?["message 6"]) 112 | let event2Other2 = try #require(events[safe: 1]?.other?["message 6-1"]) 113 | #expect(event2Other1 == "") 114 | #expect(event2Other2 == "") 115 | } 116 | 117 | @Test func dataOnlyMode() async throws { 118 | var parser = ServerEventParser(mode: .dataOnly) 119 | let jsonDecoder = JSONDecoder() 120 | 121 | let text = """ 122 | data: {"id":"abcd-1","type":"message","content":"\\ntest\\n"} 123 | 124 | data: {"id":"abcd-2","type":"message","content":"\\n\\n"} 125 | 126 | 127 | """ 128 | let data = Data(text.utf8) 129 | 130 | let events = parser.parse(data) 131 | 132 | let data1 = Data(try #require(events[0].data?.utf8)) 133 | let data2 = Data(try #require(events[1].data?.utf8)) 134 | 135 | let model1 = try jsonDecoder.decode(TestModel.self, from: data1) 136 | let model2 = try jsonDecoder.decode(TestModel.self, from: data2) 137 | 138 | #expect(model1.content == "\ntest\n") 139 | #expect(model2.content == "\n\n") 140 | } 141 | 142 | @Test func parseNotCompleteEvent() async throws { 143 | var parser = ServerEventParser() 144 | 145 | let text = """ 146 | data: test 1 147 | """ 148 | let data = Data(text.utf8) 149 | 150 | let events = parser.parse(data) 151 | 152 | #expect(events.isEmpty) 153 | } 154 | 155 | @Test func parseSeparatedEvent() async throws { 156 | var parser = ServerEventParser() 157 | 158 | let textPart1 = """ 159 | event: add 160 | 161 | """ 162 | let dataPart1 = Data(textPart1.utf8) 163 | let textPart2 = """ 164 | data: test 1 165 | 166 | 167 | """ 168 | let dataPart2 = Data(textPart2.utf8) 169 | 170 | let _ = parser.parse(dataPart1) 171 | let events = parser.parse(dataPart2) 172 | 173 | #expect(events.count == 1) 174 | 175 | let event = try #require(events.first?.event) 176 | let eventData = try #require(events.first?.data) 177 | #expect(event == "add") 178 | #expect(eventData == "test 1") 179 | } 180 | } 181 | 182 | fileprivate extension EventParserTests { 183 | struct TestModel: Decodable { 184 | let id: String 185 | let type: String 186 | let content: String 187 | } 188 | } 189 | --------------------------------------------------------------------------------