Tests/OrgAppTests/CommandHostTests.swift
282 lines · 15322 bytes
1import Foundation
2import Network
3import Testing
4import WebKit
5@testable import OrgApp
6
7/// A local port that counts the connections made to it, to show a load never left the web view.
8final class Listener: @unchecked Sendable {
9 private let listener: NWListener
10 private let counter = Counter()
11 let port: UInt16
12 var connections: Int { counter.value }
13 var url: String { "http://127.0.0.1:\(port)/" }
14
15 final class Counter: @unchecked Sendable {
16 private let lock = NSLock()
17 private var count = 0
18 var value: Int { lock.withLock { count } }
19 func add() { lock.withLock { count += 1 } }
20 }
21
22 init() async throws {
23 let parameters = NWParameters.tcp
24 parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any)
25 let listener = try NWListener(using: parameters)
26 let counter = counter
27 listener.newConnectionHandler = { connection in
28 counter.add()
29 connection.cancel()
30 }
31 let ready = AsyncStream<UInt16> { continuation in
32 listener.stateUpdateHandler = { state in
33 if case .ready = state { continuation.yield(listener.port?.rawValue ?? 0); continuation.finish() }
34 }
35 }
36 listener.start(queue: .global())
37 var port: UInt16 = 0
38 for await value in ready { port = value }
39 self.listener = listener
40 self.port = port
41 }
42
43 deinit { listener.cancel() }
44}
45
46@MainActor
47@Suite(.serialized)
48struct CommandHostTests {
49 let folder: Folder
50 let host: CommandHost
51
52 init() throws {
53 folder = try Folder()
54 host = CommandHost(folder: folder.url.appendingPathComponent("commands"))
55 try folder.write("commands/util.js", "export const twice = s => s + s;\n")
56 try folder.write("commands/main.js", """
57 import { twice } from "./util.js";
58 export function echo(context) { return context; }
59 export async function double(context) { return { text: twice(context.text) }; }
60 export function nothing() {}
61 export function fails() { throw new Error("no heading here"); }
62 export function loop() { for (;;) {} }
63 export function counter() { globalThis.count = (globalThis.count ?? 0) + 1; return globalThis.count; }
64 export async function ask(context, call) { return [await call("prompt", context), await call("message", "hi")]; }
65 export async function refused(context, call) {
66 try { await call("nope", null); } catch (e) { return "caught " + e.message; }
67 }
68 export async function waits(context, call) { await call("wait", null); return "done"; }
69 """)
70 }
71
72 @Test func runsAnExportedFunction() async throws {
73 #expect(try await host.run(module: "main.js", function: "double", context: #"{"text": "ab"}"#) == #"{"text":"abab"}"#)
74 #expect(try await host.run(module: "main.js", function: "echo", context: #"[1, "é", null]"#) == #"[1,"é",null]"#)
75 #expect(try await host.run(module: "main.js", function: "nothing", context: "{}") == "null")
76 await #expect(throws: CommandHost.Failure.script("no heading here")) {
77 _ = try await host.run(module: "main.js", function: "fails", context: "{}")
78 }
79 await #expect(throws: CommandHost.Failure.script("main.js exports no function absent.")) {
80 _ = try await host.run(module: "main.js", function: "absent", context: "{}")
81 }
82 await #expect(throws: CommandHost.Failure.script("No module ../main.js in commands/.")) {
83 _ = try await host.run(module: "../main.js", function: "echo", context: "{}")
84 }
85 }
86
87 /// Each run has a new worker: nothing a command leaves in the global scope reaches the next,
88 /// and a changed file is read again.
89 @Test func runsDontShareState() async throws {
90 #expect(try await host.run(module: "main.js", function: "counter", context: "{}") == "1")
91 #expect(try await host.run(module: "main.js", function: "counter", context: "{}") == "1")
92 try folder.write("commands/util.js", "export const twice = s => s + s + s;\n")
93 #expect(try await host.run(module: "main.js", function: "double", context: #"{"text": "a"}"#) == #"{"text":"aaa"}"#)
94 }
95
96 @Test func callsTheApp() async throws {
97 var seen: [String] = []
98 host.calls = { name, value in
99 seen.append(name)
100 switch name {
101 case "prompt": return "answer to \((value as? [String: Any])?["message"] ?? "")"
102 case "message": return NSNull()
103 default: throw CommandHost.Failure.script("No call \(name).")
104 }
105 }
106 #expect(try await host.run(module: "main.js", function: "ask", context: #"{"message": "Week"}"#) == #"["answer to Week",null]"#)
107 #expect(seen == ["prompt", "message"])
108 #expect(try await host.run(module: "main.js", function: "refused", context: "{}") == #""caught No call nope.""#)
109 }
110
111 /// Time the app spends answering a call, as in a prompt, isn't counted.
112 @Test func timeInACallDoesntCount() async throws {
113 host.calls = { _, _ in
114 try await Task.sleep(for: .milliseconds(1500))
115 return NSNull()
116 }
117 #expect(try await host.run(module: "main.js", function: "waits", context: "{}", timeout: .seconds(1)) == #""done""#)
118 }
119
120 @Test func stopsAnEndlessLoopAndRunsAgain() async throws {
121 let start = ContinuousClock.now
122 await #expect(throws: CommandHost.Failure.timedOut(.seconds(1))) {
123 _ = try await host.run(module: "main.js", function: "loop", context: "{}", timeout: .seconds(1))
124 }
125 #expect(try await host.run(module: "main.js", function: "echo", context: "7") == "7")
126 // The same web view: only the worker was ended.
127 #expect(host.engine != nil)
128 #expect(ContinuousClock.now - start < .seconds(10))
129 }
130
131 @Test func cancels() async throws {
132 let task = Task { try await host.run(module: "main.js", function: "loop", context: "{}", timeout: .seconds(30)) }
133 try await Task.sleep(for: .milliseconds(300))
134 task.cancel()
135 await #expect(throws: CancellationError.self) { _ = try await task.value }
136 #expect(try await host.run(module: "main.js", function: "echo", context: "8") == "8")
137 }
138
139 @Test func importsOnlyFromTheCommandsFolder() async throws {
140 try folder.write("outside.js", "export const secret = 1;\n")
141 try folder.write("commands/escape.js", """
142 export async function parent() { return (await import("../outside.js")).secret; }
143 export async function absolute() { return (await import("/outside.js")).secret; }
144 export async function file(path) { return (await import("file://" + path)).secret; }
145 export async function data() { return (await import("data:text/javascript,export const secret = 1")).secret; }
146 """)
147 for function in ["parent", "absolute", "data"] {
148 await #expect(throws: CommandHost.Failure.self, "\(function)") {
149 _ = try await host.run(module: "escape.js", function: function, context: "{}")
150 }
151 }
152 await #expect(throws: CommandHost.Failure.self) {
153 _ = try await host.run(module: "escape.js", function: "file", context: "\"\(folder.url.appendingPathComponent("outside.js").path)\"")
154 }
155 }
156
157 @Test func refusesSymlinksOutOfTheCommandsFolder() async throws {
158 try folder.write("secret.js", "export function echo(c) { return c; }\n")
159 try folder.write("lib/inner.js", "export function echo(c) { return c; }\n")
160 let commands = folder.url.appendingPathComponent("commands")
161 try FileManager.default.createSymbolicLink(atPath: commands.appendingPathComponent("link.js").path, withDestinationPath: "../secret.js")
162 try FileManager.default.createSymbolicLink(atPath: commands.appendingPathComponent("lib").path, withDestinationPath: folder.url.appendingPathComponent("lib").path)
163 try FileManager.default.createSymbolicLink(atPath: commands.appendingPathComponent("same.js").path, withDestinationPath: "main.js")
164 await #expect(throws: CommandHost.Failure.self) { _ = try await host.run(module: "link.js", function: "echo", context: "1") }
165 await #expect(throws: CommandHost.Failure.self) { _ = try await host.run(module: "lib/inner.js", function: "echo", context: "1") }
166 #expect(try await host.run(module: "same.js", function: "echo", context: "1") == "1")
167 #expect(CommandHost.Files.file("link.js", in: commands) == nil)
168 #expect(CommandHost.Files.file("lib/inner.js", in: commands) == nil)
169 #expect(CommandHost.Files.file("main.js", in: commands) != nil)
170 #expect(CommandHost.Files.file("../secret.js", in: commands) == nil)
171 #expect(CommandHost.Files.file("util.txt", in: commands) == nil)
172 }
173
174 /// The worker has none of the ways out, and nothing reaches a local port: not from a command,
175 /// not from a worker with its globals intact, not from the page.
176 @Test func reachesNoNetwork() async throws {
177 let listener = try await Listener()
178 try folder.write("commands/net.js", """
179 export function globals() {
180 return ["fetch", "XMLHttpRequest", "WebSocket", "EventSource", "importScripts", "indexedDB", "caches", "Worker"].filter(n => n in self);
181 }
182 export async function load(url) { return (await import(url)).x; }
183 export async function fetched(url) { return await fetch(url); }
184 export async function requested(url) { const r = new XMLHttpRequest(); r.open("GET", url, false); r.send(); }
185 export async function socket(url) { new WebSocket(url.replace("http", "ws")); }
186 """)
187 try folder.write("commands/probe.js", """
188 const url = "\(listener.url)";
189 const tries = [
190 () => fetch(url, { mode: "no-cors" }),
191 () => { const r = new XMLHttpRequest(); r.open("GET", url, false); r.send(); },
192 () => new WebSocket(url.replace("http", "ws")),
193 () => new EventSource(url),
194 () => import(url + "x.js"),
195 ];
196 Promise.allSettled(tries.map(t => { try { return Promise.resolve(t()); } catch (e) { return Promise.reject(e); } }))
197 .then(r => postMessage(r.map(x => x.status)));
198 """)
199 #expect(try await host.run(module: "net.js", function: "globals", context: "{}") == "[]")
200 for function in ["load", "fetched", "requested", "socket"] {
201 await #expect(throws: CommandHost.Failure.self, "\(function)") {
202 _ = try await host.run(module: "net.js", function: function, context: "\"\(listener.url)x.js\"")
203 }
204 }
205 let webView = try #require(host.engine?.webView)
206 let probed = try await webView.callAsyncJavaScript("""
207 const w = new Worker("commands/probe.js", { type: "module" });
208 return await new Promise(r => { w.onmessage = e => r(e.data); w.onerror = e => r(["error", e.message]); });
209 """, contentWorld: .page)
210 print("A worker with its globals: \(probed ?? "nothing")")
211 _ = try? await webView.callAsyncJavaScript("await fetch(url, { mode: 'no-cors' });", arguments: ["url": listener.url], contentWorld: .page)
212 _ = try? await webView.callAsyncJavaScript("await fetch(url, { mode: 'no-cors' });", arguments: ["url": listener.url], contentWorld: .defaultClient)
213 try await Task.sleep(for: .milliseconds(500))
214 #expect(listener.connections == 0)
215 }
216
217 /// The content rule list alone blocks a load the same web view makes without it.
218 @Test func ruleListBlocksOtherLoads() async throws {
219 let listener = try await Listener()
220 func connects(_ rules: WKContentRuleList?) async throws -> Bool {
221 let before = listener.connections
222 let configuration = WKWebViewConfiguration()
223 configuration.websiteDataStore = .nonPersistent()
224 if let rules { configuration.userContentController.add(rules) }
225 let webView = WKWebView(frame: .zero, configuration: configuration)
226 _ = try? await webView.callAsyncJavaScript("await fetch(url, { mode: 'no-cors' });", arguments: ["url": listener.url], contentWorld: .page)
227 try await Task.sleep(for: .milliseconds(300))
228 return listener.connections > before
229 }
230 #expect(try await connects(nil))
231 #expect(try await !connects(CommandHost.Engine.rules()))
232 }
233
234 @Test func recoversWhenTheContentProcessEnds() async throws {
235 #expect(try await host.run(module: "main.js", function: "echo", context: "1") == "1")
236 let webView = try #require(host.engine?.webView)
237 // Ended from outside, as the system ends a process that runs out of memory.
238 let pid = try #require(webView.value(forKey: "_webProcessIdentifier") as? Int32)
239 try #require(pid > 0)
240 let task = Task { try await host.run(module: "main.js", function: "loop", context: "{}", timeout: .seconds(10)) }
241 try await Task.sleep(for: .milliseconds(300))
242 kill(pid, SIGKILL)
243 await #expect(throws: CommandHost.Failure.stopped) { _ = try await task.value }
244 #expect(host.engine == nil)
245 #expect(try await host.run(module: "main.js", function: "echo", context: "2") == "2")
246 }
247
248 @Test func unloadsWhenIdle() async throws {
249 let host = CommandHost(folder: folder.url.appendingPathComponent("commands"), idle: .milliseconds(200))
250 #expect(try await host.run(module: "main.js", function: "echo", context: "1") == "1")
251 #expect(host.engine != nil)
252 try await Task.sleep(for: .seconds(1))
253 #expect(host.engine == nil)
254 }
255
256 /// Prints first start, a warm round trip and a round trip carrying 1 MB each way.
257 @Test func measures() async throws {
258 host.unload()
259 var start = ContinuousClock.now
260 _ = try await host.run(module: "main.js", function: "echo", context: "1")
261 let first = ContinuousClock.now - start
262 func median(_ times: Int, _ body: () async throws -> Void) async rethrows -> Duration {
263 var all: [Duration] = []
264 for _ in 0..<times {
265 start = .now
266 try await body()
267 all.append(ContinuousClock.now - start)
268 try? await Task.sleep(for: .milliseconds(50))
269 }
270 return all.sorted()[times / 2]
271 }
272 let warm = try await median(21) { _ = try await host.run(module: "main.js", function: "echo", context: "1") }
273 let megabyte = String(repeating: "* Heading\nSome text é\n", count: 1_048_576 / 23)
274 let context = String(data: try JSONSerialization.data(withJSONObject: ["text": megabyte]), encoding: .utf8)!
275 let large = try await median(9) {
276 let reply = try await host.run(module: "main.js", function: "echo", context: context)
277 #expect(reply.count == context.count)
278 }
279 print("Command host: first start \(first), warm round trip \(warm), 1 MB round trip \(large)")
280 }
281}
282