Repository navigation
Expand file tree
/
Copy pathRealtimeSerializer.swift
More file actions
258 lines (225 loc) · 7.67 KB
/
Copy pathRealtimeSerializer.swift
File metadata and controls
258 lines (225 loc) · 7.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//
// RealtimeSerializer.swift
//
//
// Created by Guilherme Souza on 12/02/26.
//
package import Foundation
package import Helpers
/// Represents a decoded binary broadcast message from the server.
package struct DecodedBroadcast: Sendable {
package let topic: String
/// The user event name extracted from the binary frame.
package let event: String
/// The frame's metadata object, e.g. `id` and `replayed` on database-originated broadcasts.
package var meta: JSONObject? = nil
package let payload: Payload
package enum Payload: Sendable {
case json(JSONObject)
case binary(Data)
}
}
/// Handles encoding/decoding between ``RealtimeMessage`` and the Realtime protocol 2.0.0 wire format.
///
/// Protocol 2.0.0 uses:
/// - JSON array text frames for non-broadcast messages: `[joinRef, ref, topic, event, payload]`
/// - Binary frames (type 0x03 client->server, type 0x04 server->client) for broadcast messages.
/// Note: broadcast messages can also arrive as JSON array text frames — the server may deliver
/// broadcasts on either transport, so the client must be able to handle both.
package struct RealtimeSerializer: Sendable {
package init() {}
/// The most UTF-8 bytes a binary frame header field holds: its length prefix is one byte.
package static let maxHeaderFieldBytes = 255
package enum BinaryKind: UInt8 {
/// Client -> server broadcast push.
case userBroadcastPush = 3
/// Server -> client broadcast.
case userBroadcast = 4
}
package enum PayloadEncoding: UInt8 {
case binary = 0
case json = 1
}
/// Encodes a ``RealtimeMessage`` as a JSON array string: `[joinRef, ref, topic, event, payload]`.
package func encodeText(_ message: RealtimeMessage) throws -> String {
let array: [JSONValue] = [
message.joinRef.map { .string($0) } ?? .null,
message.ref.map { .string($0) } ?? .null,
.string(message.topic),
.string(message.event),
.object(message.payload),
]
let data = try JSONEncoder().encode(array)
return String(decoding: data, as: UTF8.self)
}
/// Decodes a JSON array string `[joinRef, ref, topic, event, payload]` into a ``RealtimeMessage``.
package func decodeText(_ text: String) throws -> RealtimeMessage {
let data = Data(text.utf8)
let array = try JSONDecoder().decode([JSONValue].self, from: data)
guard array.count == 5 else {
throw RealtimeError.decoding(
"Expected JSON array with 5 elements, got \(array.count)."
)
}
let joinRef = array[0].stringValue
let ref = array[1].stringValue
guard let topic = array[2].stringValue else {
throw RealtimeError.decoding("Expected string for topic at index 2.")
}
guard let event = array[3].stringValue else {
throw RealtimeError.decoding("Expected string for event at index 3.")
}
guard let payload = array[4].objectValue else {
throw RealtimeError.decoding("Expected object for payload at index 4.")
}
return RealtimeMessage(
joinRef: joinRef,
ref: ref,
topic: topic,
event: event,
payload: payload
)
}
/// Encodes a broadcast push as a binary frame (type 0x03) with a JSON payload.
///
/// Binary frame format:
/// ```
/// [kind:1][joinRef_len:1][ref_len:1][topic_len:1][event_len:1][meta_len:1][encoding:1]
/// [joinRef][ref][topic][event][metadata][payload]
/// ```
package func encodeBroadcastPush(
joinRef: String?,
ref: String?,
topic: String,
event: String,
jsonPayload: JSONObject
) throws -> Data {
let payloadData = try JSONEncoder().encode(jsonPayload)
return try _encodeBroadcastPush(
joinRef: joinRef,
ref: ref,
topic: topic,
event: event,
encoding: .json,
payload: payloadData
)
}
/// Encodes a broadcast push as a binary frame (type 0x03) with a binary payload.
package func encodeBroadcastPush(
joinRef: String?,
ref: String?,
topic: String,
event: String,
binaryPayload: Data
) throws -> Data {
try _encodeBroadcastPush(
joinRef: joinRef,
ref: ref,
topic: topic,
event: event,
encoding: .binary,
payload: binaryPayload
)
}
private func _encodeBroadcastPush(
joinRef: String?,
ref: String?,
topic: String,
event: String,
encoding: PayloadEncoding,
payload: Data
) throws -> Data {
let joinRefBytes = Data((joinRef ?? "").utf8)
let refBytes = Data((ref ?? "").utf8)
let topicBytes = Data(topic.utf8)
let eventBytes = Data(event.utf8)
let metaBytes = Data()
let limit = Self.maxHeaderFieldBytes
guard joinRefBytes.count <= limit,
refBytes.count <= limit,
topicBytes.count <= limit,
eventBytes.count <= limit,
metaBytes.count <= limit
else {
throw RealtimeError.invalidRequest(
"Binary frame header fields must not exceed \(limit) bytes each."
)
}
var data = Data()
data.append(BinaryKind.userBroadcastPush.rawValue)
data.append(UInt8(joinRefBytes.count))
data.append(UInt8(refBytes.count))
data.append(UInt8(topicBytes.count))
data.append(UInt8(eventBytes.count))
data.append(UInt8(metaBytes.count))
data.append(encoding.rawValue)
data.append(joinRefBytes)
data.append(refBytes)
data.append(topicBytes)
data.append(eventBytes)
data.append(metaBytes)
data.append(payload)
return data
}
/// Decodes a binary frame (type 0x04) into a ``DecodedBroadcast``.
///
/// Binary frame format:
/// ```
/// [kind:1][topic_len:1][event_len:1][meta_len:1][encoding:1]
/// [topic][event][metadata][payload]
/// ```
package func decodeBinary(_ data: Data) throws -> DecodedBroadcast {
guard data.count >= 5 else {
throw RealtimeError.decoding("Binary frame too short: \(data.count) bytes.")
}
let kind = data[data.startIndex]
guard kind == BinaryKind.userBroadcast.rawValue else {
throw RealtimeError.decoding(
"Unexpected binary frame kind: \(kind), expected \(BinaryKind.userBroadcast.rawValue)."
)
}
let topicLen = Int(data[data.startIndex + 1])
let eventLen = Int(data[data.startIndex + 2])
let metaLen = Int(data[data.startIndex + 3])
let encodingByte = data[data.startIndex + 4]
guard let encoding = PayloadEncoding(rawValue: encodingByte) else {
throw RealtimeError.decoding("Unknown payload encoding: \(encodingByte).")
}
let headerSize = 5
let expectedMinSize = headerSize + topicLen + eventLen + metaLen
guard data.count >= expectedMinSize else {
throw RealtimeError.decoding(
"Binary frame too short for declared field lengths."
)
}
var offset = data.startIndex + headerSize
let topicData = data[offset..<(offset + topicLen)]
offset += topicLen
let eventData = data[offset..<(offset + eventLen)]
offset += eventLen
let metaData = data[offset..<(offset + metaLen)]
offset += metaLen
let payloadData = data[offset...]
guard let topic = String(data: topicData, encoding: .utf8) else {
throw RealtimeError.decoding("Failed to decode topic as UTF-8.")
}
guard let event = String(data: eventData, encoding: .utf8) else {
throw RealtimeError.decoding("Failed to decode event as UTF-8.")
}
let meta = metaLen > 0 ? try JSONDecoder().decode(JSONObject.self, from: Data(metaData)) : nil
let payload: DecodedBroadcast.Payload
switch encoding {
case .json:
let jsonObject = try JSONDecoder().decode(JSONObject.self, from: Data(payloadData))
payload = .json(jsonObject)
case .binary:
payload = .binary(Data(payloadData))
}
return DecodedBroadcast(
topic: topic,
event: event,
meta: meta,
payload: payload
)
}
}