| 1 | import Foundation |
| 2 | import RastrilloApple |
| 3 | import RastrilloNative |
| 4 | import RastrilloTestSupport |
| 5 | import XCTest |
| 6 | @testable import DocsKit |
| 7 | |
| 8 | /// Delete…'s client rule (spec 2026-11-22 §1, plan S2b acceptance): JSON ok; |
| 9 | /// 303 then 404; 303 then 200; POST 404 then GET 404 (deleted); POST 404 |
| 10 | /// then GET 200 (failed: the lane and the replica are kept). |
| 11 | @MainActor final class DocsDeletionTests: XCTestCase { |
| 12 | private let ok = Data(#"{"ok":true}"#.utf8) |
| 13 | private let json = ["Content-Type": "application/json"] |
| 14 | |
| 15 | private func run(_ steps: [ScriptedTransport.Step]) async -> (DocsDeletion.Outcome, [ScriptedTransport.Call]) { |
| 16 | let transport = ScriptedTransport(steps) |
| 17 | let outcome = await DocsDeletion.run(sqid: "doc", transport: transport) |
| 18 | XCTAssertEqual(transport.remainingSteps, 0, "every scripted answer was asked for") |
| 19 | return (outcome, transport.calls) |
| 20 | } |
| 21 | |
| 22 | func testJSONOKIsDeletedWithNoCheck() async { |
| 23 | let (outcome, calls) = await run([.respond(status: 200, body: ok, headers: json)]) |
| 24 | XCTAssertEqual(outcome, .deleted) |
| 25 | XCTAssertEqual(calls.map(\.method), ["POST"]) |
| 26 | XCTAssertEqual(calls.first?.path, "/d/doc/delete") |
| 27 | } |
| 28 | |
| 29 | /// An older or lagged server: the delete committed, then a 303 to the list. |
| 30 | func testA303ThenA404IsDeleted() async { |
| 31 | let (outcome, calls) = await run([.respond(status: 303, headers: ["Location": "/"]), .respond(status: 404)]) |
| 32 | XCTAssertEqual(outcome, .deleted) |
| 33 | XCTAssertEqual(calls.map { "\($0.method) \($0.path)" }, ["POST /d/doc/delete", "GET /d/doc"]) |
| 34 | } |
| 35 | |
| 36 | func testA303ThenA200IsNotDeleted() async { |
| 37 | let (outcome, _) = await run([.respond(status: 303, headers: ["Location": "/"]), .respond(status: 200, body: Data("{}".utf8), headers: json)]) |
| 38 | XCTAssertEqual(outcome, .stillThere) |
| 39 | } |
| 40 | |
| 41 | /// A 404 is ambiguous (a non-owner gets one, and so does a retry after a |
| 42 | /// lost answer): the check decides. |
| 43 | func testAPost404ThenAGet404IsDeleted() async { |
| 44 | let (outcome, _) = await run([.respond(status: 404), .respond(status: 404)]) |
| 45 | XCTAssertEqual(outcome, .deleted) |
| 46 | } |
| 47 | |
| 48 | func testAPost404ThenAGet200IsNotDeleted() async { |
| 49 | let (outcome, _) = await run([.respond(status: 404), .respond(status: 200, body: Data("{}".utf8), headers: json)]) |
| 50 | XCTAssertEqual(outcome, .stillThere) |
| 51 | } |
| 52 | |
| 53 | /// A 2xx that is not `{"ok":true}` (a page, or the list a followed |
| 54 | /// redirect would give) is checked too; a check that cannot say is |
| 55 | /// "not known", never deleted. |
| 56 | func testAnythingElseIsChecked() async { |
| 57 | var (outcome, _) = await run([.respond(status: 200, body: Data("<html>".utf8), headers: ["Content-Type": "text/html"]), .respond(status: 200)]) |
| 58 | XCTAssertEqual(outcome, .stillThere) |
| 59 | (outcome, _) = await run([.respond(status: 200, body: Data(#"{"documents":[]}"#.utf8), headers: json), .respond(status: 404)]) |
| 60 | XCTAssertEqual(outcome, .deleted) |
| 61 | (outcome, _) = await run([.respond(status: 503), .respond(status: 503)]) |
| 62 | XCTAssertEqual(outcome, .unknown) |
| 63 | (outcome, _) = await run([.offline(), .offline()]) |
| 64 | XCTAssertEqual(outcome, .unknown) |
| 65 | // The answer was lost after the server committed it. |
| 66 | (outcome, _) = await run([.commitThenLoseResponse(), .respond(status: 404)]) |
| 67 | XCTAssertEqual(outcome, .deleted) |
| 68 | } |
| 69 | |
| 70 | // MARK: - Through the model |
| 71 | |
| 72 | private func open(_ delete: [ScriptedTransport.Step]) async throws -> (DocsModel, DeleteServer, String) { |
| 73 | let server = DeleteServer(delete) |
| 74 | try await server.inner.seed([.object(["type": .string("paragraph"), "children": .array([ |
| 75 | .object(["type": .string("text"), "runs": .array([.object(["insert": .string("Old minutes"), "marks": .object([:])])])])])])]) |
| 76 | let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| 77 | let account = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity, transport: { server }) |
| 78 | let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account) |
| 79 | await model.open("doc") |
| 80 | XCTAssertNotNil(model.projection, "the document opened") |
| 81 | let key = try account.key(for: "doc") |
| 82 | XCTAssertTrue(try account.replicaCache.hasBase(key), "precondition: the replica is on the device") |
| 83 | XCTAssertNotNil(try account.metadata(key)) |
| 84 | return (model, server, key) |
| 85 | } |
| 86 | |
| 87 | func testDeletedDropsTheLaneAndTheReplica() async throws { |
| 88 | let (model, _, key) = try await open([.respond(status: 200, body: ok, headers: json)]) |
| 89 | XCTAssertNil(model.deleteBlock(offline: false)) |
| 90 | let result = await model.deleteDocument() |
| 91 | XCTAssertEqual(result, .init(outcome: .deleted, wasOpen: true)) |
| 92 | XCTAssertFalse(try model.offlineAccount.replicaCache.hasBase(key), "the replica is gone") |
| 93 | XCTAssertNil(try model.offlineAccount.metadata(key), "and its metadata") |
| 94 | let lane = await model.offlineAccount.outbox.summary.only("doc:" + key) |
| 95 | XCTAssertTrue(lane.isEmpty, "and its lane") |
| 96 | XCTAssertNil(model.detail, "the model holds no document") |
| 97 | } |
| 98 | |
| 99 | func testNotDeletedKeepsTheLaneAndTheReplica() async throws { |
| 100 | let (model, server, key) = try await open([.respond(status: 404)]) |
| 101 | await server.answerDetail(200) |
| 102 | let result = await model.deleteDocument() |
| 103 | XCTAssertEqual(result?.outcome, .stillThere) |
| 104 | XCTAssertTrue(try model.offlineAccount.replicaCache.hasBase(key), "the replica is kept") |
| 105 | XCTAssertNotNil(try model.offlineAccount.metadata(key)) |
| 106 | XCTAssertEqual(model.detail?.sqid, "doc", "the document stays open") |
| 107 | XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("x")]), |
| 108 | "and editable: the delete's pause is lifted") |
| 109 | await model.stop() |
| 110 | } |
| 111 | |
| 112 | /// Fable on #178, finding 1: the answer comes after another document |
| 113 | /// was opened (back to the library, open B, on a slow link). Only A's |
| 114 | /// lane, replica and metadata go; B, open now, keeps all of its own, and |
| 115 | /// the model stays on B. |
| 116 | func testADeleteAnsweredAfterAnotherDocumentOpenedDropsOnlyItsOwn() async throws { |
| 117 | let (model, server, keyA) = try await open([.respond(status: 200, body: ok, headers: json)]) |
| 118 | try await server.b.seed([.object(["type": .string("paragraph"), "children": .array([ |
| 119 | .object(["type": .string("text"), "runs": .array([.object(["insert": .string("B's text"), "marks": .object([:])])])])])])]) |
| 120 | await server.holdDelete() |
| 121 | let deleting = Task { await model.deleteDocument() } |
| 122 | let deadline = Date().addingTimeInterval(5) |
| 123 | while !(await server.deleteWaiting) { |
| 124 | guard Date() < deadline else { return XCTFail("the delete never reached the server") } |
| 125 | try await Task.sleep(for: .milliseconds(5)) |
| 126 | } |
| 127 | await model.open("b") |
| 128 | XCTAssertEqual(model.detail?.sqid, "b", "B is open while A's delete waits") |
| 129 | let keyB = try model.offlineAccount.key(for: "b") |
| 130 | XCTAssertNotEqual(keyA, keyB) |
| 131 | // An unsent change in B: its lane must survive A's delete. |
| 132 | XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("x")]), |
| 133 | "B takes typing: A's delete does not hold it") |
| 134 | let typedDeadline = Date().addingTimeInterval(5) |
| 135 | while await model.offlineAccount.outbox.summary.only("doc:" + keyB).isEmpty { |
| 136 | guard Date() < typedDeadline else { return XCTFail("B's change never reached its lane") } |
| 137 | try await Task.sleep(for: .milliseconds(5)) |
| 138 | } |
| 139 | await model.persistReplica() |
| 140 | |
| 141 | await server.releaseDelete() |
| 142 | let result = await deleting.value |
| 143 | XCTAssertEqual(result, .init(outcome: .deleted, wasOpen: false), "A was deleted, and it was no longer the open document") |
| 144 | XCTAssertEqual(model.detail?.sqid, "b", "the model stays on B") |
| 145 | XCTAssertTrue(try model.offlineAccount.replicaCache.hasBase(keyB), "B's replica survives") |
| 146 | XCTAssertNotNil(try model.offlineAccount.metadata(keyB), "and its metadata") |
| 147 | let laneB = await model.offlineAccount.outbox.summary.only("doc:" + keyB) |
| 148 | XCTAssertFalse(laneB.isEmpty, "and its unsent lane") |
| 149 | XCTAssertFalse(try model.offlineAccount.replicaCache.hasBase(keyA), "A's replica is gone") |
| 150 | XCTAssertNil(try model.offlineAccount.metadata(keyA), "and A's metadata") |
| 151 | let laneA = await model.offlineAccount.outbox.summary.only("doc:" + keyA) |
| 152 | XCTAssertTrue(laneA.isEmpty, "and A's lane") |
| 153 | await model.stop() |
| 154 | } |
| 155 | |
| 156 | /// Owners only; never a draft; refused while anything is unsent. |
| 157 | func testDeleteIsRefusedWithUnsentChangesAndForNonOwners() async throws { |
| 158 | let (model, _, _) = try await open([]) |
| 159 | model.renameInput = "Renamed, not yet committed" |
| 160 | XCTAssertEqual(model.deleteBlock(offline: false), .unsent) |
| 161 | let outcome = await model.deleteDocument() |
| 162 | XCTAssertNil(outcome, "refused, and nothing was asked of the server") |
| 163 | model.renameInput = nil |
| 164 | XCTAssertEqual(model.deleteBlock(offline: true), .offline) |
| 165 | |
| 166 | let draft = DocsModel(transport: { nil }, draft: true) |
| 167 | XCTAssertEqual(draft.deleteBlock(offline: false), .notOwner, "a draft has no Delete…") |
| 168 | await model.stop() |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// LoopServer with POST /d/doc/delete answered from a script, and the |
| 173 | /// detail's status under the test's control after it. |
| 174 | actor DeleteServer: NativeTransport { |
| 175 | nonisolated let origin = URL(string: "https://docs.delete.invalid")! |
| 176 | let inner = LoopServer() |
| 177 | /// A second document, "b": the same LoopServer routes under /d/b. Its |
| 178 | /// update POSTs are refused (503), so what B types stays in its lane. |
| 179 | let b = LoopServer() |
| 180 | private var deleteSteps: [ScriptedTransport.Step] |
| 181 | private var detailStatus = 200 |
| 182 | private(set) var deleteCalls = 0 |
| 183 | private var holding = false |
| 184 | private var gate: CheckedContinuation<Void, Never>? |
| 185 | |
| 186 | init(_ steps: [ScriptedTransport.Step]) { deleteSteps = steps } |
| 187 | func answerDetail(_ status: Int) { detailStatus = status } |
| 188 | func holdDelete() { holding = true } |
| 189 | var deleteWaiting: Bool { gate != nil } |
| 190 | func releaseDelete() { holding = false; gate?.resume(); gate = nil } |
| 191 | |
| 192 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 193 | if path == "/d/b" || path.hasPrefix("/d/b/") || path.hasPrefix("/d/b?") { |
| 194 | if method == "GET", path == "/d/b" { |
| 195 | let detail = DocumentDetail(sqid: "b", title: "B", guid: "render-loop", can_write: true, can_share: true) |
| 196 | return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| 197 | } |
| 198 | if method == "POST" { return NativeResponse(data: Data(), status: 503, headers: [:]) } |
| 199 | return try await b.responseDetails("/d/doc" + path.dropFirst(4), method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| 200 | } |
| 201 | if method == "POST", path == "/d/doc/delete" { |
| 202 | deleteCalls += 1 |
| 203 | if holding { await withCheckedContinuation { gate = $0 } } |
| 204 | guard !deleteSteps.isEmpty else { throw NativeClientError.message("DeleteServer: no scripted answer left for the delete") } |
| 205 | switch deleteSteps.removeFirst() { |
| 206 | case .respond(let status, let body, let headers): |
| 207 | if (200..<300).contains(status) || status == 303 { detailStatus = 404 } |
| 208 | return NativeResponse(data: body, status: status, headers: headers) |
| 209 | case .offline(let code): throw NativeClientError.offline(code) |
| 210 | default: throw NativeClientError.offline(.networkConnectionLost) |
| 211 | } |
| 212 | } |
| 213 | if method == "GET", path == "/d/doc" { |
| 214 | guard detailStatus == 200 else { return NativeResponse(data: Data(), status: detailStatus, headers: [:]) } |
| 215 | let detail = DocumentDetail(sqid: "doc", title: "Old minutes", guid: "render-loop", can_write: true, can_share: true) |
| 216 | return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| 217 | } |
| 218 | return try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| 219 | } |
| 220 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 221 | if path.hasPrefix("/d/b/") { return try await b.stream("/d/doc" + path.dropFirst(4), onOpen: onOpen, onLine: onLine) } |
| 222 | try await inner.stream(path, onOpen: onOpen, onLine: onLine) |
| 223 | } |
| 224 | func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| 225 | } |
| 226 | |