|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the APNSwift open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2024 the APNSwift project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of APNSwift project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import APNSCore |
| 16 | +import AsyncHTTPClient |
| 17 | +import struct Foundation.Date |
| 18 | +import struct Foundation.UUID |
| 19 | +import NIOConcurrencyHelpers |
| 20 | +import NIOCore |
| 21 | +import NIOHTTP1 |
| 22 | +import NIOSSL |
| 23 | +import NIOTLS |
| 24 | +import NIOPosix |
| 25 | + |
| 26 | +/// A client for managing Apple Push Notification broadcast channels. |
| 27 | +public final class APNSBroadcastClient<Decoder: APNSJSONDecoder & Sendable, Encoder: APNSJSONEncoder & Sendable>: APNSBroadcastClientProtocol { |
| 28 | + |
| 29 | + /// The broadcast environment to use. |
| 30 | + private let environment: APNSBroadcastEnvironment |
| 31 | + |
| 32 | + /// The ``HTTPClient`` used by the APNS broadcast client. |
| 33 | + private let httpClient: HTTPClient |
| 34 | + |
| 35 | + /// The decoder for the responses from APNs. |
| 36 | + private let responseDecoder: Decoder |
| 37 | + |
| 38 | + /// The encoder for the requests to APNs. |
| 39 | + @usableFromInline |
| 40 | + /* private */ internal let requestEncoder: Encoder |
| 41 | + |
| 42 | + /// The authentication token manager. |
| 43 | + private let authenticationTokenManager: APNSAuthenticationTokenManager<ContinuousClock>? |
| 44 | + |
| 45 | + /// The ByteBufferAllocator |
| 46 | + @usableFromInline |
| 47 | + /* private */ internal let byteBufferAllocator: ByteBufferAllocator |
| 48 | + |
| 49 | + /// Default ``HTTPHeaders`` which will be adapted for each request. This saves some allocations. |
| 50 | + private let defaultRequestHeaders: HTTPHeaders = { |
| 51 | + var headers = HTTPHeaders() |
| 52 | + headers.reserveCapacity(10) |
| 53 | + headers.add(name: "content-type", value: "application/json") |
| 54 | + headers.add(name: "user-agent", value: "APNS/swift-nio") |
| 55 | + return headers |
| 56 | + }() |
| 57 | + |
| 58 | + /// Initializes a new APNSBroadcastClient. |
| 59 | + /// |
| 60 | + /// The client will create an internal ``HTTPClient`` which is used to make requests to APNs broadcast API. |
| 61 | + /// |
| 62 | + /// - Parameters: |
| 63 | + /// - authenticationMethod: The authentication method to use. |
| 64 | + /// - environment: The broadcast environment (production or sandbox). |
| 65 | + /// - eventLoopGroupProvider: Specify how EventLoopGroup will be created. |
| 66 | + /// - responseDecoder: The decoder for the responses from APNs. |
| 67 | + /// - requestEncoder: The encoder for the requests to APNs. |
| 68 | + /// - byteBufferAllocator: The `ByteBufferAllocator`. |
| 69 | + public init( |
| 70 | + authenticationMethod: APNSClientConfiguration.AuthenticationMethod, |
| 71 | + environment: APNSBroadcastEnvironment, |
| 72 | + eventLoopGroupProvider: NIOEventLoopGroupProvider, |
| 73 | + responseDecoder: Decoder, |
| 74 | + requestEncoder: Encoder, |
| 75 | + byteBufferAllocator: ByteBufferAllocator = .init() |
| 76 | + ) { |
| 77 | + self.environment = environment |
| 78 | + self.byteBufferAllocator = byteBufferAllocator |
| 79 | + self.responseDecoder = responseDecoder |
| 80 | + self.requestEncoder = requestEncoder |
| 81 | + |
| 82 | + var tlsConfiguration = TLSConfiguration.makeClientConfiguration() |
| 83 | + switch authenticationMethod.method { |
| 84 | + case .jwt(let privateKey, let teamIdentifier, let keyIdentifier): |
| 85 | + self.authenticationTokenManager = APNSAuthenticationTokenManager( |
| 86 | + privateKey: privateKey, |
| 87 | + teamIdentifier: teamIdentifier, |
| 88 | + keyIdentifier: keyIdentifier, |
| 89 | + clock: ContinuousClock() |
| 90 | + ) |
| 91 | + case .tls(let privateKey, let certificateChain): |
| 92 | + self.authenticationTokenManager = nil |
| 93 | + tlsConfiguration.privateKey = privateKey |
| 94 | + tlsConfiguration.certificateChain = certificateChain |
| 95 | + } |
| 96 | + |
| 97 | + var httpClientConfiguration = HTTPClient.Configuration() |
| 98 | + httpClientConfiguration.tlsConfiguration = tlsConfiguration |
| 99 | + httpClientConfiguration.httpVersion = .automatic |
| 100 | + |
| 101 | + switch eventLoopGroupProvider { |
| 102 | + case .shared(let eventLoopGroup): |
| 103 | + self.httpClient = HTTPClient( |
| 104 | + eventLoopGroupProvider: .shared(eventLoopGroup), |
| 105 | + configuration: httpClientConfiguration |
| 106 | + ) |
| 107 | + case .createNew: |
| 108 | + self.httpClient = HTTPClient( |
| 109 | + configuration: httpClientConfiguration |
| 110 | + ) |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /// Shuts down the client gracefully. |
| 115 | + public func shutdown() async throws { |
| 116 | + try await self.httpClient.shutdown() |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +extension APNSBroadcastClient: Sendable where Decoder: Sendable, Encoder: Sendable {} |
| 121 | + |
| 122 | +// MARK: - Broadcast operations |
| 123 | + |
| 124 | +extension APNSBroadcastClient { |
| 125 | + |
| 126 | + public func send<Message: Encodable & Sendable, ResponseBody: Decodable & Sendable>( |
| 127 | + _ request: APNSBroadcastRequest<Message> |
| 128 | + ) async throws -> APNSBroadcastResponse<ResponseBody> { |
| 129 | + var headers = self.defaultRequestHeaders |
| 130 | + |
| 131 | + // Add request ID if present |
| 132 | + if let apnsRequestID = request.apnsRequestID { |
| 133 | + headers.add(name: "apns-request-id", value: apnsRequestID.uuidString.lowercased()) |
| 134 | + } |
| 135 | + |
| 136 | + // Authorization token |
| 137 | + if let authenticationTokenManager = self.authenticationTokenManager { |
| 138 | + let token = try await authenticationTokenManager.nextValidToken |
| 139 | + headers.add(name: "authorization", value: token) |
| 140 | + } |
| 141 | + |
| 142 | + // Build the request URL |
| 143 | + let requestURL = "\(self.environment.url):\(self.environment.port)\(request.operation.path)" |
| 144 | + |
| 145 | + // Create HTTP request |
| 146 | + var httpClientRequest = HTTPClientRequest(url: requestURL) |
| 147 | + httpClientRequest.method = HTTPMethod(rawValue: request.operation.httpMethod) |
| 148 | + httpClientRequest.headers = headers |
| 149 | + |
| 150 | + // Add body for operations that require it (e.g., create) |
| 151 | + if let message = request.message { |
| 152 | + var byteBuffer = self.byteBufferAllocator.buffer(capacity: 0) |
| 153 | + try self.requestEncoder.encode(message, into: &byteBuffer) |
| 154 | + httpClientRequest.body = .bytes(byteBuffer) |
| 155 | + } |
| 156 | + |
| 157 | + // Execute the request |
| 158 | + let response = try await self.httpClient.execute(httpClientRequest, deadline: .distantFuture) |
| 159 | + |
| 160 | + // Extract request ID from response |
| 161 | + let apnsRequestID = response.headers.first(name: "apns-request-id").flatMap { UUID(uuidString: $0) } |
| 162 | + |
| 163 | + // Handle successful responses |
| 164 | + if response.status == .ok || response.status == .created { |
| 165 | + let body = try await response.body.collect(upTo: 1024 * 1024) // 1MB max |
| 166 | + let responseBody = try responseDecoder.decode(ResponseBody.self, from: body) |
| 167 | + return APNSBroadcastResponse(apnsRequestID: apnsRequestID, body: responseBody) |
| 168 | + } |
| 169 | + |
| 170 | + // Handle error responses |
| 171 | + let body = try await response.body.collect(upTo: 1024) |
| 172 | + let errorResponse = try responseDecoder.decode(APNSErrorResponse.self, from: body) |
| 173 | + |
| 174 | + let error = APNSError( |
| 175 | + responseStatus: Int(response.status.code), |
| 176 | + apnsID: nil, |
| 177 | + apnsUniqueID: nil, |
| 178 | + apnsResponse: errorResponse, |
| 179 | + timestamp: errorResponse.timestampInSeconds.flatMap { Date(timeIntervalSince1970: $0) } |
| 180 | + ) |
| 181 | + |
| 182 | + throw error |
| 183 | + } |
| 184 | +} |
0 commit comments