SPB Git

Repository Public

ActionForm.swift 8.6 KB 191 lines swift

1import Foundation2import Observation34/// One input of an action form, derived from the JSON Schema of `GET /action-types` (`params_schema`).5public struct SchemaField: Identifiable, Sendable, Hashable {6    public enum Kind: Sendable, Hashable {7        case string8        case choice([String])9        case integer(min: Int?, max: Int?)10        case number(min: Double?, max: Double?)11        case boolean12        /// A shape this client does not render as a control: edited as raw JSON, validated by the server.13        case json14    }15    public var name: String16    public var title: String17    public var help: String?18    public var kind: Kind19    public var required: Bool20    public var defaultValue: JSONValue?21    public var id: String { name }2223    /// Fields of an object schema, required ones first, then in alphabetical order (JSON objects are unordered).24    public static func fields(from schema: JSONValue) -> [SchemaField] {25        guard let props = schema["properties"]?.objectValue else { return [] }26        let required = Set(schema["required"]?.arrayValue?.compactMap(\.stringValue) ?? [])27        return props.map { name, s in28            let kind: Kind29            if let options = s["enum"]?.arrayValue?.compactMap(\.stringValue), !options.isEmpty {30                kind = .choice(options)31            } else {32                switch s["type"]?.stringValue {33                case "string": kind = .string34                case "integer": kind = .integer(min: s["minimum"]?.intValue, max: s["maximum"]?.intValue)35                case "number": kind = .number(min: s["minimum"]?.doubleValue, max: s["maximum"]?.doubleValue)36                case "boolean": kind = .boolean37                default: kind = .json38                }39            }40            return SchemaField(name: name, title: s["title"]?.stringValue ?? name, help: s["description"]?.stringValue,41                               kind: kind, required: required.contains(name), defaultValue: s["default"])42        }43        .sorted { ($0.required ? 0 : 1, $0.name) < ($1.required ? 0 : 1, $1.name) }44    }45}4647/// State of an action request form. It only checks that what the server will require is present; whether the48/// confirmation matches, the justification is acceptable or the caller is allowed is decided by the server.49@MainActor50@Observable51public final class ActionFormModel {52    public let type: API.ActionType53    public let target: API.ActionTarget54    /// What the user is asked to type when `requires_confirmation` (alias of the node / name of the service).55    public let targetLabel: String56    public let fields: [SchemaField]57    public var values: [String: JSONValue]58    /// Raw text of `.json` fields, by field name.59    public var rawJSON: [String: String] = [:]60    public var justification = ""61    public var confirmation = ""62    public private(set) var isSubmitting = false63    public private(set) var error: APIError?64    public private(set) var created: API.Action?65    @ObservationIgnored private var tracker = IdempotencyTracker()6667    public init(type: API.ActionType, target: API.ActionTarget, targetLabel: String, presetParams: [String: JSONValue] = [:]) {68        self.type = type69        self.target = target70        self.targetLabel = targetLabel71        let fields = SchemaField.fields(from: JSONValue(type.paramsSchema.additionalProperties))72        self.fields = fields73        var v: [String: JSONValue] = [:]74        for f in fields {75            if let d = f.defaultValue { v[f.name] = d }76            // A switch always shows a definite state: make that state the value instead of "missing".77            else if case .boolean = f.kind { v[f.name] = .bool(false) }78        }79        v.merge(presetParams) { $1 }80        self.values = v81    }8283    public var missingFields: [String] {84        fields.filter { f in85            guard f.required else { return false }86            if case .json = f.kind { return (rawJSON[f.name] ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && values[f.name] == nil }87            switch values[f.name] {88            case nil, .null?: return true89            case .string(let s)?: return s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty90            default: return false91            }92        }.map(\.name)93    }9495    public var invalidJSONFields: [String] {96        fields.filter { f in97            guard case .json = f.kind, let raw = rawJSON[f.name], !raw.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false }98            return (try? JSONValue.parse(Data(raw.utf8))) == nil99        }.map(\.name)100    }101102    public var needsJustification: Bool { type.requiresJustification && justification.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }103    public var needsConfirmation: Bool { type.requiresConfirmation && confirmation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }104105    /// Local completeness only (and the catalog's `available` flag, which the server would refuse anyway).106    public var canSubmit: Bool {107        type.available && !isSubmitting && missingFields.isEmpty && invalidJSONFields.isEmpty && !needsJustification && !needsConfirmation108    }109110    public func params() -> [String: JSONValue] {111        var out = values.filter { $0.value != .null }112        for f in fields {113            if case .json = f.kind, let raw = rawJSON[f.name], let v = try? JSONValue.parse(Data(raw.utf8)) { out[f.name] = v }114            if case .string(let s)? = out[f.name], s.isEmpty, !f.required { out[f.name] = nil }115        }116        return out117    }118119    public func request() throws -> API.CreateActionRequest {120        let p = params()121        let payload = p.isEmpty ? nil : try JSONValue.object(p).decode(API.CreateActionRequest.ParamsPayload.self)122        let j = justification.trimmingCharacters(in: .whitespacesAndNewlines)123        let c = confirmation.trimmingCharacters(in: .whitespacesAndNewlines)124        return API.CreateActionRequest(_type: type._type, target: target, params: payload, confirm: c.isEmpty ? nil : c, justification: j.isEmpty ? nil : j)125    }126127    /// The `Idempotency-Key` of the current content: the same for a re-submission of the same intent.128    public func idempotencyKey() throws -> String {129        let enc = JSONEncoder()130        enc.outputFormatting = [.sortedKeys]131        return tracker.key(forBody: String(decoding: try enc.encode(try request()), as: UTF8.self))132    }133134    /// Sends the request. On success `created` is set; on failure `error` holds the server's answer (precheck,135    /// confirmation mismatch, target locked...) and the form can be corrected and re-sent.136    @discardableResult137    public func submit(using actions: ActionsRepository) async -> API.Action? {138        guard canSubmit else { return nil }139        isSubmitting = true140        error = nil141        defer { isSubmitting = false }142        do {143            let action = try await actions.create(try request(), idempotencyKey: try idempotencyKey())144            tracker.complete()145            created = action146            return action147        } catch {148            self.error = APIError.from(error)149            return nil150        }151    }152}153154/// Follows one action until it reaches a final state: detail, event-driven updates and streamed output.155@MainActor156@Observable157public final class ActionRunModel {158    public let actionID: String159    @ObservationIgnored private let session: AppSession160    @ObservationIgnored private var poller: Task<Void, Never>?161162    public init(actionID: String, session: AppSession) {163        self.actionID = actionID164        self.session = session165    }166167    public var detail: Resource<API.ActionDetail> { session.actions.detail[actionID] }168    public var action: API.Action? { detail.value?.action }169    public var output: ActionOutputBuffer { session.actions.output(for: actionID) }170    public var isFinished: Bool { action?.state.isTerminal ?? false }171172    /// Loads the action and keeps it current. Events drive the updates; a slow poll covers a missing stream.173    public func start() {174        guard poller == nil else { return }175        poller = Task { [weak self] in176            guard let self else { return }177            await self.detail.load()178            await self.session.actions.refreshOutput(for: self.actionID)179            while !Task.isCancelled, !self.isFinished {180                try? await Task.sleep(for: .seconds(self.session.streamState.isConnected ? 10 : 2))181                if Task.isCancelled { return }182                await self.detail.load()183                await self.session.actions.refreshOutput(for: self.actionID)184            }185            await self.session.actions.refreshOutput(for: self.actionID)   // final catch-up186        }187    }188189    public func stop() { poller?.cancel(); poller = nil }190}191
Files main
Menu

Theme