oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/engines/saving-webkit.swift — saving.mjs in WebKit itself (Docs'
2// own, Docs #94, with the page and its ready check from the config): a
3// WKWebView, the engine Safari is, rather than Playwright's build of it.
4// Two scenarios, chosen by the config's "scenario", each reporting the
5// save states the page showed; internal/slidestest/saving_browser_test.go
6// checks the server's side.
7//
8// - "held-link", saving.mjs's own, with the same in-page script (passed
9// in the config): open a document, click a link the server never
10// answers, type.
11// - "back": type, and leave while that save is on the wire (the server
12// answers it late, once the page is in the back/forward cache, which
13// Playwright's WebKit does not keep); come back and type again. WebKit
14// never settles the promise of a keepalive save answered while its page
15// was away, so the editor waited on it forever and nothing typed after
16// coming back was ever sent. With "before" a large paste and a short
17// "awayMs", the page is back while that save and the unload beacon may
18// still hold keepalive's 64KiB, and the resend is refused: that must not
19// read as a failed save.
20//
21// The window is never shown, so the page would be hidden and its timers
22// throttled, as an occluded Safari tab's are; occlusion detection is
23// turned off so the page is visible, as a document someone is typing in
24// is. Built by the test with swiftc; macOS only.
25//
26// As in saving.mjs, nothing waits a fixed time to decide anything: each
27// scenario watches the page at least as long as it used to, then until the
28// server's view of the document (config.state) holds config.want, for at
29// most twenty seconds, and reports whether it did. The page's requests are
30// recorded by the config's trace script and printed on a "SAVING TRACE"
31// line, which the test shows if the scenario fails.
32
33import Cocoa
34import WebKit
35
36struct Config: Decodable {
37 struct Cookie: Decodable {
38 let Name: String
39 let Value: String
40 }
41 let origin: String
42 let doc: String
43 let scenario: String
44 let script: String
45 let typing: [String: String]
46 let type: String
47 let cookies: [Cookie]
48 // trace records the page's requests; state, followed by the sqid, is
49 // the server's view of the document; want is what the server must
50 // hold for the scenario to be done.
51 let trace: String
52 let state: String
53 let want: String
54 let page: String
55 let ready: String
56 // back: what is typed before leaving, and how long the page is away.
57 let before: String?
58 let awayMs: Int?
59}
60
61@MainActor final class Harness: NSObject, NSApplicationDelegate {
62 var window: NSWindow!
63 var web: WKWebView!
64 let config: Config
65
66 init(config: Config) { self.config = config }
67
68 func applicationDidFinishLaunching(_ notification: Notification) {
69 Task {
70 do {
71 try await run()
72 exit(0)
73 } catch {
74 print("SAVING FAILED \(error)")
75 exit(1)
76 }
77 }
78 }
79
80 func js(_ script: String) async throws -> Any? { try await web.evaluateJavaScript(script) }
81
82 func until(_ script: String, seconds: Double) async -> Bool {
83 let end = Date().addingTimeInterval(seconds)
84 while Date() < end {
85 if (try? await js(script)) as? Bool == true { return true }
86 try? await Task.sleep(for: .milliseconds(100))
87 }
88 return false
89 }
90
91 // The fixed pause each scenario's watch replaces, and how long it
92 // waits for the server at most.
93 let watch = 3.0
94 let ceiling = 20.0
95
96 // View is the test server's side of the document: its text, how many
97 // saves it answered while the held link loaded, and every save that
98 // reached it. Asked from here, not from the page.
99 struct View: Decodable {
100 struct Post: Decodable { let status: Int }
101 let text: String
102 let held: Int
103 let posts: [Post]
104 }
105
106 func view() async -> View? {
107 guard let (data, _) = try? await URLSession.shared.data(from: URL(string: config.origin + config.state + config.doc)!) else { return nil }
108 return try? JSONDecoder().decode(View.self, from: data)
109 }
110
111 func holds(_ text: String, _ want: String) -> Bool {
112 want.split(separator: " ").allSatisfy { text.contains($0) }
113 }
114
115 // settle waits for done(view) from since, at least watchFor seconds
116 // and at most the ceiling; it says whether it came, and after how
117 // many milliseconds.
118 func settle(since: Date, watchFor: Double, _ done: (View) -> Bool) async -> (Bool, Int) {
119 while true {
120 let s = Date().timeIntervalSince(since)
121 if s >= watchFor, let v = await view(), done(v) {
122 try? await Task.sleep(for: .milliseconds(250))
123 return (true, Int(s * 1000))
124 }
125 if s >= ceiling { return (false, Int(s * 1000)) }
126 try? await Task.sleep(for: .milliseconds(100))
127 }
128 }
129
130 // report prints the scenario's "SAVING RESULT" and "SAVING TRACE"
131 // lines: the save states the page showed, whether what it waited for
132 // came, and the page's requests.
133 func report(_ engine: String, persisted: Bool? = nil, settled: Bool, ms: Int, waiting: String) async {
134 func read(_ script: String) async -> Any {
135 let s = (try? await js(script)) as? String ?? "[]"
136 return (try? JSONSerialization.jsonObject(with: Data(s.utf8))) ?? []
137 }
138 var result: [String: Any] = ["engine": engine, "states": await read("JSON.stringify(window.__saveStates || [])"), "settled": settled, "ms": ms, "waiting": waiting]
139 if let persisted { result["persisted"] = persisted }
140 let trace: [String: Any] = ["engine": engine, "trace": await read("JSON.stringify(window.__saveTrace || [])")]
141 for (prefix, line) in [("SAVING RESULT ", result), ("SAVING TRACE ", trace)] {
142 let data = try! JSONSerialization.data(withJSONObject: line, options: [.sortedKeys])
143 print(prefix + String(decoding: data, as: UTF8.self))
144 }
145 }
146
147 func run() async throws {
148 setbuf(stdout, nil)
149 let cfg = WKWebViewConfiguration()
150 cfg.websiteDataStore = .nonPersistent()
151 cfg.userContentController.addUserScript(WKUserScript(source: config.trace, injectionTime: .atDocumentStart, forMainFrameOnly: true))
152 let host = URL(string: config.origin)!.host!
153 for c in config.cookies {
154 let cookie = HTTPCookie(properties: [.name: c.Name, .value: c.Value, .domain: host, .path: "/"])!
155 await cfg.websiteDataStore.httpCookieStore.setCookie(cookie)
156 }
157 web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1100, height: 800), configuration: cfg)
158 // A visible page, as one being typed in is (see the header).
159 let occlusion = Selector(("_setWindowOcclusionDetectionEnabled:"))
160 if web.responds(to: occlusion) {
161 typealias Set = @convention(c) (AnyObject, Selector, Bool) -> Void
162 unsafeBitCast(web.method(for: occlusion), to: Set.self)(web, occlusion, false)
163 }
164 window = NSWindow(contentRect: web.frame, styleMask: [.titled], backing: .buffered, defer: false)
165 window.contentView = web
166 let editor = "!!(\(config.ready))"
167 if config.scenario == "back" {
168 try await back(editor)
169 return
170 }
171 web.load(URLRequest(url: URL(string: config.origin + "/d/" + config.doc + config.page)!))
172 guard await until(editor, seconds: 30) else {
173 throw NSError(domain: "the editor never opened", code: 1)
174 }
175 try await Task.sleep(for: .milliseconds(500))
176 let typing = String(data: try JSONEncoder().encode(config.typing), encoding: .utf8)!
177 let since = Date()
178 _ = try await js("(\(config.script))(\(typing)); true")
179 let (settled, ms) = await settle(since: since, watchFor: watch) { holds($0.text, config.want) && $0.held > 0 }
180 await report("wkwebview", settled: settled, ms: ms, waiting: "the server to hold \"\(config.want)\", saved while the link loaded")
181 }
182
183 // back is the "back" scenario (see the header).
184 func back(_ editor: String) async throws {
185 // Away to a page that costs nothing to draw (the documents list lays
186 // out a thumbnail of every document, the large ones included).
187 let list = "location.pathname === '/healthz' && document.readyState === 'complete'"
188 web.load(URLRequest(url: URL(string: config.origin + "/healthz")!))
189 guard await until(list, seconds: 30) else { throw NSError(domain: "the first page never loaded", code: 1) }
190 // From there, so there is a page to come back to (WebKit turns a
191 // navigation before the load event into a replacement).
192 web.load(URLRequest(url: URL(string: config.origin + "/d/" + config.doc + config.page)!))
193 guard await until(editor, seconds: 30) else { throw NSError(domain: "the editor never opened", code: 1) }
194 try await Task.sleep(for: .milliseconds(500))
195 _ = try await js("window.__saveStates = []; new MutationObserver(() => window.__saveStates.push(document.querySelector('[estilo-save-status]').getAttribute('data-state'))).observe(document.querySelector('[estilo-save-status]'), { attributes: true, attributeFilter: ['data-state'] }); addEventListener('pageshow', (e) => { window.__persisted = e.persisted }); true")
196 let beforeText = config.before ?? "Before leaving"
197 let before = String(data: try JSONEncoder().encode([beforeText]), encoding: .utf8)!
198 var since = Date()
199 _ = try await js("(\(config.type))(\(before)[0]); true")
200 // Past the debounce: the save is on the wire, and the server holds it.
201 var (settled, ms) = await settle(since: since, watchFor: 0) { !$0.posts.isEmpty }
202 guard settled else {
203 await report("wkwebview-back", settled: false, ms: ms, waiting: "the save typed before leaving to reach the server")
204 return
205 }
206 web.load(URLRequest(url: URL(string: config.origin + "/healthz")!))
207 guard await until(list, seconds: 30) else { throw NSError(domain: "the document was never left", code: 1) }
208 // The held save is answered while the page is away, or, back
209 // sooner (awayMs), it is still on the wire.
210 if let away = config.awayMs {
211 try await Task.sleep(for: .milliseconds(away))
212 } else {
213 since = Date()
214 (settled, ms) = await settle(since: since, watchFor: 0) { v in holds(v.text, beforeText) && v.posts.allSatisfy { $0.status != 0 } }
215 guard settled else {
216 await report("wkwebview-back", settled: false, ms: ms, waiting: "the save typed before leaving to be answered while the page was away")
217 return
218 }
219 }
220 web.goBack()
221 guard await until("window.__persisted === true && " + editor, seconds: 15) else {
222 await report("wkwebview-back", persisted: false, settled: false, ms: 0, waiting: "the page to come back from the back/forward cache")
223 return
224 }
225 try await Task.sleep(for: .milliseconds(300))
226 since = Date()
227 _ = try await js("(\(config.type))('After coming back'); true")
228 (settled, ms) = await settle(since: since, watchFor: watch) { holds($0.text, config.want) }
229 await report("wkwebview-back", persisted: true, settled: settled, ms: ms, waiting: "the server to hold \"\(config.want)\"")
230 }
231}
232
233let config = try! JSONDecoder().decode(Config.self, from: ProcessInfo.processInfo.environment["DOCS_SAVING_CONFIG"]!.data(using: .utf8)!)
234MainActor.assumeIsolated {
235 let app = NSApplication.shared
236 let delegate = Harness(config: config)
237 app.delegate = delegate
238 app.setActivationPolicy(.accessory)
239 app.run()
240}
241