|
| 1 | +import struct AmoreStore.Product |
| 2 | +import Foundation |
| 3 | + |
| 4 | +extension AmoreCheckout { |
| 5 | + |
| 6 | + /// Abandons the checkout and returns to ``CheckoutState/idle``: a flow in |
| 7 | + /// progress ends with a pending ``start(_:customerEmail:)`` returning |
| 8 | + /// `.cancelled`, and a terminal state is cleared so the next start begins |
| 9 | + /// fresh. Refused during ``CheckoutState/activating`` |
| 10 | + /// (``CheckoutState/isCancellable`` is `false`), so a paid session always |
| 11 | + /// runs to a terminal state. |
| 12 | + public func cancel() { |
| 13 | + if case .activating = state { return } |
| 14 | + flow?.cancel() |
| 15 | + state = .idle |
| 16 | + } |
| 17 | + |
| 18 | + /// Runs a checkout for `product` to its terminal result: creates a |
| 19 | + /// session, polls until payment resolves, and activates the purchased |
| 20 | + /// license. |
| 21 | + /// |
| 22 | + /// ``state`` tracks progress for observers and settles on the matching |
| 23 | + /// terminal state before the result is returned, so the two can never |
| 24 | + /// disagree. Calling from ``CheckoutState/completed(_:licenseKey:)`` or |
| 25 | + /// ``CheckoutState/failed(_:)`` starts a fresh attempt, so a Try Again |
| 26 | + /// button is just another `await checkout.start(product)`. Calling while |
| 27 | + /// an attempt is already in progress joins it and returns that attempt's |
| 28 | + /// result, whichever product it was for, so a surface offering several |
| 29 | + /// products should disable its buy buttons on ``isInProgress``. |
| 30 | + /// Cancelling the surrounding task, or calling ``cancel()``, ends the |
| 31 | + /// flow with `.cancelled`. |
| 32 | + /// |
| 33 | + /// A purchase interrupted after payment is picked up instead of charged |
| 34 | + /// again: a persisted pending session that completed activates its |
| 35 | + /// license, and one still processing is polled to its result. Only an |
| 36 | + /// unpaid, expired, or stale pending session is superseded by a fresh one. |
| 37 | + /// A ``recoverPendingPurchase()`` still in flight is awaited first, and if |
| 38 | + /// it activated the interrupted purchase the attempt ends `.cancelled` |
| 39 | + /// rather than opening a checkout for a product now owned. |
| 40 | + /// - Parameters: |
| 41 | + /// - product: The product to purchase, from `AmoreStore.products()`. |
| 42 | + /// - customerEmail: Prefills the email field on the checkout page. |
| 43 | + @discardableResult |
| 44 | + public func start( |
| 45 | + _ product: Product, |
| 46 | + customerEmail: String? = nil |
| 47 | + ) async -> CheckoutResult { |
| 48 | + // A re-entrant start (a double-clicked retry, two surfaces driving |
| 49 | + // one checkout) joins the attempt in progress instead of reporting a |
| 50 | + // false .cancelled for a flow that is still running. |
| 51 | + if let flow, isInProgress { |
| 52 | + return await flow.value |
| 53 | + } |
| 54 | + state = .preparing |
| 55 | + |
| 56 | + let flow = Task { await run(product: product, customerEmail: customerEmail) } |
| 57 | + self.flow = flow |
| 58 | + let result = await withTaskCancellationHandler { |
| 59 | + await flow.value |
| 60 | + } onCancel: { |
| 61 | + flow.cancel() |
| 62 | + } |
| 63 | + // A flow ended by cancelling the surrounding task still owns the state |
| 64 | + // and returns it to idle; once cancel() or a newer start() has taken |
| 65 | + // over, it keeps its hands off. |
| 66 | + if case .cancelled = result, self.flow == flow, isInProgress { |
| 67 | + state = .idle |
| 68 | + } |
| 69 | + return result |
| 70 | + } |
| 71 | + |
| 72 | + // MARK: - Private |
| 73 | + |
| 74 | + private func run(product: Product, customerEmail: String?) async -> CheckoutResult { |
| 75 | + if let recovery { |
| 76 | + _ = await recovery.value |
| 77 | + if case .valid = licensing.status { return .cancelled } |
| 78 | + } |
| 79 | + if let resumed = await resumePendingSession(for: product) { return resumed } |
| 80 | + let session: CheckoutSession |
| 81 | + do { |
| 82 | + session = try await client.createSession( |
| 83 | + productId: product.id, customerEmail: customerEmail |
| 84 | + ) |
| 85 | + } catch { |
| 86 | + guard !Task.isCancelled else { return .cancelled } |
| 87 | + return fail(.sessionCreationFailed(underlying: error)) |
| 88 | + } |
| 89 | + guard !Task.isCancelled else { return .cancelled } |
| 90 | + do { |
| 91 | + try store.save(PendingCheckout( |
| 92 | + session: session, productId: product.id, createdAt: .now |
| 93 | + )) |
| 94 | + } catch { |
| 95 | + store.clear() |
| 96 | + return fail(.checkoutNotRecordable) |
| 97 | + } |
| 98 | + state = .awaitingPayment(session.checkoutURL) |
| 99 | + return await poll( |
| 100 | + sessionId: session.sessionId, paymentDeadline: session.pollDeadline(from: .now) |
| 101 | + ) |
| 102 | + } |
| 103 | + |
| 104 | + // A pending session persisted by an earlier interrupted purchase is |
| 105 | + // resolved before any new session is created, so the customer cannot be |
| 106 | + // charged twice: a completed session activates its license, one still |
| 107 | + // processing is polled to its result, and an open one for the same |
| 108 | + // product is reopened at its original URL. Only an unpaid session falls |
| 109 | + // through to a fresh checkout: one for another product, an expired or |
| 110 | + // stale one, one the server has no record of, or a leftover held by an |
| 111 | + // already-licensed user. |
| 112 | + private func resumePendingSession(for product: Product) async -> CheckoutResult? { |
| 113 | + guard let pending = store.load() else { return nil } |
| 114 | + guard pending.createdAt.addingTimeInterval(Self.maxPendingAge) > .now else { |
| 115 | + store.clear() |
| 116 | + return nil |
| 117 | + } |
| 118 | + let status: CheckoutSessionStatusResponse |
| 119 | + do { |
| 120 | + status = try await client.sessionStatus(sessionId: pending.sessionId) |
| 121 | + } catch { |
| 122 | + guard !Task.isCancelled else { return .cancelled } |
| 123 | + if case .httpStatus(404) = error { |
| 124 | + store.clear() |
| 125 | + return nil |
| 126 | + } |
| 127 | + return fail(.pendingSessionUnresolved(underlying: error)) |
| 128 | + } |
| 129 | + guard !Task.isCancelled else { return .cancelled } |
| 130 | + switch status.status { |
| 131 | + case .complete: |
| 132 | + guard let key = status.licenseKey else { |
| 133 | + return fail(.pendingSessionUnresolved(underlying: nil)) |
| 134 | + } |
| 135 | + return await activate(licenseKey: key) |
| 136 | + case .processing: |
| 137 | + state = .activating |
| 138 | + return await poll(sessionId: pending.sessionId, paymentDeadline: nil) |
| 139 | + case .expired: |
| 140 | + store.clear() |
| 141 | + return nil |
| 142 | + case .open: |
| 143 | + if case .valid = licensing.status { |
| 144 | + store.clear() |
| 145 | + return nil |
| 146 | + } |
| 147 | + // The session's own expiry bounds the reopened wait, falling back |
| 148 | + // to the pending-age ceiling when the server omitted one. |
| 149 | + let expiry = pending.session.pollDeadline(from: pending.createdAt) |
| 150 | + guard pending.productId == product.id, expiry > .now else { return nil } |
| 151 | + state = .awaitingPayment(pending.session.checkoutURL) |
| 152 | + return await poll(sessionId: pending.sessionId, paymentDeadline: expiry) |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + // The wait for payment is bounded by the session's own expiry; the wait |
| 157 | + // for the license that follows it is bounded by the number of requests |
| 158 | + // instead, so a server that never issues one cannot be polled |
| 159 | + // indefinitely. A nil `paymentDeadline` is a session already paid for. |
| 160 | + private func poll(sessionId: String, paymentDeadline: Date?) async -> CheckoutResult { |
| 161 | + var deadline = paymentDeadline |
| 162 | + var activationPolls = 0 |
| 163 | + var consecutiveFailures = 0 |
| 164 | + while !Task.isCancelled { |
| 165 | + if case .activating = state { deadline = nil } |
| 166 | + if let deadline { |
| 167 | + if deadline <= .now { return fail(.sessionExpired) } |
| 168 | + } else { |
| 169 | + activationPolls += 1 |
| 170 | + if activationPolls > Self.maxActivationPolls { |
| 171 | + return fail(.licenseIssuanceTimedOut) |
| 172 | + } |
| 173 | + } |
| 174 | + do { |
| 175 | + let status = try await client.sessionStatus(sessionId: sessionId) |
| 176 | + guard !Task.isCancelled else { return .cancelled } |
| 177 | + consecutiveFailures = 0 |
| 178 | + switch status.status { |
| 179 | + case .complete: |
| 180 | + if let key = status.licenseKey { |
| 181 | + return await activate(licenseKey: key) |
| 182 | + } |
| 183 | + // Payment landed; the license is still being issued. |
| 184 | + state = .activating |
| 185 | + case .processing: |
| 186 | + state = .activating |
| 187 | + case .expired: |
| 188 | + return fail(.sessionExpired) |
| 189 | + case .open: |
| 190 | + break |
| 191 | + } |
| 192 | + } catch { |
| 193 | + consecutiveFailures += 1 |
| 194 | + if state != .activating { |
| 195 | + if case .httpStatus(404) = error { return fail(.sessionExpired) } |
| 196 | + if consecutiveFailures > Self.maxPollingFailures { |
| 197 | + return fail(.pollingFailed(underlying: error)) |
| 198 | + } |
| 199 | + } |
| 200 | + } |
| 201 | + try? await Task.sleep(for: pollInterval * (1 << min(consecutiveFailures, 3))) |
| 202 | + } |
| 203 | + return .cancelled |
| 204 | + } |
| 205 | + |
| 206 | + private func activate(licenseKey: String) async -> CheckoutResult { |
| 207 | + state = .activating |
| 208 | + do { |
| 209 | + try await licensing.activate(licenseKey: licenseKey) |
| 210 | + } catch { |
| 211 | + guard !Task.isCancelled else { return .cancelled } |
| 212 | + return fail(.activationFailed(licenseKey: licenseKey, underlying: error)) |
| 213 | + } |
| 214 | + store.clear() |
| 215 | + guard case .valid(let license) = licensing.status else { |
| 216 | + return fail(.activationFailed(licenseKey: licenseKey, underlying: .invalidToken)) |
| 217 | + } |
| 218 | + state = .completed(license, licenseKey: licenseKey) |
| 219 | + return .completed(license, licenseKey: licenseKey) |
| 220 | + } |
| 221 | + |
| 222 | + private func fail(_ error: CheckoutError) -> CheckoutResult { |
| 223 | + state = .failed(error) |
| 224 | + return .failed(error) |
| 225 | + } |
| 226 | +} |
0 commit comments