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