import Foundation import RastrilloApple /// Ask set up during sign-in, with no code to approve (spec 3.8, P1, P2): /// the app fetches an Oficina ID assertion addressed to Equipo and posts it /// to Base, which finishes Equipo's own native sign-in for the person and /// keeps the key. Equipo's key from Oficina ID lasts seven days, so Base /// says when to renew it (`renew_after`) and this does, silently. /// /// It runs when `/ask/state` says `connect` or `reconnect` (a write's 409 /// reconnect too), or `renew_after` has passed: /// /// 1. `assertion(for: equipo_origin)`; /// 2. `POST /api/v1/ask/oficina`; /// 3. read `/ask/state` again, whatever happened. /// /// - `ready`: done. `not_linked` (Equipo doesn't know this person): Ask /// shows it, with the web's set-up; never retried by itself. /// - `422 failed`: once more at once, with a fresh assertion. /// - `409 superseded` (the person disconnected or reconnected another way /// meanwhile): not retried; the state read afresh says how things are. /// - The kit's CancellationError (the sign-in changed while Home answered, /// its own silent re-sign-in after a 401 included): nothing shown, tried /// again at the next foreground or state load. /// - `409 disconnected` (an automatic set-up while the member has /// disconnected, on any client): stop; Ask shows Set up. /// - Anything else: Ask stays as Base reports it; tried again later. /// /// Never more than once a minute, whatever triggers it, but for a person /// pressing Set it up. @MainActor public final class AskSetup { public typealias Assertion = @MainActor (URL) async throws -> (assertion: String, verifier: String) let client: BaseClient let ask: AskModel let assertion: Assertion let now: () -> Date /// The Equipo Ask relays to, when `/ask/state` hasn't said yet. var fallbackEquipo: () -> URL? /// Whether the session that made this is still the one (the account /// hasn't changed or signed out). var isCurrent: () -> Bool = { true } /// The person disconnected Ask: no set-up by itself until they set it /// up again (`force`) or sign in afresh. Base's word (`/ask/state`'s /// `disconnected`) when it says; the device's cache otherwise. var heldOff: () -> Bool = { false } /// Base answered an automatic set-up `409 disconnected`. var onDisconnected: () -> Void = {} /// Bumped by `invalidate()`: a set-up already running lands nothing. private var epoch = 0 /// Disconnect: whatever set-up is running must not undo it. public func invalidate() { epoch += 1 } private(set) var lastAttempt: Date? /// The epoch of the run in flight, if any. private var runningEpoch: Int? var running: Bool { runningEpoch != nil } /// Equipo answered not_linked: no more automatic attempts this session. private(set) var notLinked = false public init(client: BaseClient, ask: AskModel, assertion: @escaping Assertion, now: @escaping () -> Date = Date.init, fallbackEquipo: @escaping () -> URL? = { nil }) { self.client = client; self.ask = ask; self.assertion = assertion; self.now = now; self.fallbackEquipo = fallbackEquipo } /// Whether Ask wants setting up now, by its state. public var wanted: Bool { switch ask.phase { case .connect, .reconnect: true case .ready, .norunner, .oldrunner: ask.renewAfter.map { $0 <= now() } ?? false default: false } } /// Runs the set-up if Ask wants it and the minute has passed (`force`: /// the person pressed Set it up, which also clears a not_linked). @discardableResult public func runIfNeeded(force: Bool = false) async -> Bool { // Base still says connect after not_linked: Ask keeps saying why. if !force, heldOff() { return false } if notLinked, !force, ask.phase == .connect || ask.phase == .reconnect { ask.show(.notLinked); return false } // One run at a time; but the person's own Set it up goes ahead when // the run in flight was invalidated (a Disconnect, Set it up), and // that one lands nothing. if let inFlight = runningEpoch, !(force && inFlight != epoch) { return false } guard wanted || (force && ask.phase != .loading) else { return false } if !force { guard !notLinked else { return false } if let last = lastAttempt, now().timeIntervalSince(last) < 60 { return false } } guard let equipo = ask.equipoOrigin ?? fallbackEquipo() else { return false } let activity = ask.activity, started = epoch runningEpoch = started defer { if runningEpoch == started { runningEpoch = nil } } let previousAttempt = lastAttempt, thisAttempt = now() lastAttempt = thisAttempt notLinked = false // After every suspension: the account, Ask's activity (a pause, a // sign-out) and this task must all be as they were, or nothing lands. func live() -> Bool { isCurrent() && epoch == started && ask.activity == activity && !ask.paused && !ask.disposed && !Task.isCancelled } // A run that ends because it no longer counts spends no minute: the // next trigger may try at once. func abandon() -> Bool { if lastAttempt == thisAttempt { lastAttempt = previousAttempt } return false } var tries = 0 while tries < 2 { tries += 1 let proof: (assertion: String, verifier: String) do { proof = try await assertion(equipo) } catch { // CancellationError (the sign-in moved under it) and any other // failure to get a proof: nothing to show; next time. Abandoned // meanwhile (the account went, a pause, an invalidation): it // spends no minute either. return live() ? false : abandon() } guard live() else { return abandon() } do { let answer = try await client.connectAsk(assertion: proof.assertion, verifier: proof.verifier, auto: !force) guard live() else { return abandon() } if answer.state == .notLinked { notLinked = true; ask.show(.notLinked); return false } await ask.load() return true } catch .server(422, _, "failed") where tries < 2 { guard live() else { return abandon() } continue } catch .server(409, _, "disconnected") { // The member disconnected (here or on another device): stop, // and let Ask show Set up. guard live() else { return abandon() } onDisconnected() await ask.load() return false } catch .server(409, _, "not_linked") { guard live() else { return abandon() } notLinked = true ask.show(.notLinked) return false } catch { // superseded, unavailable, Ask off, a refused session: Ask as // Base says it is now. guard live() else { return abandon() } await ask.load() return false } } guard live() else { return abandon() } await ask.load() return false } }