SPB Git

Repository Public

MarketsLive.swift 9.9 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/DeFi/MarketsLive.swift10// Description      : The Markets screens' use of the owner's quote stream11//                    (SPWalletCore `QuoteStream`, read-only public market12//                    data): subscribes ONLY to the markets on screen,13//                    unsubscribes when they leave, stops in the background and14//                    when the screen goes away. It keeps the last quote of each15//                    market with the means to judge its freshness NOW; when the16//                    stream drops, what is held stops reading « live » at once.17// Module           : Features18// Repository       : https://git.spboucher.ai/sp-wallet-ios19// Created          : 2026-11-1820// Last Modified    : 2026-11-1821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import Observation96import SPWalletCore9798@MainActor @Observable99final class MarketsLive {100    private(set) var connection: QuoteStreamState = .idle101    private(set) var quotes: [String: LiveQuote] = [:]102    private(set) var venues: [String: StreamVenueStatus] = [:]103    /** channels the server will never serve (`unknown_instrument`, `unsupported_channel`, `restricted`): shown, not retried */104    private(set) var refused: [String: String] = [:]105    /** markets whose held quote the stream declared unmaintained, until a new quote arrives */106    private(set) var unmaintained: Set<String> = []107    /** advances every second while the screen is visible so that ages and marks are re-evaluated */108    private(set) var now = Date()109    private(set) var limitReached = false110111    @ObservationIgnored private var client: APIClient?112    @ObservationIgnored private var stream: QuoteStream?113    @ObservationIgnored private var events: Task<Void, Never>?114    @ObservationIgnored private var clock: Task<Void, Never>?115    /** how many rows on screen show each market (the list row and the detail row of one market overlap during a push) */116    @ObservationIgnored private var shown: [String: Int] = [:]117    private var visible: Set<String> { Set(shown.keys) }118    @ObservationIgnored private var subscribed: Set<String> = []119    @ObservationIgnored private var sync: Task<Void, Never>?120    @ObservationIgnored private var active = true121    /** leave room under the connection's subscription limit (300 by default) */122    static let maxVisible = 120123124    isolated deinit { events?.cancel(); clock?.cancel(); sync?.cancel() }125126    /** Called by every Markets screen when it appears. Nothing connects until a market is on screen. */127    func attach(_ client: APIClient) { self.client = client }128129    /** Foreground / background. In the background the socket is closed; held quotes turn stale at once (the stream is idle). */130    func setActive(_ on: Bool) {131        guard on != active else { return }132        active = on133        if on { scheduleSync() } else {134            clock?.cancel(); clock = nil135            sync?.cancel(); sync = nil136            let s = stream, gone = subscribed137            subscribed = []138            Task { await s?.unsubscribe(gone.map { StreamChannel.quote($0) }); await s?.stop() }139        }140    }141142    /** A market row came on screen / left the screen. */143    func appeared(_ id: String) { shown[id, default: 0] += 1; if shown[id] == 1 { scheduleSync() } }144    func disappeared(_ id: String) {145        guard let n = shown[id] else { return }146        if n <= 1 { shown[id] = nil; scheduleSync() } else { shown[id] = n - 1 }147    }148149    private func ensureStream() -> QuoteStream? {150        if let stream { return stream }151        guard let client else { return nil }152        let s = QuoteStream(client: client)153        stream = s154        events = Task { [weak self] in155            for await e in await s.events() { guard let self else { return }; self.apply(e) }156        }157        return s158    }159160    private func scheduleSync() {161        guard active else { return }162        sync?.cancel()163        // rows appear and disappear in bursts while scrolling: one subscription frame per pause in the movement164        sync = Task { [weak self] in165            try? await Task.sleep(for: .milliseconds(250))166            guard !Task.isCancelled, let self else { return }167            await self.syncNow()168        }169    }170171    private func syncNow() async {172        guard active, let stream = ensureStream() else { return }173        let wanted = Set(visible.sorted().prefix(Self.maxVisible))174        limitReached = visible.count > Self.maxVisible175        let add = wanted.subtracting(subscribed).filter { refused[$0] == nil }, drop = subscribed.subtracting(wanted)176        if !drop.isEmpty {177            await stream.unsubscribe(drop.map { StreamChannel.quote($0) })178            for id in drop { quotes[id] = nil; unmaintained.remove(id) }179        }180        if !add.isEmpty {181            do { try await stream.subscribe(add.map { StreamChannel.quote($0) }) } catch { limitReached = true; return }182            // after the session ended the stream does not reconnect by itself: the owner is signed in again when a screen asks183            if case .ended = connection { await stream.start() }184        }185        subscribed = wanted.subtracting(refused.keys)186        if subscribed.isEmpty {187            await stream.stop()188            clock?.cancel(); clock = nil189        } else if clock == nil {190            clock = Task { [weak self] in191                while !Task.isCancelled { try? await Task.sleep(for: .seconds(1)); self?.now = Date() }192            }193        }194    }195196    /** The stream's quote of a market with its freshness now; nil when none was received. */197    func live(_ id: String) -> (quote: StreamQuoteMessage, freshness: StreamFreshness)? {198        guard let q = quotes[id] else { return nil }199        // a quote the stream declared unmaintained is judged as if the stream were idle: stale, with its age200        let f = q.freshness(connection: unmaintained.contains(id) ? .idle : connection, now: now, venue: venues[q.venue]?.status)201        return (q.quote, f)202    }203204    private func apply(_ e: QuoteStreamEvent) {205        switch e {206        case .state(let s): connection = s207        case .quote(let q): quotes[q.id] = q; unmaintained.remove(q.id)208        case .venue(let v): venues[v.venue] = v209        case .stale(let keys): for k in keys { if let id = Self.quoteId(k) { unmaintained.insert(id) } }210        case .unsubscribed(let key): if let id = Self.quoteId(key) { quotes[id] = nil }211        case .error(let m):212            if m.isPermanentForChannel, let ch = m.channel, ch.type == "quote" { refused[ch.id] = m.code; subscribed.remove(ch.id) }213        default: break214        }215    }216217    /** `quote|<id>|` → `<id>` */218    nonisolated static func quoteId(_ key: String) -> String? {219        guard key.hasPrefix("quote|"), key.hasSuffix("|") else { return nil }220        return String(key.dropFirst(6).dropLast())221    }222}223
Files main
Menu

Theme