SPB Git

Repository Public

OutboundTracker.swift 7.8 KB 156 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Model/OutboundTracker.swift3// Description: The messages the SERVER is tracking for this user (`GET /api/v1/messages/outbound`): what the composer sent through4// `/api/v1/messages/send` — held for undo, scheduled, queued, accepted, delivered, deferred, bounced, failed, per recipient with the SMTP5// reply. The local outbox item of such a send is gone once the server took the message; this list is what keeps the send visible in6// « Boîte d’envoi ». Refreshed quietly: when the outbox opens, after a sync, and while something is still moving — on a schedule that7// follows the server's own deadlines (never a tight poll). Nothing here is assumed: every state shown is one the server reported.8import SPMailCore9import SwiftUI1011@MainActor @Observable12final class OutboundTracker {13    @ObservationIgnored weak var app: AppModel?14    /// Recent server-tracked sends, newest first (cancelled sends and hidden rows left out).15    private(set) var items: [OutboundStatus] = []16    /// Why the list could not be refreshed (offline…); the last known rows stay on screen.17    private(set) var notice: String?18    private(set) var loadedAt: Date?19    @ObservationIgnored private var subjects: [String: String] = [:]20    @ObservationIgnored private var hidden: Set<String> = []21    @ObservationIgnored private var restored = false22    @ObservationIgnored private var inFlight: Task<Void, Never>?23    @ObservationIgnored private var timer: Task<Void, Never>?24    @ObservationIgnored private var lastLoad = Date.distantPast2526    private static let subjectsKey = "outbound.subjects", hiddenKey = "outbound.hidden"2728    // MARK: rules (pure: exercised by the self-test)2930    /// The message is held by undo send: it can still be taken back.31    static func isHeld(_ o: OutboundStatus, now: Date = Date()) -> Bool { o.status == "scheduled" && (o.undoUntil ?? .distantPast) > now }32    /// How long a row stays listed after its last change: what is still moving always, a failure one week, a success two days.33    static func isListed(_ o: OutboundStatus, now: Date = Date()) -> Bool {34        let age = now.timeIntervalSince(o.updatedAt ?? o.createdAt ?? now)35        switch o.status {36        case "cancelled", "draft": return false37        case "bounced", "failed": return age < 7 * 86_40038        case "delivered", "sent": return age < 2 * 86_40039        default: return true40        }41    }42    /// When to ask the server again, from what the rows say — nil when nothing is expected to change soon.43    /// A hold is checked once it ends; a fresh send every 15 s for two minutes, then every minute for a quarter of an hour; a deferred44    /// delivery every two minutes; a scheduled send when its time comes (if it is within ten minutes).45    static func nextCheck(_ items: [OutboundStatus], now: Date = Date()) -> TimeInterval? {46        var best: TimeInterval?47        func want(_ t: TimeInterval) { best = min(best ?? t, t) }48        for o in items {49            let age = now.timeIntervalSince(o.updatedAt ?? o.createdAt ?? now)50            switch o.status {51            case "scheduled":52                if let until = o.undoUntil, until > now { want(until.timeIntervalSince(now) + 1.5) }53                else if let at = o.sendAt ?? o.undoUntil { let t = at.timeIntervalSince(now); if t < 600 { want(max(t, 0) + 3) } }54            case "queued", "sent": if age < 120 { want(15) } else if age < 900 { want(60) }55            case "deferred": if age < 86_400 { want(120) }56            case "pending_approval": if age < 3600 { want(300) }57            default: break58            }59        }60        return best.map { max($0, 2) }61    }6263    // MARK: state6465    func title(for o: OutboundStatus) -> String? { subjects[o.id] ?? o.subject }6667    /// Remembers the subject of a message this device just sent (the server's outbound status carries none).68    func note(subject: String, for id: String) {69        subjects[id] = subject70        persist()71    }7273    /// Takes a finished row off the list on this device (the server keeps its record).74    func hide(_ id: String) {75        hidden.insert(id)76        items.removeAll { $0.id == id }77        persist()78    }7980    private func persist() {81        guard let store = app?.store else { return }82        let listed = Set(items.map(\.id))83        // bounded: only what is still listed, and what was noted for a send not listed yet84        if subjects.count > 200 { subjects = subjects.filter { listed.contains($0.key) } }85        if hidden.count > 400 { hidden = hidden.intersection(listed) }86        let s = subjects, h = Array(hidden)87        Task { try? await store.setValue(Self.subjectsKey, s); try? await store.setValue(Self.hiddenKey, h) }88    }8990    private func restore() async {91        guard !restored, let store = app?.store else { return }92        restored = true93        subjects.merge((try? await store.value(Self.subjectsKey, as: [String: String].self)) ?? [:]) { mine, _ in mine }94        hidden.formUnion((try? await store.value(Self.hiddenKey, as: [String].self)) ?? [])95    }9697    /// Asks the server for the recent sends. Throttled (8 s) unless `force`; quiet on failure. One request at a time: a forced reload98    /// asked while another one runs waits for it, then asks again (what it wants to see may have happened in between).99    func reload(force: Bool = false) async {100        while let running = inFlight {101            await running.value102            if !force { return }103        }104        guard let app, app.phase == .ready || app.phase == .locked else { return }105        if !force, Date().timeIntervalSince(lastLoad) < 8 { return }106        // the task clears `inFlight` itself, before it completes: a caller waiting on it never finds a finished task still in place107        let task = Task { await self.load(app); self.inFlight = nil }108        inFlight = task109        await task.value110    }111112    private func load(_ app: AppModel) async {113        await restore()114        lastLoad = Date()115        do {116            let fresh = try await app.api.outboundMessages(limit: 50).filter { !hidden.contains($0.id) && Self.isListed($0) }117            // the subject: what this device noted when it sent the message, else the stored copy in the local cache118            for i in fresh.indices where subjects[fresh[i].id] == nil {119                guard let ref = fresh[i].messageId.flatMap({ V1MessageID.decode($0) }), let e = (try? await app.store?.email(ref.mailboxId, id: ref.emailId)) ?? nil else { continue }120                subjects[fresh[i].id] = e.subject121            }122            if fresh != items { items = fresh }123            notice = nil124            loadedAt = Date()125        } catch let e as APIError where e.isUnauthorized {126            await app.sessionRevoked()127            return128        } catch let e as APIError where e.isOffline {129            notice = L("Hors ligne — dernier état connu des envois")130        } catch let e as APIError where e.status == 404 {131            items = [] // a server without the sending API: nothing is tracked there132        } catch {133            notice = app.describe(error)134        }135        schedule()136    }137138    /// One timer at most, set from the rows themselves; it stops by itself when nothing is moving, offline, or when the session ends.139    private func schedule() {140        timer?.cancel(); timer = nil141        guard let app, app.phase == .ready, app.isOnline, let delay = Self.nextCheck(items) else { return }142        timer = Task { [weak self] in143            try? await Task.sleep(for: .seconds(delay))144            guard !Task.isCancelled else { return }145            await self?.reload(force: true)146        }147    }148149    /// Sign-out or revoked session.150    func reset() {151        timer?.cancel(); timer = nil152        inFlight?.cancel(); inFlight = nil153        items = []; notice = nil; loadedAt = nil; subjects = [:]; hidden = []; restored = false; lastLoad = .distantPast154    }155}156
Files main
Menu

Theme