Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Storage Node9// File : MacLustrStorageNode/Services/NodeController.swift10// Description : Bridge between the engine (an actor) and SwiftUI:11// publishes the node snapshot, applies settings, relays user12// actions.13// Module : MacLustrStorageNode14// Repository : https://git.spboucher.ai/maclustr-storage-ios15// Project Website : https://storage.spboucher.ai16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: admin@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import SwiftUI92import UIKit9394@MainActor95final class NodeController: ObservableObject {96 static let shared = NodeController()9798 @Published private(set) var snapshot = NodeSnapshot()99 @Published var settings = NodeSettings.load()100 @Published private(set) var paired = false101 @Published private(set) var activated = UserDefaults.standard.bool(forKey: "node.activated")102 @Published private(set) var activity: [ActivityEntry] = []103 @Published private(set) var startupError: String?104 @Published private(set) var pairing: Pairing?105 @Published private(set) var keyHardwareBacked = false106 @Published var stationPresented = false107 @Published var selectedTab = 0108109 private(set) var engine: NodeEngine?110 private var booted = false111112 static var deviceInfo: DeviceInfo {113 var sys = utsname(); uname(&sys)114 let model = withUnsafePointer(to: &sys.machine) { $0.withMemoryRebound(to: CChar.self, capacity: 1) { String(cString: $0) } }115 let v = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?"116 let b = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?"117 return DeviceInfo(name: UIDevice.current.name, model: model, os: UIDevice.current.systemVersion, app: "\(v) (\(b))")118 }119120 func boot() async {121 guard !booted else { return }122 booted = true123 do {124 let e = try NodeEngine()125 engine = e126 await e.setObserver { [weak self] snap in Task { @MainActor in self?.apply(snap) } }127 await e.start(info: Self.deviceInfo)128 settings = await e.currentSettings129 await refreshIdentity()130 await reloadActivity()131 await applyLaunchArguments()132 } catch { startupError = "The storage engine could not start: \(error)" }133 }134135 private func apply(_ snap: NodeSnapshot) {136 let wasPaired = paired137 snapshot = snap138 paired = snap.connection != .unpaired && snap.connection != .revoked139 if wasPaired && !paired { setActivated(false); stationPresented = false; Task { await refreshIdentity() } }140 updateIdleTimer()141 }142143 private func refreshIdentity() async {144 guard let engine else { return }145 pairing = await engine.pairingRecord146 paired = await engine.isPaired147 keyHardwareBacked = await engine.keyIsHardwareBacked148 }149150 private func setActivated(_ v: Bool) { activated = v; UserDefaults.standard.set(v, forKey: "node.activated") }151152 /// The screen stays awake only in station mode, only when the user asked for it, and only on external power.153 private func updateIdleTimer() {154 UIApplication.shared.isIdleTimerDisabled = stationPresented && settings.keepAwakeInStationMode && snapshot.charging155 }156157 // MARK: Actions158159 func pair(_ input: String) async -> String? {160 guard let engine else { return "Engine not started" }161 do { try await engine.pair(input: input); await refreshIdentity(); return nil }162 catch let e as MSPError {163 switch e {164 case .http(_, "invalid_pairing_code"): return "This code is not valid: it may have expired or been used already. Generate a new one in the MacLustr dashboard."165 case .http(_, "too_many_attempts"): return "Too many attempts. Wait ten minutes and try again."166 case .transport(let m): return "The cluster could not be reached: \(m)"167 default: return e.message168 }169 } catch { return String(describing: error) }170 }171172 func activate(quota: Int64) async {173 var s = settings; s.quotaBytes = quota; s.suspended = false174 await save(s)175 setActivated(true)176 }177178 func save(_ new: NodeSettings) async {179 settings = new180 await engine?.update(settings: new)181 updateIdleTimer()182 }183184 func reloadActivity() async { if let engine { activity = await engine.activity() } }185 func clearActivity() async { await engine?.clearActivity(); await reloadActivity() }186187 func drain(remove: Bool) async -> String? {188 do { try await engine?.requestDrain(remove: remove); return nil } catch let e as MSPError { return e.message } catch { return "\(error)" }189 }190 func cancelDrain() async -> String? {191 do { try await engine?.cancelDrain(); return nil } catch let e as MSPError { return e.message } catch { return "\(error)" }192 }193 func emergencyRelease(remove: Bool) async -> Int64 {194 let freed = await engine?.emergencyRelease(remove: remove) ?? 0195 await refreshIdentity(); await reloadActivity()196 return freed197 }198 func diagnose() async -> [DiagnosticLine] { await engine?.diagnose() ?? [] }199 func benchmark() async -> BenchmarkReport? { await engine?.runBenchmark() }200 func rotateKey() async -> Bool { let ok = await engine?.rotateKey() ?? false; await refreshIdentity(); return ok }201 func syncNow() async { await engine?.heartbeat(); await engine?.workCycle(wait: 0); await reloadActivity() }202203 func scenePhase(_ phase: ScenePhase) {204 switch phase {205 case .active: Task { await engine?.setForeground(true) }206 case .background:207 BackgroundScheduler.schedule()208 let bg = UIApplication.shared.beginBackgroundTask(withName: "handover")209 Task { await engine?.setForeground(false); UIApplication.shared.endBackgroundTask(bg) }210 default: break211 }212 }213214 func enterStation() { stationPresented = true; updateIdleTimer() }215 func exitStation() { stationPresented = false; updateIdleTimer() }216217 // MARK: Launch arguments (Debug builds only): scripted pairing and navigation for tests on the simulator218219 private func applyLaunchArguments() async {220 #if DEBUG221 let d = UserDefaults.standard222 if let code = d.string(forKey: "PairingCode"), !paired { if let err = await pair(code) { startupError = "pairing: \(err)" } }223 if d.object(forKey: "QuotaGB") != nil, paired { await activate(quota: Int64(d.integer(forKey: "QuotaGB")) * Format.gb) }224 if d.object(forKey: "Tab") != nil { selectedTab = d.integer(forKey: "Tab") }225 if d.bool(forKey: "Station") { enterStation() }226 if d.bool(forKey: "EmergencyRelease"), paired { _ = await emergencyRelease(remove: false) }227 #endif228 }229}230