ReviewOS

also looking at this

craft-native/craft

iOS Phase 7: location and motion streams — ratchet 64 → 58

#89
Merged glennmichael123 wants to merge feat/ios-phase7-events into main
9 files +5347 -2

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

packages/zig/src/ios_dispatch.zigmodified+2-0
Changes to packages/zig/src/ios_dispatch.zig
@@ -4,6 +4,7 @@ const objc_runtime = @import("objc_runtime.zig");
44const request_context = @import("request_context.zig");
55const bridge_error = @import("bridge_error.zig");
66pub const ios_async = @import("ios_async.zig");
7pub const ios_events = @import("ios_events.zig");
78const bridge_mobile = @import("bridge_mobile.zig");
89const bridge_mobile_clipboard = @import("bridge_mobile_clipboard.zig");
910const bridge_mobile_haptics = @import("bridge_mobile_haptics.zig");
@@ -380,6 +381,7 @@ fn buildShimError(
380381
381382test {
382383 _ = ios_async;
384 _ = ios_events;
383385}
384386
385387const testing = std.testing;
packages/zig/src/ios_events.zigadded+230-0
Changes to packages/zig/src/ios_events.zig
@@ -0,0 +1,230 @@
1//! Pushing an event to the page, from wherever the event happened.
2//!
3//! A reply answers a call the page made; an event is native talking first.
4//! That difference decides everything about this file. There is no request id
5//! to carry, so `ios_async`'s slot pool has nothing to hold — but the hard part
6//! it solves is still here: a `CLLocationManager` delegate callback, a
7//! `CMMotionManager` handler, a `SFSpeechRecognizer` result all arrive on
8//! whatever queue the framework chose, and `evaluateJavaScript` is
9//! main-thread-only.
10//!
11//! The desktop emits events by concatenating JavaScript by hand —
12//! `bridge_iap.zig:362` builds `dispatchEvent(new CustomEvent('...', { detail:
13//! { productId: '` and then appends a value with its own escaping. That works
14//! until a value contains a quote. Here the detail is already JSON, so it is
15//! inlined as an object literal and never escaped twice; the only thing
16//! interpolated as a *name* comes from the `Channel` enum, which is a fixed
17//! set of literals rather than anything a page or a device can influence.
18//!
19//! Emitting also marks the channel live, so `craft.capabilities()` stops
20//! saying "unknown" about a channel that has actually fired. A page asking
21//! what it can subscribe to gets an answer from the code that does the
22//! subscribing, not from a list someone maintained by hand.
23
24const std = @import("std");
25const builtin = @import("builtin");
26const capabilities = @import("capabilities.zig");
27const compat_mutex = @import("compat_mutex.zig");
28
29/// A queued event, owned until the main queue drains it.
30const Pending = struct {
31 in_use: bool = false,
32 /// The channel, not its name: an enum is a fixed vocabulary, and the
33 /// formatter reads the literal from it rather than accepting a string that
34 /// could carry a quote into a JS source position.
35 channel: capabilities.Channel = @fromBackingInt(@intCast(0)),
36 /// The `detail` payload as JSON. Owned; freed after delivery.
37 detail: ?[]u8 = null,
38};
39
40/// Events can burst — a location subscription at high accuracy fires several
41/// times a second, and a page that has stopped listening still costs a hop.
42/// Sixteen deep matches the async pool; beyond that the oldest queued event is
43/// dropped in favour of the newest, which is the right trade for a stream
44/// whose consumer wants current state rather than history.
45const max_queued = 16;
46
47var queue: [max_queued]Pending = @splat(.{});
48var queue_mutex: compat_mutex.Mutex = .{};
49
50/// How many events were dropped because the queue was full.
51///
52/// Counted rather than logged per-drop: a saturated stream would otherwise
53/// produce a log line per event and drown the thing being diagnosed. Read it
54/// when a page reports missing updates.
55var dropped: usize = 0;
56
57pub fn droppedCount() usize {
58 queue_mutex.lock();
59 defer queue_mutex.unlock();
60 return dropped;
61}
62
63const dispatch_function_t = *const fn (?*anyopaque) callconv(.c) void;
64extern "c" fn dispatch_async_f(queue_ref: *anyopaque, context: ?*anyopaque, work: dispatch_function_t) void;
65extern var _dispatch_main_q: anyopaque;
66
67/// Emit `channel` with `detail_json` as the event's `detail`.
68///
69/// Safe to call from any thread. `detail_json` must be a complete JSON value —
70/// an object literal is the convention — and is copied, because the caller is
71/// typically a delegate callback whose buffer dies on return.
72///
73/// A full queue drops the *oldest* pending event rather than refusing the new
74/// one. For a stream, stale data is worse than a gap.
75pub fn emit(channel: capabilities.Channel, detail_json: []const u8) void {
76 if (!builtin.target.os.tag.isDarwin()) return;
77
78 const allocator = std.heap.c_allocator;
79 const copy = allocator.dupe(u8, detail_json) catch {
80 // Nothing to deliver and nobody to tell — an event has no promise
81 // waiting on it. Counted so a page reporting gaps has something to
82 // point at.
83 queue_mutex.lock();
84 defer queue_mutex.unlock();
85 dropped += 1;
86 return;
87 };
88
89 var index: usize = undefined;
90 {
91 queue_mutex.lock();
92 defer queue_mutex.unlock();
93
94 index = findFreeSlot() orelse blk: {
95 // Evict the oldest. Slot 0 is as good as any: the queue is drained
96 // in index order, so it holds the least recently delivered.
97 if (queue[0].detail) |old| allocator.free(old);
98 queue[0] = .{};
99 dropped += 1;
100 break :blk 0;
101 };
102
103 queue[index] = .{ .in_use = true, .channel = channel, .detail = copy };
104 }
105
106 // Marking the channel live is what makes `craft.capabilities()` answer
107 // truthfully. Done on emit rather than on subscribe, because a channel
108 // nothing has ever fired is not knowably live.
109 _ = capabilities.registerEmitter(channel);
110
111 dispatch_async_f(&_dispatch_main_q, @ptrFromInt(index + 1), deliverOnMain);
112}
113
114fn findFreeSlot() ?usize {
115 for (&queue, 0..) |*slot, i| {
116 if (!slot.in_use) return i;
117 }
118 return null;
119}
120
121fn deliverOnMain(context: ?*anyopaque) callconv(.c) void {
122 const index: usize = @intFromPtr(context orelse return) - 1;
123 if (index >= max_queued) return;
124
125 var channel: capabilities.Channel = undefined;
126 var detail: ?[]u8 = null;
127 {
128 queue_mutex.lock();
129 defer queue_mutex.unlock();
130 const slot = &queue[index];
131 if (!slot.in_use) return; // evicted before this hop ran
132 channel = slot.channel;
133 detail = slot.detail;
134 slot.* = .{};
135 }
136
137 const allocator = std.heap.c_allocator;
138 const payload = detail orelse return;
139 defer allocator.free(payload);
140
141 const js = formatEvent(allocator, channel, payload) catch return;
142 defer allocator.free(js);
143
144 const ios_dispatch = @import("ios_dispatch.zig");
145 ios_dispatch.evalJS(js) catch |err| {
146 std.log.warn("ios events: could not emit {s}: {}", .{ channel.eventName(), err });
147 };
148}
149
150/// The `dispatchEvent` call for one event.
151///
152/// The detail is inlined as a JSON literal, not as a quoted string: it is
153/// already JSON, and wrapping it would make the page parse a string containing
154/// an object. The `if (window.dispatchEvent)` guard mirrors the desktop's, for
155/// a document torn down between the emit and the hop.
156///
157/// Split out from `deliverOnMain` so the exact bytes are testable without a
158/// webview or a run loop.
159fn formatEvent(
160 allocator: std.mem.Allocator,
161 channel: capabilities.Channel,
162 detail_json: []const u8,
163) ![]u8 {
164 return std.fmt.allocPrint(
165 allocator,
166 "if(window.dispatchEvent)window.dispatchEvent(new CustomEvent('{s}',{⁠{detail:{s}}}));",
167 .{ channel.eventName(), detail_json },
168 );
169}
170
171const testing = std.testing;
172
173test "an event inlines its detail as JSON, not as a quoted string" {
174 // Quoting it would hand the page a string that happens to contain an
175 // object, so `e.detail.latitude` would be undefined and the subscriber
176 // would read it as a missing reading rather than a bug.
177 const js = try formatEvent(testing.allocator, .location_update, "{\"latitude\":1.5}");
178 defer testing.allocator.free(js);
179
180 try testing.expectEqualStrings(
181 "if(window.dispatchEvent)window.dispatchEvent(new CustomEvent('craft:location:update',{detail:{\"latitude\":1.5}}));",
182 js,
183 );
184}
185
186test "the event name comes from the enum, so a page cannot influence it" {
187 // The name lands in a JS source position. Taking it from the Channel enum
188 // rather than a caller-supplied string is what makes escaping unnecessary
189 // there — this pins that the formatter reads the enum.
190 try testing.expectEqualStrings("craft:location:error", capabilities.Channel.location_error.eventName());
191 try testing.expectEqualStrings("craft:location:authChanged", capabilities.Channel.location_authchanged.eventName());
192}
193
194test "a full queue drops the oldest event and counts it" {
195 // A stream's consumer wants current state. Refusing the newest reading to
196 // preserve a stale one is the wrong trade, but a silent drop is worse than
197 // a counted one.
198 if (!builtin.target.os.tag.isDarwin()) return error.SkipZigTest;
199
200 const before = droppedCount();
201
202 queue_mutex.lock();
203 for (&queue) |*slot| {
204 if (!slot.in_use) {
205 slot.* = .{ .in_use = true, .channel = .location_update, .detail = null };
206 }
207 }
208 queue_mutex.unlock();
209
210 // No free slot: this must evict rather than block or leak.
211 emit(.location_update, "{\"n\":1}");
212
213 try testing.expect(droppedCount() > before);
214
215 queue_mutex.lock();
216 defer queue_mutex.unlock();
217 for (&queue) |*slot| {
218 if (slot.detail) |owned| std.heap.c_allocator.free(owned);
219 slot.* = .{};
220 }
221}
222
223test "emitting marks the channel live for craft.capabilities()" {
224 if (!builtin.target.os.tag.isDarwin()) return error.SkipZigTest;
225
226 // A channel nothing has fired is honestly unknown; one that has fired is
227 // knowably live. This is the only thing that moves it.
228 const emitter = capabilities.registerEmitter(.location_update);
229 try testing.expectEqualStrings("craft:location:update", emitter.eventName());
230}