@zapiack/react-native 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Zapiack Realtime: live messages over one WebSocket.
3
+ *
4
+ * Your server mints a short-lived token with its API key (`POST /v1/realtime/tokens`) and hands it to the client, so the API key never
5
+ * reaches a browser or an app. The client asks for a token every time it connects, so a token that expires is simply replaced.
6
+ *
7
+ * It reconnects by itself with a growing, jittered pause, re-joins every channel and asks for what it missed since the last persisted
8
+ * message it saw, so a lost signal costs no messages. Nothing here touches push, so it works in any JavaScript runtime that has a
9
+ * WebSocket: browsers, React Native, Node 22+.
10
+ */
11
+ type RealtimeState = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed';
12
+ interface RealtimeMessage<T = unknown> {
13
+ msgId: string;
14
+ ts: number;
15
+ channel: string;
16
+ event: string;
17
+ data: T;
18
+ /** The user id (or connection id) of the sender. */
19
+ from: string | null;
20
+ /** True when it was sent while this client was away and is being replayed. */
21
+ replayed?: boolean;
22
+ }
23
+ interface PresenceMember {
24
+ connId: string;
25
+ user: string | null;
26
+ data: unknown;
27
+ at: number;
28
+ }
29
+ interface PublishOptions {
30
+ /** The name of the event. Default `message`. */
31
+ event?: string;
32
+ /** Keep it in the channel's history, so clients that were away can replay it. Default false. */
33
+ persist?: boolean;
34
+ /** Wait for the server to confirm. Default true. Pass false to fire and forget. */
35
+ ack?: boolean;
36
+ }
37
+ interface PublishResult {
38
+ msgId: string;
39
+ /** How many connections were subscribed when it was sent. */
40
+ delivered: number;
41
+ }
42
+ declare class ZapiackRealtimeError extends Error {
43
+ /** The server's code: 401 token, 403 not allowed, 413 too large, 429 slow down, 503 try again. 0 for a problem on this side. */
44
+ readonly code: number;
45
+ /** For a failed request (`request()`): the service's own word for it: `forbidden`, `invalid`, `no_route`, `timeout`, `rate_limited` or `internal`. */
46
+ readonly reason?: string | undefined;
47
+ constructor(message: string,
48
+ /** The server's code: 401 token, 403 not allowed, 413 too large, 429 slow down, 503 try again. 0 for a problem on this side. */
49
+ code?: number,
50
+ /** For a failed request (`request()`): the service's own word for it: `forbidden`, `invalid`, `no_route`, `timeout`, `rate_limited` or `internal`. */
51
+ reason?: string | undefined);
52
+ }
53
+ interface SocketLike {
54
+ readyState: number;
55
+ send(data: string): void;
56
+ close(code?: number, reason?: string): void;
57
+ onopen: ((ev?: unknown) => void) | null;
58
+ onmessage: ((ev: {
59
+ data: unknown;
60
+ }) => void) | null;
61
+ onclose: ((ev: {
62
+ code: number;
63
+ }) => void) | null;
64
+ onerror: ((ev?: unknown) => void) | null;
65
+ }
66
+ interface RealtimeEnv {
67
+ socket(url: string): SocketLike;
68
+ setTimeout(fn: () => void, ms: number): unknown;
69
+ clearTimeout(id: unknown): void;
70
+ setInterval(fn: () => void, ms: number): unknown;
71
+ clearInterval(id: unknown): void;
72
+ random(): number;
73
+ }
74
+ interface RealtimeOptions {
75
+ /** Returns a fresh token from your server. Called on every connect, so an expired token is replaced. */
76
+ getToken: () => Promise<string>;
77
+ /** Default `wss://rt.zapiack.com`. */
78
+ url?: string;
79
+ /** How often to check the line is alive. Default 25 seconds. */
80
+ heartbeatMs?: number;
81
+ /** The shortest and longest pause before reconnecting. Default 1s and 30s. */
82
+ backoffMs?: {
83
+ min: number;
84
+ max: number;
85
+ };
86
+ /** How long to wait for a confirmation. Default 10 seconds. */
87
+ ackTimeoutMs?: number;
88
+ }
89
+ declare const DEFAULT_REALTIME_URL = "wss://rt.zapiack.com";
90
+ declare const browserRealtimeEnv: () => RealtimeEnv;
91
+ type Handler = (m: RealtimeMessage) => void;
92
+ declare class ZapiackRealtime {
93
+ private readonly env;
94
+ private readonly now;
95
+ private readonly o;
96
+ private ws;
97
+ private _state;
98
+ private readonly subs;
99
+ private readonly presenceHandlers;
100
+ private readonly members;
101
+ private readonly waiting;
102
+ private readonly pending;
103
+ private rpcSeq;
104
+ private readonly stateHandlers;
105
+ private readonly errorHandlers;
106
+ private outbox;
107
+ private attempt;
108
+ private wanted;
109
+ private retry;
110
+ private beat;
111
+ private heard;
112
+ private ackSeq;
113
+ private first;
114
+ /** Set by an error the server marks fatal, for runtimes that cannot see a custom close code. */
115
+ private refused;
116
+ private _connId;
117
+ constructor(options: RealtimeOptions, env?: RealtimeEnv, now?: () => number);
118
+ get state(): RealtimeState;
119
+ /** This connection's id, once connected. Other members use it to signal you. */
120
+ get connectionId(): string | null;
121
+ onState(fn: (s: RealtimeState) => void): () => void;
122
+ onError(fn: (e: ZapiackRealtimeError) => void): () => void;
123
+ /** Connects and resolves once the server has said hello. It keeps itself connected afterwards until `disconnect()`. */
124
+ connect(): Promise<void>;
125
+ private chain;
126
+ /** Leaves for good: closes the socket, forgets the pending sends. Subscriptions stay, for a later `connect()`. */
127
+ disconnect(): void;
128
+ /** Calls `handler` for every message on the channel, now and after reconnects. Returns how to stop. */
129
+ subscribe(channel: string, handler: Handler, options?: {
130
+ resumeFrom?: string;
131
+ }): () => void;
132
+ /** Sends a message. Resolves when the server confirms, unless `ack: false`. */
133
+ publish(channel: string, data: unknown, options?: PublishOptions): Promise<PublishResult | void>;
134
+ /**
135
+ * Asks a Zapiack service something over this connection and waits for the answer: the way a call client talks to the media server.
136
+ * Needs a token minted for a call. It is never queued for later: if the line is down it fails at once, because an answer to an old
137
+ * question is worse than none.
138
+ */
139
+ request<T = unknown>(method: string, data?: unknown): Promise<T>;
140
+ /** Sends to one connection in a channel you are subscribed to. Used for peer-to-peer setup such as WebRTC. */
141
+ signal(channel: string, to: string, event: string, data: unknown): void;
142
+ /** Presence in a channel you are subscribed to. */
143
+ presence(channel: string): {
144
+ enter: (data?: unknown) => boolean;
145
+ update: (data: unknown) => boolean;
146
+ leave: () => boolean;
147
+ /** Who is here now, as last told. */
148
+ members: () => PresenceMember[];
149
+ onChange: (fn: (e: {
150
+ action: "enter" | "update" | "leave";
151
+ member: Partial<PresenceMember>;
152
+ }) => void) => () => boolean;
153
+ };
154
+ private set;
155
+ private fail;
156
+ private settle;
157
+ private failAll;
158
+ private failRequests;
159
+ /** Writes now if the line is open, otherwise keeps it (a short while) for when it is. False when there is no room. */
160
+ private send;
161
+ private open;
162
+ private onFrame;
163
+ private onMessage;
164
+ private onPresence;
165
+ private rejoin;
166
+ private startBeat;
167
+ private stopBeat;
168
+ private onClose;
169
+ private later;
170
+ }
171
+
172
+ export { DEFAULT_REALTIME_URL as D, ZapiackRealtime as Z, ZapiackRealtimeError as a, browserRealtimeEnv as g };
173
+ export type { PresenceMember as P, RealtimeEnv as R, SocketLike as S, PublishOptions as b, PublishResult as c, RealtimeMessage as d, RealtimeOptions as e, RealtimeState as f };
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Zapiack Realtime: live messages over one WebSocket.
3
+ *
4
+ * Your server mints a short-lived token with its API key (`POST /v1/realtime/tokens`) and hands it to the client, so the API key never
5
+ * reaches a browser or an app. The client asks for a token every time it connects, so a token that expires is simply replaced.
6
+ *
7
+ * It reconnects by itself with a growing, jittered pause, re-joins every channel and asks for what it missed since the last persisted
8
+ * message it saw, so a lost signal costs no messages. Nothing here touches push, so it works in any JavaScript runtime that has a
9
+ * WebSocket: browsers, React Native, Node 22+.
10
+ */
11
+ type RealtimeState = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed';
12
+ interface RealtimeMessage<T = unknown> {
13
+ msgId: string;
14
+ ts: number;
15
+ channel: string;
16
+ event: string;
17
+ data: T;
18
+ /** The user id (or connection id) of the sender. */
19
+ from: string | null;
20
+ /** True when it was sent while this client was away and is being replayed. */
21
+ replayed?: boolean;
22
+ }
23
+ interface PresenceMember {
24
+ connId: string;
25
+ user: string | null;
26
+ data: unknown;
27
+ at: number;
28
+ }
29
+ interface PublishOptions {
30
+ /** The name of the event. Default `message`. */
31
+ event?: string;
32
+ /** Keep it in the channel's history, so clients that were away can replay it. Default false. */
33
+ persist?: boolean;
34
+ /** Wait for the server to confirm. Default true. Pass false to fire and forget. */
35
+ ack?: boolean;
36
+ }
37
+ interface PublishResult {
38
+ msgId: string;
39
+ /** How many connections were subscribed when it was sent. */
40
+ delivered: number;
41
+ }
42
+ declare class ZapiackRealtimeError extends Error {
43
+ /** The server's code: 401 token, 403 not allowed, 413 too large, 429 slow down, 503 try again. 0 for a problem on this side. */
44
+ readonly code: number;
45
+ /** For a failed request (`request()`): the service's own word for it: `forbidden`, `invalid`, `no_route`, `timeout`, `rate_limited` or `internal`. */
46
+ readonly reason?: string | undefined;
47
+ constructor(message: string,
48
+ /** The server's code: 401 token, 403 not allowed, 413 too large, 429 slow down, 503 try again. 0 for a problem on this side. */
49
+ code?: number,
50
+ /** For a failed request (`request()`): the service's own word for it: `forbidden`, `invalid`, `no_route`, `timeout`, `rate_limited` or `internal`. */
51
+ reason?: string | undefined);
52
+ }
53
+ interface SocketLike {
54
+ readyState: number;
55
+ send(data: string): void;
56
+ close(code?: number, reason?: string): void;
57
+ onopen: ((ev?: unknown) => void) | null;
58
+ onmessage: ((ev: {
59
+ data: unknown;
60
+ }) => void) | null;
61
+ onclose: ((ev: {
62
+ code: number;
63
+ }) => void) | null;
64
+ onerror: ((ev?: unknown) => void) | null;
65
+ }
66
+ interface RealtimeEnv {
67
+ socket(url: string): SocketLike;
68
+ setTimeout(fn: () => void, ms: number): unknown;
69
+ clearTimeout(id: unknown): void;
70
+ setInterval(fn: () => void, ms: number): unknown;
71
+ clearInterval(id: unknown): void;
72
+ random(): number;
73
+ }
74
+ interface RealtimeOptions {
75
+ /** Returns a fresh token from your server. Called on every connect, so an expired token is replaced. */
76
+ getToken: () => Promise<string>;
77
+ /** Default `wss://rt.zapiack.com`. */
78
+ url?: string;
79
+ /** How often to check the line is alive. Default 25 seconds. */
80
+ heartbeatMs?: number;
81
+ /** The shortest and longest pause before reconnecting. Default 1s and 30s. */
82
+ backoffMs?: {
83
+ min: number;
84
+ max: number;
85
+ };
86
+ /** How long to wait for a confirmation. Default 10 seconds. */
87
+ ackTimeoutMs?: number;
88
+ }
89
+ declare const DEFAULT_REALTIME_URL = "wss://rt.zapiack.com";
90
+ declare const browserRealtimeEnv: () => RealtimeEnv;
91
+ type Handler = (m: RealtimeMessage) => void;
92
+ declare class ZapiackRealtime {
93
+ private readonly env;
94
+ private readonly now;
95
+ private readonly o;
96
+ private ws;
97
+ private _state;
98
+ private readonly subs;
99
+ private readonly presenceHandlers;
100
+ private readonly members;
101
+ private readonly waiting;
102
+ private readonly pending;
103
+ private rpcSeq;
104
+ private readonly stateHandlers;
105
+ private readonly errorHandlers;
106
+ private outbox;
107
+ private attempt;
108
+ private wanted;
109
+ private retry;
110
+ private beat;
111
+ private heard;
112
+ private ackSeq;
113
+ private first;
114
+ /** Set by an error the server marks fatal, for runtimes that cannot see a custom close code. */
115
+ private refused;
116
+ private _connId;
117
+ constructor(options: RealtimeOptions, env?: RealtimeEnv, now?: () => number);
118
+ get state(): RealtimeState;
119
+ /** This connection's id, once connected. Other members use it to signal you. */
120
+ get connectionId(): string | null;
121
+ onState(fn: (s: RealtimeState) => void): () => void;
122
+ onError(fn: (e: ZapiackRealtimeError) => void): () => void;
123
+ /** Connects and resolves once the server has said hello. It keeps itself connected afterwards until `disconnect()`. */
124
+ connect(): Promise<void>;
125
+ private chain;
126
+ /** Leaves for good: closes the socket, forgets the pending sends. Subscriptions stay, for a later `connect()`. */
127
+ disconnect(): void;
128
+ /** Calls `handler` for every message on the channel, now and after reconnects. Returns how to stop. */
129
+ subscribe(channel: string, handler: Handler, options?: {
130
+ resumeFrom?: string;
131
+ }): () => void;
132
+ /** Sends a message. Resolves when the server confirms, unless `ack: false`. */
133
+ publish(channel: string, data: unknown, options?: PublishOptions): Promise<PublishResult | void>;
134
+ /**
135
+ * Asks a Zapiack service something over this connection and waits for the answer: the way a call client talks to the media server.
136
+ * Needs a token minted for a call. It is never queued for later: if the line is down it fails at once, because an answer to an old
137
+ * question is worse than none.
138
+ */
139
+ request<T = unknown>(method: string, data?: unknown): Promise<T>;
140
+ /** Sends to one connection in a channel you are subscribed to. Used for peer-to-peer setup such as WebRTC. */
141
+ signal(channel: string, to: string, event: string, data: unknown): void;
142
+ /** Presence in a channel you are subscribed to. */
143
+ presence(channel: string): {
144
+ enter: (data?: unknown) => boolean;
145
+ update: (data: unknown) => boolean;
146
+ leave: () => boolean;
147
+ /** Who is here now, as last told. */
148
+ members: () => PresenceMember[];
149
+ onChange: (fn: (e: {
150
+ action: "enter" | "update" | "leave";
151
+ member: Partial<PresenceMember>;
152
+ }) => void) => () => boolean;
153
+ };
154
+ private set;
155
+ private fail;
156
+ private settle;
157
+ private failAll;
158
+ private failRequests;
159
+ /** Writes now if the line is open, otherwise keeps it (a short while) for when it is. False when there is no room. */
160
+ private send;
161
+ private open;
162
+ private onFrame;
163
+ private onMessage;
164
+ private onPresence;
165
+ private rejoin;
166
+ private startBeat;
167
+ private stopBeat;
168
+ private onClose;
169
+ private later;
170
+ }
171
+
172
+ export { DEFAULT_REALTIME_URL as D, ZapiackRealtime as Z, ZapiackRealtimeError as a, browserRealtimeEnv as g };
173
+ export type { PresenceMember as P, RealtimeEnv as R, SocketLike as S, PublishOptions as b, PublishResult as c, RealtimeMessage as d, RealtimeOptions as e, RealtimeState as f };
@@ -0,0 +1,134 @@
1
+ import Foundation
2
+
3
+ public protocol HTTPTransport {
4
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
5
+ }
6
+
7
+ public struct URLSessionTransport: HTTPTransport {
8
+ private let session: URLSession
9
+
10
+ public init(session: URLSession = .shared) {
11
+ self.session = session
12
+ }
13
+
14
+ public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
15
+ let (data, response) = try await session.data(for: request)
16
+ guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
17
+ return (data, http)
18
+ }
19
+ }
20
+
21
+ public struct EventsResult: Decodable, Equatable {
22
+ public struct Rejection: Decodable, Equatable {
23
+ public var index: Int
24
+ public var reason: String
25
+ }
26
+
27
+ public var accepted: Int
28
+ public var ignored: Int
29
+ public var rejected: [Rejection]
30
+ }
31
+
32
+ public enum SendOutcome: Equatable {
33
+ case sent(EventsResult)
34
+ /// The request did not get through, or the service was busy: keep the events and try again.
35
+ case retry
36
+ /// The request was refused for good: repeating it will be refused again.
37
+ case refused(status: Int)
38
+ }
39
+
40
+ public struct DeviceRegistration: Encodable {
41
+ public var installationId: String
42
+ public var platform: String
43
+ public var token: String
44
+ public var externalUserId: String??
45
+ public var tags: [String: JSONValue]?
46
+ public var permission: String?
47
+ public var environment: String?
48
+ public var appVersion: String?
49
+ /// iOS 17.2+: the push-to-start token for Zapiack Live Activities, as hex. Absent leaves the one on file alone.
50
+ public var liveActivityToken: String?
51
+
52
+ public init(installationId: String, platform: String = "ios", token: String, externalUserId: String?? = nil, tags: [String: JSONValue]? = nil, permission: String? = nil, environment: String? = nil, appVersion: String? = nil, liveActivityToken: String? = nil) {
53
+ self.installationId = installationId
54
+ self.platform = platform
55
+ self.token = token
56
+ self.externalUserId = externalUserId
57
+ self.tags = tags
58
+ self.permission = permission
59
+ self.environment = environment
60
+ self.appVersion = appVersion
61
+ self.liveActivityToken = liveActivityToken
62
+ }
63
+
64
+ private enum CodingKeys: String, CodingKey {
65
+ case installationId, platform, token, externalUserId, tags, permission, environment, appVersion, liveActivityToken
66
+ }
67
+
68
+ // An absent user leaves the link alone, a string links it, and an explicit null unlinks it, so all three are kept apart.
69
+ public func encode(to encoder: Encoder) throws {
70
+ var c = encoder.container(keyedBy: CodingKeys.self)
71
+ try c.encode(installationId, forKey: .installationId)
72
+ try c.encode(platform, forKey: .platform)
73
+ try c.encode(token, forKey: .token)
74
+ switch externalUserId {
75
+ case .none: break
76
+ case .some(.none): try c.encodeNil(forKey: .externalUserId)
77
+ case .some(.some(let id)): try c.encode(id, forKey: .externalUserId)
78
+ }
79
+ try c.encodeIfPresent(tags, forKey: .tags)
80
+ try c.encodeIfPresent(permission, forKey: .permission)
81
+ try c.encodeIfPresent(environment, forKey: .environment)
82
+ try c.encodeIfPresent(appVersion, forKey: .appVersion)
83
+ try c.encodeIfPresent(liveActivityToken, forKey: .liveActivityToken)
84
+ }
85
+ }
86
+
87
+ public struct SdkApi {
88
+ private let config: ZapiackConfig
89
+ private let transport: HTTPTransport
90
+
91
+ public init(config: ZapiackConfig, transport: HTTPTransport = URLSessionTransport()) {
92
+ self.config = config
93
+ self.transport = transport
94
+ }
95
+
96
+ func request(_ path: String, method: String, body: Data?) -> URLRequest {
97
+ var url = config.baseUrl
98
+ for part in ["push", "sdk", path] { url.appendPathComponent(part) }
99
+ var request = URLRequest(url: url)
100
+ request.httpMethod = method
101
+ request.httpBody = body
102
+ request.timeoutInterval = 20
103
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
104
+ request.setValue(config.appKey, forHTTPHeaderField: "X-Zapiack-App-Key")
105
+ return request
106
+ }
107
+
108
+ public func register(_ registration: DeviceRegistration) async throws {
109
+ let body = try JSONEncoder().encode(registration)
110
+ let (_, response) = try await transport.send(request("devices", method: "PUT", body: body))
111
+ guard (200..<300).contains(response.statusCode) else { throw ZapiackError.registrationFailed(status: response.statusCode) }
112
+ }
113
+
114
+ public func sendEvents(_ events: [SdkEvent]) async -> SendOutcome {
115
+ guard let body = try? JSONEncoder().encode(["events": events]) else { return .refused(status: 0) }
116
+ do {
117
+ let (data, response) = try await transport.send(request("events", method: "POST", body: body))
118
+ if (200..<300).contains(response.statusCode) {
119
+ let result = (try? JSONDecoder().decode(EventsResult.self, from: data)) ?? EventsResult(accepted: events.count, ignored: 0, rejected: [])
120
+ return .sent(result)
121
+ }
122
+ // Busy or down: try again. Anything else (a wrong key, a bad request) will not improve by repeating it.
123
+ if response.statusCode == 429 || response.statusCode == 408 || response.statusCode >= 500 { return .retry }
124
+ return .refused(status: response.statusCode)
125
+ } catch {
126
+ return .retry
127
+ }
128
+ }
129
+ }
130
+
131
+ public enum ZapiackError: Error, Equatable {
132
+ case notConfigured
133
+ case registrationFailed(status: Int)
134
+ }
@@ -0,0 +1,95 @@
1
+ import Foundation
2
+
3
+ /// Events waiting to be sent, one file each. The app and its extension both write here, and a file is only ever created whole
4
+ /// and removed whole, so neither can overwrite the other's events the way a shared list would.
5
+ public final class EventQueue {
6
+ public static let maxEvents = 500
7
+ public static let batchSize = 100
8
+ private static let maxAge: TimeInterval = 6 * 24 * 3600
9
+
10
+ private let directory: URL
11
+ private let fileManager = FileManager.default
12
+ private let lock = NSLock()
13
+ private var sequence = 0
14
+
15
+ public init(directory: URL) {
16
+ self.directory = directory
17
+ try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
18
+ }
19
+
20
+ @discardableResult
21
+ public func add(_ event: SdkEvent, now: Date = Date()) -> Bool {
22
+ guard let data = try? JSONEncoder().encode(event) else { return false }
23
+ lock.lock()
24
+ sequence += 1
25
+ let seq = sequence
26
+ lock.unlock()
27
+ // The time first so files list in the order events happened, then a counter for events in the same millisecond.
28
+ let name = String(format: "%015ld-%06ld-%@.json", Int(now.timeIntervalSince1970 * 1000), seq, event.clientEventId)
29
+ do {
30
+ try data.write(to: directory.appendingPathComponent(name), options: .atomic)
31
+ } catch {
32
+ return false
33
+ }
34
+ trim()
35
+ return true
36
+ }
37
+
38
+ public func pending() -> [(url: URL, event: SdkEvent)] {
39
+ let urls = (try? fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []
40
+ return urls
41
+ .filter { $0.pathExtension == "json" }
42
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
43
+ .compactMap { url in
44
+ guard let data = try? Data(contentsOf: url), let event = try? JSONDecoder().decode(SdkEvent.self, from: data) else {
45
+ // A file nothing can read is never going to be sent.
46
+ try? fileManager.removeItem(at: url)
47
+ return nil
48
+ }
49
+ return (url, event)
50
+ }
51
+ }
52
+
53
+ public var count: Int { pending().count }
54
+
55
+ /// Sends what is waiting, a batch at a time. Stops at the first batch that has to be retried, leaving it in place.
56
+ @discardableResult
57
+ public func flush(using api: SdkApi, now: Date = Date()) async -> Bool {
58
+ discardExpired(now: now)
59
+ while true {
60
+ let batch = Array(pending().prefix(Self.batchSize))
61
+ if batch.isEmpty { return true }
62
+ switch await api.sendEvents(batch.map(\.event)) {
63
+ case .retry:
64
+ return false
65
+ case .refused, .sent:
66
+ // Sent, or refused for good: either way these events are finished with. Rejected ones are malformed, so dropped too.
67
+ for item in batch { try? fileManager.removeItem(at: item.url) }
68
+ }
69
+ }
70
+ }
71
+
72
+ private func discardExpired(now: Date) {
73
+ for item in pending() {
74
+ guard let at = ISO8601DateFormatter.withFraction.date(from: item.event.at) else {
75
+ try? fileManager.removeItem(at: item.url)
76
+ continue
77
+ }
78
+ if now.timeIntervalSince(at) > Self.maxAge { try? fileManager.removeItem(at: item.url) }
79
+ }
80
+ }
81
+
82
+ private func trim() {
83
+ let all = pending()
84
+ guard all.count > Self.maxEvents else { return }
85
+ for item in all.prefix(all.count - Self.maxEvents) { try? fileManager.removeItem(at: item.url) }
86
+ }
87
+ }
88
+
89
+ extension ISO8601DateFormatter {
90
+ static let withFraction: ISO8601DateFormatter = {
91
+ let f = ISO8601DateFormatter()
92
+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
93
+ return f
94
+ }()
95
+ }
@@ -0,0 +1,22 @@
1
+ import Foundation
2
+
3
+ /// Picks the file type a downloaded picture is shown as; the system decides from the extension.
4
+ public struct ImageFile: Equatable {
5
+ public var fileExtension: String
6
+
7
+ public static func kind(mimeType: String?, url: URL) -> ImageFile? {
8
+ switch mimeType?.lowercased() {
9
+ case "image/jpeg", "image/jpg": return ImageFile(fileExtension: "jpg")
10
+ case "image/png": return ImageFile(fileExtension: "png")
11
+ case "image/gif": return ImageFile(fileExtension: "gif")
12
+ case "image/webp": return nil
13
+ default:
14
+ switch url.pathExtension.lowercased() {
15
+ case "jpg", "jpeg": return ImageFile(fileExtension: "jpg")
16
+ case "png": return ImageFile(fileExtension: "png")
17
+ case "gif": return ImageFile(fileExtension: "gif")
18
+ default: return nil
19
+ }
20
+ }
21
+ }
22
+ }