@tokamakdev/platform-macos-x64 0.1.1-beta.162 → 0.1.1-beta.163

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.
@@ -39,14 +39,15 @@ typedef struct {
39
39
 
40
40
  void *tokamak_runtime_start(const char *packaged_dir, const char *state_dir,
41
41
  const char *storage_dir, const char *host,
42
- bool foreground, TokamakPluginHandler plugins,
43
- char *error, size_t error_len);
42
+ TokamakPluginHandler plugins, char *error,
43
+ size_t error_len);
44
44
  void *tokamak_runtime_start_development(const char *state_dir, const char *host,
45
45
  const char *endpoint,
46
46
  const char *session_token,
47
- bool foreground,
48
47
  TokamakPluginHandler plugins,
49
48
  char *error, size_t error_len);
49
+ bool tokamak_has_handler(const char *packaged_dir, const char *handler);
50
+ void tokamak_runtime_deliver_start(const void *runtime, bool foreground);
50
51
  uint16_t tokamak_runtime_port(const void *runtime);
51
52
  uint16_t tokamak_runtime_await_port_change(const void *runtime, uint16_t known,
52
53
  uint64_t timeout_ms);
@@ -8,8 +8,10 @@ import WebKit
8
8
  #endif
9
9
 
10
10
  private let startupErrorFile = "startup-error.log"
11
- /// How long the Worker has for `resume` and `suspend`.
11
+ /// How long the Worker has for `_onResume` and `_onSuspend`.
12
12
  private let lifecycleDeadline: TimeInterval = 10
13
+ /// How long launch waits for the Worker's `_beforeStart`.
14
+ private let beforeStartDeadline: TimeInterval = 1
13
15
  #if os(iOS)
14
16
  /// The system gives an app about 30 seconds after it leaves the foreground.
15
17
  private let suspendDeadline: TimeInterval = 25
@@ -28,7 +30,7 @@ final class TokamakApp: TokamakHostApp {
28
30
  private var waiting: [(Result<RuntimeHandle, Error>) -> Void] = []
29
31
  /// The Worker's calls and subscriptions on the plugins.
30
32
  private var workerRequests: TokamakPluginRequests<UInt64>!
31
- /// Delivers `resume` and `suspend` one at a time, in order.
33
+ /// Delivers `_onResume` and `_onSuspend` one at a time, in order.
32
34
  private let lifecycle = DispatchQueue(label: "tokamak.lifecycle")
33
35
  #if os(iOS)
34
36
  /// The scenes in the foreground.
@@ -55,14 +57,39 @@ final class TokamakApp: TokamakHostApp {
55
57
  })
56
58
  }
57
59
 
