@geastack/host 0.1.17 → 0.1.18

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,442 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Link this provider on Apple desktop targets (Foundation, ARC, blocks).
3
+ #if defined(__APPLE__) && !defined(ESP_PLATFORM)
4
+ #include "host/websocket_platform.h"
5
+ #import <Foundation/Foundation.h>
6
+ #include <atomic>
7
+ #include <deque>
8
+ #include <mutex>
9
+ #include <unordered_map>
10
+
11
+ namespace gea::host::websocket::apple {
12
+ struct State;
13
+ }
14
+ @interface GeaWebSocketDelegate : NSObject <NSURLSessionWebSocketDelegate> {
15
+ @public
16
+ std::weak_ptr<gea::host::websocket::apple::State> owner;
17
+ }
18
+ @end
19
+
20
+ namespace gea::host::websocket::apple {
21
+ constexpr std::size_t maxBuffered = 512 * 1024;
22
+ struct State : std::enable_shared_from_this<State> {
23
+ NativeWebSocketHandle handle;
24
+ std::mutex mutex;
25
+ std::deque<std::string> outgoing;
26
+ std::size_t bytes = 0;
27
+ bool sending = false;
28
+ bool opened = false;
29
+ bool stopped = false;
30
+ std::atomic<bool> terminal{false};
31
+ TextProducer producer;
32
+ NSURLSession *session = nil;
33
+ NSURLSessionWebSocketTask *task = nil;
34
+ GeaWebSocketDelegate *delegate = nil;
35
+ dispatch_source_t timer = nil;
36
+ explicit State(NativeWebSocketHandle h) : handle(h) {}
37
+ ~State() { shutdown(); }
38
+
39
+ void shutdown() {
40
+ dispatch_source_t oldTimer;
41
+ NSURLSession *oldSession;
42
+ TextProducer retired;
43
+ {
44
+ std::lock_guard lock(mutex);
45
+ stopped = true;
46
+ retired = std::move(producer);
47
+ outgoing.clear();
48
+ bytes = 0;
49
+ oldTimer = timer;
50
+ timer = nil;
51
+ oldSession = session;
52
+ session = nil;
53
+ }
54
+ retired = {};
55
+ if (oldTimer)
56
+ dispatch_source_cancel(oldTimer);
57
+ [oldSession invalidateAndCancel];
58
+ }
59
+ void failed(const char *message) {
60
+ TextProducer retired;
61
+ const auto code = task.closeCode;
62
+ if (code != NSURLSessionWebSocketCloseCodeInvalid) {
63
+ {
64
+ std::lock_guard lock(mutex);
65
+ stopped = true;
66
+ retired = std::move(producer);
67
+ outgoing.clear();
68
+ bytes = 0;
69
+ }
70
+ retired = {};
71
+ NSData *reason = task.closeReason;
72
+ terminal.store(true, std::memory_order_release);
73
+ transport_close(handle, static_cast<int>(code),
74
+ reason.length
75
+ ? std::string(static_cast<const char *>(reason.bytes),
76
+ reason.length)
77
+ : std::string{});
78
+ shutdown();
79
+ return;
80
+ }
81
+ bool alreadyStopped;
82
+ {
83
+ std::lock_guard lock(mutex);
84
+ alreadyStopped = stopped;
85
+ stopped = true;
86
+ retired = std::move(producer);
87
+ outgoing.clear();
88
+ bytes = 0;
89
+ }
90
+ retired = {};
91
+ if (alreadyStopped) {
92
+ // Cancelling during the handshake may complete without didClose.
93
+ terminal.store(true, std::memory_order_release);
94
+ transport_close(handle, 1000, "WebSocket closed locally");
95
+ shutdown();
96
+ return;
97
+ }
98
+ terminal.store(true, std::memory_order_release);
99
+ transport_error(handle, message);
100
+ transport_close(handle, 1006, "WebSocket transport failed");
101
+ shutdown();
102
+ }
103
+ bool enqueue(std::string text) {
104
+ bool overflow = false;
105
+ {
106
+ std::lock_guard lock(mutex);
107
+ if (stopped || !opened)
108
+ return false;
109
+ overflow = outgoing.size() + (sending ? 1 : 0) >= 1024 ||
110
+ text.size() > maxBuffered - bytes;
111
+ if (!overflow) {
112
+ bytes += text.size();
113
+ outgoing.push_back(std::move(text));
114
+ }
115
+ }
116
+ if (overflow) {
117
+ failed("WebSocket send queue exceeds 512 KiB");
118
+ return false;
119
+ }
120
+ pump();
121
+ return true;
122
+ }
123
+ void pump() {
124
+ std::string text;
125
+ {
126
+ std::lock_guard lock(mutex);
127
+ if (stopped || sending || !opened || outgoing.empty())
128
+ return;
129
+ sending = true;
130
+ text = std::move(outgoing.front());
131
+ outgoing.pop_front();
132
+ }
133
+ NSString *value = [[NSString alloc] initWithBytes:text.data()
134
+ length:text.size()
135
+ encoding:NSUTF8StringEncoding];
136
+ if (!value) {
137
+ failed("WebSocket text must be valid UTF-8");
138
+ return;
139
+ }
140
+ const auto length = text.size();
141
+ std::weak_ptr<State> weak = shared_from_this();
142
+ [task sendMessage:[[NSURLSessionWebSocketMessage alloc]
143
+ initWithString:value]
144
+ completionHandler:^(NSError *error) {
145
+ if (auto state = weak.lock()) {
146
+ if (error) {
147
+ state->failed("WebSocket send failed");
148
+ return;
149
+ }
150
+ {
151
+ std::lock_guard lock(state->mutex);
152
+ if (state->stopped)
153
+ return;
154
+ state->bytes -= length;
155
+ state->sending = false;
156
+ }
157
+ state->pump();
158
+ }
159
+ }];
160
+ }
161
+ void receive() {
162
+ {
163
+ std::lock_guard lock(mutex);
164
+ if (stopped)
165
+ return;
166
+ }
167
+ std::weak_ptr<State> weak = shared_from_this();
168
+ [task receiveMessageWithCompletionHandler:^(
169
+ NSURLSessionWebSocketMessage *message, NSError *error) {
170
+ if (auto state = weak.lock()) {
171
+ {
172
+ std::lock_guard lock(state->mutex);
173
+ if (state->stopped)
174
+ return;
175
+ }
176
+ if (error) {
177
+ state->failed("WebSocket receive failed");
178
+ return;
179
+ }
180
+ if (message.type == NSURLSessionWebSocketMessageTypeString) {
181
+ NSData *utf8 =
182
+ [message.string dataUsingEncoding:NSUTF8StringEncoding];
183
+ transport_message(
184
+ state->handle,
185
+ utf8.length ? std::string(static_cast<const char *>(utf8.bytes),
186
+ utf8.length)
187
+ : std::string{});
188
+ }
189
+ state->receive(); // The public facade exposes text messages only.
190
+ }
191
+ }];
192
+ }
193
+ void produce() {
194
+ TextProducer next;
195
+ {
196
+ std::lock_guard lock(mutex);
197
+ if (stopped || !opened)
198
+ return;
199
+ next = producer;
200
+ }
201
+ if (!next)
202
+ return;
203
+ try {
204
+ auto text = next();
205
+ if (!text.empty())
206
+ enqueue(std::move(text));
207
+ } catch (...) {
208
+ failed("WebSocket text producer failed");
209
+ }
210
+ }
211
+ };
212
+ std::mutex tableMutex;
213
+ std::unordered_map<NativeWebSocketHandle, std::shared_ptr<State>> table;
214
+ std::shared_ptr<State> find(NativeWebSocketHandle handle) {
215
+ std::lock_guard lock(tableMutex);
216
+ auto it = table.find(handle);
217
+ return it == table.end() ? nullptr : it->second;
218
+ }
219
+ } // namespace gea::host::websocket::apple
220
+
221
+ @implementation GeaWebSocketDelegate
222
+ - (void)URLSession:(NSURLSession *)session
223
+ webSocketTask:(NSURLSessionWebSocketTask *)task
224
+ didOpenWithProtocol:(NSString *)protocol {
225
+ if (auto state = owner.lock()) {
226
+ {
227
+ std::lock_guard lock(state->mutex);
228
+ if (state->stopped)
229
+ return;
230
+ state->opened = true;
231
+ }
232
+ if (gea::host::websocket::transport_open(state->handle)) {
233
+ state->receive();
234
+ state->pump();
235
+ }
236
+ }
237
+ }
238
+ - (void)URLSession:(NSURLSession *)session
239
+ webSocketTask:(NSURLSessionWebSocketTask *)task
240
+ didCloseWithCode:(NSURLSessionWebSocketCloseCode)code
241
+ reason:(NSData *)reason {
242
+ if (auto state = owner.lock()) {
243
+ gea::host::websocket::TextProducer retired;
244
+ {
245
+ std::lock_guard lock(state->mutex);
246
+ state->stopped = true;
247
+ retired = std::move(state->producer);
248
+ state->outgoing.clear();
249
+ state->bytes = 0;
250
+ }
251
+ retired = {};
252
+ std::string text;
253
+ if (reason.length)
254
+ text.assign(static_cast<const char *>(reason.bytes), reason.length);
255
+ state->terminal.store(true, std::memory_order_release);
256
+ gea::host::websocket::transport_close(state->handle, static_cast<int>(code),
257
+ text);
258
+ state->shutdown();
259
+ }
260
+ }
261
+ - (void)URLSession:(NSURLSession *)session
262
+ task:(NSURLSessionTask *)task
263
+ didCompleteWithError:(NSError *)error {
264
+ if (error)
265
+ if (auto state = owner.lock())
266
+ state->failed("WebSocket connection failed");
267
+ }
268
+ @end
269
+
270
+ namespace gea::host::websocket {
271
+ void platform_open(NativeWebSocketHandle handle, const std::string &url,
272
+ const std::string &protocols, const std::string &headers) {
273
+ @autoreleasepool {
274
+ NSString *raw = [[NSString alloc] initWithBytes:url.data()
275
+ length:url.size()
276
+ encoding:NSUTF8StringEncoding];
277
+ NSURLComponents *parts =
278
+ raw ? [NSURLComponents componentsWithString:raw] : nil;
279
+ if (!parts ||
280
+ (![parts.scheme isEqualToString:@"ws"] &&
281
+ ![parts.scheme isEqualToString:@"wss"]) ||
282
+ !parts.host.length || parts.user || parts.password || parts.fragment ||
283
+ !parts.URL || url.find('\0') != std::string::npos ||
284
+ protocols.find_first_of("\r\n") != std::string::npos ||
285
+ protocols.find('\0') != std::string::npos) {
286
+ transport_error(handle, "Invalid WebSocket URL or protocols");
287
+ transport_close(handle, 1006, "WebSocket connection rejected");
288
+ return;
289
+ }
290
+ NSMutableURLRequest *request =
291
+ [NSMutableURLRequest requestWithURL:parts.URL];
292
+ request.timeoutInterval = 10;
293
+ if (!protocols.empty())
294
+ [request setValue:[NSString stringWithUTF8String:protocols.c_str()]
295
+ forHTTPHeaderField:@"Sec-WebSocket-Protocol"];
296
+ std::size_t offset = 0;
297
+ while (offset < headers.size()) {
298
+ const auto end = headers.find("\r\n", offset);
299
+ const auto colon = headers.find(':', offset);
300
+ if (end == std::string::npos || colon == std::string::npos ||
301
+ colon >= end || colon == offset) {
302
+ transport_error(handle, "Invalid WebSocket header");
303
+ transport_close(handle, 1006, "WebSocket connection rejected");
304
+ return;
305
+ }
306
+ const auto name = headers.substr(offset, colon - offset);
307
+ const auto value = headers.substr(colon + 1, end - colon - 1);
308
+ if (name.find_first_not_of("!#$%&'*+-.^_`|~"
309
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi"
310
+ "jklmnopqrstuvwxyz") != std::string::npos ||
311
+ value.find_first_of("\r\n") != std::string::npos ||
312
+ value.find('\0') != std::string::npos) {
313
+ transport_error(handle, "Invalid WebSocket header");
314
+ transport_close(handle, 1006, "WebSocket connection rejected");
315
+ return;
316
+ }
317
+ NSString *headerValue =
318
+ [[NSString alloc] initWithBytes:value.data()
319
+ length:value.size()
320
+ encoding:NSUTF8StringEncoding];
321
+ if (!headerValue) {
322
+ transport_error(handle, "Invalid WebSocket header encoding");
323
+ transport_close(handle, 1006, "WebSocket connection rejected");
324
+ return;
325
+ }
326
+ [request setValue:headerValue
327
+ forHTTPHeaderField:[NSString stringWithUTF8String:name.c_str()]];
328
+ offset = end + 2;
329
+ }
330
+ auto state = std::make_shared<apple::State>(handle);
331
+ state->delegate = [GeaWebSocketDelegate new];
332
+ state->delegate->owner = state;
333
+ auto configuration =
334
+ [NSURLSessionConfiguration ephemeralSessionConfiguration];
335
+ configuration.HTTPCookieStorage = nil;
336
+ configuration.URLCredentialStorage = nil;
337
+ auto queue = [NSOperationQueue new];
338
+ queue.maxConcurrentOperationCount = 1;
339
+ state->session = [NSURLSession sessionWithConfiguration:configuration
340
+ delegate:state->delegate
341
+ delegateQueue:queue];
342
+ state->task = [state->session webSocketTaskWithRequest:request];
343
+ state->task.maximumMessageSize = 1024 * 1024;
344
+ state->timer = dispatch_source_create(
345
+ DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
346
+ dispatch_queue_create("gea.websocket.producer", DISPATCH_QUEUE_SERIAL));
347
+ std::weak_ptr<apple::State> weak = state;
348
+ dispatch_source_set_event_handler(state->timer, ^{
349
+ if (auto current = weak.lock())
350
+ current->produce();
351
+ });
352
+ dispatch_source_set_timer(state->timer,
353
+ dispatch_time(DISPATCH_TIME_NOW, 10000000),
354
+ 10000000, 1000000);
355
+ {
356
+ std::lock_guard lock(apple::tableMutex);
357
+ apple::table.emplace(handle, state);
358
+ }
359
+ dispatch_resume(state->timer);
360
+ [state->task resume];
361
+ }
362
+ }
363
+ std::size_t platform_buffered(NativeWebSocketHandle handle) {
364
+ auto state = apple::find(handle);
365
+ if (!state)
366
+ return 0;
367
+ std::lock_guard lock(state->mutex);
368
+ return state->bytes;
369
+ }
370
+ void platform_send(NativeWebSocketHandle handle, const std::string &text) {
371
+ auto state = apple::find(handle);
372
+ if (!state || !state->enqueue(text))
373
+ throw std::runtime_error("WebSocket is not open or send queue is full");
374
+ }
375
+ void platform_close(NativeWebSocketHandle handle) {
376
+ auto state = apple::find(handle);
377
+ if (!state)
378
+ return;
379
+ TextProducer retired;
380
+ {
381
+ std::lock_guard lock(state->mutex);
382
+ if (state->stopped)
383
+ return;
384
+ state->stopped = true;
385
+ retired = std::move(state->producer);
386
+ }
387
+ retired = {};
388
+ transport_closing(handle);
389
+ [state->task cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure
390
+ reason:nil];
391
+ }
392
+ void platform_destroy(NativeWebSocketHandle handle) {
393
+ std::shared_ptr<apple::State> state;
394
+ {
395
+ std::lock_guard lock(apple::tableMutex);
396
+ auto it = apple::table.find(handle);
397
+ if (it == apple::table.end())
398
+ return;
399
+ state = std::move(it->second);
400
+ apple::table.erase(it);
401
+ }
402
+ state->shutdown();
403
+ }
404
+ void platform_reap() {
405
+ std::vector<std::shared_ptr<apple::State>> retired;
406
+ {
407
+ std::lock_guard lock(apple::tableMutex);
408
+ for (auto it = apple::table.begin(); it != apple::table.end();) {
409
+ if (it->second->terminal.load(std::memory_order_acquire)) {
410
+ retired.push_back(std::move(it->second));
411
+ it = apple::table.erase(it);
412
+ } else
413
+ ++it;
414
+ }
415
+ }
416
+ // Facade instances retain CLOSED/url metadata; native transport ownership
417
+ // ends.
418
+ for (auto &state : retired)
419
+ state->shutdown();
420
+ }
421
+ namespace apple {
422
+ std::size_t transport_count_for_test() {
423
+ std::lock_guard lock(tableMutex);
424
+ return table.size();
425
+ }
426
+ } // namespace apple
427
+ void platform_set_producer(NativeWebSocketHandle handle,
428
+ TextProducer producer) {
429
+ auto state = apple::find(handle);
430
+ if (!state)
431
+ throw std::invalid_argument("Closed WebSocket producer");
432
+ TextProducer retired;
433
+ {
434
+ std::lock_guard lock(state->mutex);
435
+ if (state->stopped)
436
+ throw std::invalid_argument("Closed WebSocket producer");
437
+ retired = std::move(state->producer);
438
+ state->producer = std::move(producer);
439
+ }
440
+ }
441
+ } // namespace gea::host::websocket
442
+ #endif