58
- /// Starts the runtime in the background, which delivers `start` with
59
- /// `foreground`. Call it once, on the main thread.
60
- func start(foreground: Bool) {
60
+ /// Starts the runtime in the background. When the Worker receives
61
+ /// `_beforeStart`, waits until it returns or its deadline passes, running
62
+ /// the plugin calls it makes on the main thread. Call it once, on the main
63
+ /// thread, inside the platform's launch.
64
+ func start() {
61
65
  dispatchPrecondition(condition: .onQueue(.main))
62
66
  let plugins = workerPlugins
63
- DispatchQueue.global(qos: .userInitiated).async {
64
- let result = Result { try RuntimeHandle(foreground: foreground, plugins: plugins) }
65
- DispatchQueue.main.async { self.started(result) }
67
+ let waits = RuntimeHandle.receivesBeforeStart
68
+ let deadline = Date() + beforeStartDeadline
69
+ let launch = {
70
+ let result = Result { try RuntimeHandle(plugins: plugins) }
71
+ TokamakMainThread.post { self.started(result) }
72
+ guard waits, case .success(let runtime) = result else { return }
73
+ do {
74
+ _ = try runtime.emit(
75
+ "_beforeStart", payload: Data("{}".utf8), timeout: deadline.timeIntervalSinceNow)
76
+ } catch {
77
+ print("tokamak _beforeStart failed: \(error)")
78
+ }
79
+ }
80
+ if waits {
81
+ TokamakMainThread.run(until: deadline, work: launch)
82
+ } else {
83
+ DispatchQueue.global(qos: .userInitiated).async(execute: launch)
84
+ }
85
+ }
86
+
87
+ /// Records whether the app starts in the `foreground` and delivers
88
+ /// `_onStart` with it, once the runtime has started. Call it once, on the
89
+ /// main thread, after the platform's launch.
90
+ func deliverStart(foreground: Bool) {
91
+ ready { started in
92
+ if case .success(let runtime) = started { runtime.deliverStart(foreground: foreground) }
66
93
  }
67
94
  }
68
95
 
@@ -124,10 +151,10 @@ final class TokamakApp: TokamakHostApp {
124
151
  }
125
152
 
126
153
  /// Delivers the event `name`, whose encoded data is `payload`, to the
127
- /// Worker's listeners, and calls `completion` on the main thread with their
128
- /// encoded reply, which is empty when none replied. Fails unless they
129
- /// return within `timeout`, which includes runtime startup. Call it on the
130
- /// main thread.
154
+ /// Worker's method of that name, and calls `completion` on the main thread
155
+ /// with its encoded reply, which is empty when it returns nothing. Fails
156
+ /// unless it returns within `timeout`, which includes runtime startup. Call
157
+ /// it on the main thread.
131
158
  func emit(
132
159
  _ name: String,
133
160
  payload: Data,
@@ -188,10 +215,10 @@ final class TokamakApp: TokamakHostApp {
188
215
  }
189
216
 
190
217
  /// Records the app moving into or out of the foreground once the runtime
191
- /// has started, and delivers `resume` or `suspend` when that changed its
192
- /// stage. Call it on the main thread.
218
+ /// has started, and delivers `_onResume` or `_onSuspend` when that changed
219
+ /// its stage. Call it on the main thread.
193
220
  func moved(toForeground foreground: Bool) {
194
- let name = foreground ? "resume" : "suspend"
221
+ let name = foreground ? "_onResume" : "_onSuspend"
195
222
  #if os(iOS)
196
223
  // The system suspends the app soon after it leaves the foreground
197
224
  // unless a background task holds it there.
@@ -225,7 +252,7 @@ final class TokamakApp: TokamakHostApp {
225
252
  }
226
253
 
227
254
  #if os(iOS)
228
- /// Delivers `resume` as the first scene enters the foreground.
255
+ /// Delivers `_onResume` as the first scene enters the foreground.
229
256
  func sceneWillEnterForeground() {
230
257
  foregroundScenes += 1
231
258
  if foregroundScenes == 1 {
@@ -233,7 +260,7 @@ final class TokamakApp: TokamakHostApp {
233
260
  }
234
261
  }
235
262
 
236
- /// Delivers `suspend` as the last scene leaves the foreground.
263
+ /// Delivers `_onSuspend` as the last scene leaves the foreground.
237
264
  func sceneDidEnterBackground() {
238
265
  foregroundScenes -= 1
239
266
  if foregroundScenes == 0 {
@@ -320,9 +347,18 @@ final class RuntimeHandle {
320
347
  let appHost: String
321
348
  private var handle: UnsafeMutableRawPointer?
322
349
 
323
- /// Starts the runtime, which delivers `start` with `foreground`, and whose
324
- /// Worker calls `plugins`.
325
- init(foreground: Bool, plugins: TokamakPluginHandler) throws {
350
+ /// Whether the Worker receives `_beforeStart`: its packaged class has that
351
+ /// method, or it runs in the development server, which receives every event.
352
+ static var receivesBeforeStart: Bool {
353
+ if Bundle.main.object(forInfoDictionaryKey: "TokamakDevEndpoint") is String { return true }
354
+ guard let app = Bundle.main.resourceURL?.appendingPathComponent("app") else { return false }
355
+ return app.path.withCString { app in
356
+ "_beforeStart".withCString { tokamak_has_handler(app, $0) }
357
+ }
358
+ }
359
+
360
+ /// Starts the runtime, whose Worker calls `plugins`.
361
+ init(plugins: TokamakPluginHandler) throws {
326
362
  guard let appHost = Bundle.main.tokamakHost, !appHost.isEmpty else {
327
363
  throw RuntimeError(description: "TokamakHost is required")
328
364
  }
@@ -344,7 +380,6 @@ final class RuntimeHandle {
344
380
  appHost,
345
381
  endpoint,
346
382
  sessionToken,
347
- foreground,
348
383
  plugins,
349
384
  error.baseAddress,
350
385
  error.count
@@ -370,7 +405,6 @@ final class RuntimeHandle {
370
405
  statePath,
371
406
  storagePath,
372
407
  appHost,
373
- foreground,
374
408
  plugins,
375
409
  error.baseAddress,
376
410
  error.count
@@ -415,9 +449,16 @@ final class RuntimeHandle {
415
449
  return port
416
450
  }
417
451
 
452
+ /// Records whether the app starts in the `foreground`, and delivers
453
+ /// `_onStart` with it in the background.
454
+ func deliverStart(foreground: Bool) {
455
+ tokamak_runtime_deliver_start(handle, foreground)
456
+ }
457
+
418
458
  /// Delivers the event `name`, whose encoded data is `payload`, to the
419
- /// Worker's listeners, blocking until they return or `timeout` passes, and
420
- /// returns their encoded reply, which is empty when none replied.
459
+ /// Worker's method of that name, blocking until it returns or `timeout`
460
+ /// passes, and returns its encoded reply, which is empty when it returns
461
+ /// nothing.
421
462
  func emit(_ name: String, payload: Data, timeout: TimeInterval) throws -> Data {
422
463
  var reply = TokamakBytes()
423
464
  var error = [CChar](repeating: 0, count: 1024)
@@ -361,6 +361,7 @@ private final class TokamakController {
361
361
  private var visible = false
362
362
 
363
363
  func applicationDidFinishLaunching(_ notification: Notification) {
364
+ app.start()
364
365
  let window = NSWindow(
365
366
  contentRect: NSRect(x: 0, y: 0, width: 1024, height: 768),
366
367
  styleMask: [.titled, .closable, .miniaturizable, .resizable],
@@ -374,7 +375,7 @@ private final class TokamakController {
374
375
  NSApplication.shared.activate(ignoringOtherApps: true)
375
376
  self.window = window
376
377
  visible = !NSApplication.shared.isHidden
377
- app.start(foreground: visible)
378
+ app.deliverStart(foreground: visible)
378
379
  observeVisibility()
379
380
 
380
381
  guard let content = window.contentView else { return }
@@ -477,14 +478,15 @@ private final class TokamakController {
477
478
  /// Exists from launch, whether or not a scene connects.
478
479
  let app = TokamakApp()
479
480
 
480
- /// Starts the runtime once launch finishes. A scene a user launches the
481
- /// app into has entered the foreground by then.
481
+ /// Starts the runtime, and delivers `_onStart` once launch finishes. A
482
+ /// scene a user launches the app into has entered the foreground by then.
482
483
  func application(
483
484
  _ application: UIApplication,
484
485
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
485
486
  ) -> Bool {
487
+ app.start()
486
488
  DispatchQueue.main.async {
487
- self.app.start(foreground: self.app.hasForegroundScene)
489
+ self.app.deliverStart(foreground: self.app.hasForegroundScene)
488
490
  }
489
491
  return true
490
492
  }
@@ -13,7 +13,7 @@ public protocol TokamakExports: TokamakPlugin {
13
13
  /// `event` as the JSON data of the event `name`, which the registration lists.
14
14
  func eventPayload(_ name: String, _ event: Any) throws(TokamakPluginError) -> Data
15
15
 
16
- /// The listeners' JSON `reply` to the event `name`, which the registration
16
+ /// The handler's JSON `reply` to the event `name`, which the registration
17
17
  /// lists with a reply, as its type, or nil for null.
18
18
  func eventReply(_ name: String, _ reply: Data) throws(TokamakPluginError) -> Any?
19
19
  }
@@ -40,10 +40,11 @@ public enum TokamakOverflow {
40
40
  /// replies are `Decodable`, method results and events `Encodable`, and options
41
41
  /// literal values.
42
42
  public struct TokamakExporter<Plugin> {
43
- /// Lists the event `name`, whose listeners receive an `E`.
43
+ /// Lists the event `name`: the Worker's method `name`, which starts with
44
+ /// `_`, receives an `E`.
44
45
  public mutating func event<E: Encodable>(_ name: String, _ type: E.Type, doc: String = "") {}
45
46
 
46
- /// Lists the event `name`, whose listeners receive an `E` and may reply with an `R`.
47
+ /// Lists the event `name`, whose handler receives an `E` and may reply with an `R`.
47
48
  public mutating func event<E: Encodable, R: Decodable>(
48
49
  _ name: String, _ type: E.Type, reply: R.Type, doc: String = ""
49
50
  ) {}
@@ -333,7 +334,7 @@ public func tokamakEncode<T: Encodable>(
333
334
  }
334
335
  }
335
336
 
336
- /// `event` as the JSON data of the event `name`, whose listeners receive a `T`.
337
+ /// `event` as the JSON data of the event `name`, whose handler receives a `T`.
337
338
  public func tokamakEvent<T: Encodable>(
338
339
  _ name: String, _ event: Any, as type: T.Type
339
340
  ) throws(TokamakPluginError) -> Data {
@@ -125,9 +125,9 @@ public protocol TokamakHostApp: AnyObject {
125
125
  #endif
126
126
 
127
127
  /// Delivers the event `name`, whose encoded data is `payload`, to the
128
- /// Worker's listeners, and calls `completion` on the main thread with their
129
- /// encoded reply, which is empty when none replied. Fails unless they return
130
- /// within `timeout`, which includes runtime startup.
128
+ /// Worker's method of that name, and calls `completion` on the main thread
129
+ /// with its encoded reply, which is empty when it returns nothing. Fails
130
+ /// unless it returns within `timeout`, which includes runtime startup.
131
131
  func emit(
132
132
  _ name: String, payload: Data, timeout: TimeInterval,
133
133
  completion: @escaping (Result<Data, Error>) -> Void)
@@ -183,23 +183,23 @@ public final class TokamakHost {
183
183
  }
184
184
  #endif
185
185
 
186
- /// Delivers the plugin's event `name`, which the Worker's listeners
187
- /// receive as `<plugin>.apple.<name>`, with its encoded `payload`, and calls
188
- /// `completion` on the main thread with their encoded reply, which is empty
189
- /// when none replied. Fails unless they return within `timeout`, which
190
- /// includes runtime startup. Call it on the main thread.
186
+ /// Delivers the plugin's event `name` to the Worker's method of that name,
187
+ /// with its encoded `payload`, and calls `completion` on the main thread
188
+ /// with the method's encoded reply, which is empty when it returns nothing.
189
+ /// Fails unless it returns within `timeout`, which includes runtime
190
+ /// startup. Call it on the main thread.
191
191
  public func emitBytes(
192
192
  _ name: String,
193
193
  payload: Data,
194
194
  timeout: TimeInterval,
195
195
  completion: @escaping (Result<Data, Error>) -> Void
196
196
  ) {
197
- app.emit("\(plugin).apple.\(name)", payload: payload, timeout: timeout, completion: completion)
197
+ app.emit(name, payload: payload, timeout: timeout, completion: completion)
198
198
  }
199
199
 
200
- /// Delivers `event` to the Worker's listeners of the plugin's event `name`,
201
- /// which `Exports.swift` lists, then calls `completion` on the main
202
- /// thread. Fails unless they return within `timeout`, which includes runtime
200
+ /// Delivers `event` to the Worker's method `name`, the plugin's event that
201
+ /// `Exports.swift` lists, then calls `completion` on the main thread. Fails
202
+ /// unless the method returns within `timeout`, which includes runtime
203
203
  /// startup. Call it on the main thread.
204
204
  public func emit(
205
205
  _ name: String,
@@ -210,9 +210,9 @@ public final class TokamakHost {
210
210
  send(name, event, timeout: timeout) { completion($0.map { _ in }) }
211
211
  }
212
212
 
213
- /// `emit` of an event whose listeners may reply, calling `completion` with
213
+ /// `emit` of an event whose handler may reply, calling `completion` with
214
214
  /// the reply as the plugin's generated dispatch decodes it, which is a
215
- /// `Reply`, or nil when none replied.
215
+ /// `Reply`, or nil without one.
216
216
  public func emit<Reply>(
217
217
  _ name: String,
218
218
  event: some Encodable,
@@ -242,7 +242,7 @@ public final class TokamakHost {
242
242
  emitBytes(name, payload: payload, timeout: timeout, completion: completion)
243
243
  }
244
244
 
245
- /// The listeners' `reply` to the event `name` as a `Reply`, or nil when none replied.
245
+ /// The handler's `reply` to the event `name` as a `Reply`, or nil without one.
246
246
  private func decoded<Reply>(
247
247
  _ reply: Data, to name: String, as type: Reply.Type
248
248
  ) throws(TokamakPluginError) -> Reply? {
@@ -426,6 +426,57 @@ public enum TokamakPluginRequest {
426
426
  case call, callWithBody, subscribe
427
427
  }
428
428
 
429
+ /// Work for the main thread. Its queue runs the work, except while the main
430
+ /// thread waits in `run`, which then runs it.
431
+ public enum TokamakMainThread {
432
+ private static let condition = NSCondition()
433
+ /// The work posted while the main thread waits, which is nil otherwise.
434
+ private static var waiting: [() -> Void]?
435
+ private static var finished = false
436
+
437
+ public static func post(_ work: @escaping () -> Void) {
438
+ let taken = condition.withLock {
439
+ waiting?.append(work)
440
+ condition.signal()
441
+ return waiting != nil
442
+ }
443
+ if !taken { DispatchQueue.main.async(execute: work) }
444
+ }
445
+
446
+ /// Blocks the main thread until `work`, which runs on another thread,
447
+ /// returns or `deadline` passes, running the work posted meanwhile.
448
+ public static func run(until deadline: Date, work: @escaping () -> Void) {
449
+ condition.withLock {
450
+ waiting = []
451
+ finished = false
452
+ }
453
+ DispatchQueue.global(qos: .userInitiated).async {
454
+ work()
455
+ condition.withLock {
456
+ finished = true
457
+ condition.signal()
458
+ }
459
+ }
460
+ condition.lock()
461
+ while !finished {
462
+ if let posted = waiting?.first {
463
+ waiting?.removeFirst()
464
+ condition.unlock()
465
+ posted()
466
+ condition.lock()
467
+ } else if !condition.wait(until: deadline) {
468
+ break
469
+ }
470
+ }
471
+ let rest = waiting ?? []
472
+ waiting = nil
473
+ condition.unlock()
474
+ for posted in rest {
475
+ DispatchQueue.main.async(execute: posted)
476
+ }
477
+ }
478
+ }
479
+
429
480
  /// Runs the Worker's requests on the executor each plugin chooses, and passes
430
481
  /// replies straight to the runtime.
431
482
  public final class TokamakPluginRequests<Key: Hashable> {
@@ -477,7 +528,7 @@ public final class TokamakPluginRequests<Key: Hashable> {
477
528
  send(key, result)
478
529
  if subscribe && result.done { cancel(request) }
479
530
  }
480
- request.queue.async { [self] in
531
+ let start = { [self] in
481
532
  guard isPending(key, request) else { return }
482
533
  do throws(TokamakPluginError) {
483
534
  if subscribe {
@@ -494,6 +545,11 @@ public final class TokamakPluginRequests<Key: Hashable> {
494
545
  if remove(key, request) { send(key, TokamakPluginResult(.failure(error), done: true)) }
495
546
  }
496
547
  }
548
+ if request.queue === DispatchQueue.main {
549
+ TokamakMainThread.post(start)
550
+ } else {
551
+ request.queue.async(execute: start)
552
+ }
497
553
  }
498
554
 
499
555
  /// Answers the pending read of the call `key`'s body with the chunk the
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/macos-x64/tools/tokamak-swift-describe
3
3
  size: 34571400 bytes
4
- sha256: baf549749a8e44b4ebb2dfafd38aa94b23d184566d5d692ae85b7ca2883c0fe6
4
+ sha256: 46bebdce722eeb346ca9d2b3c7ef1b53bdba6bbd69aa3f5366d5db4904be25bc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokamakdev/platform-macos-x64",
3
- "version": "0.1.1-beta.162",
3
+ "version": "0.1.1-beta.163",
4
4
  "description": "The tokamak platform pack for macos-x64",
5
5
  "repository": {
6
6
  "type": "git",