Repository Public
1import Foundation2import Observation34/// Finds the occurrences of a query in a log text (case-insensitive, literal — never a pattern).5public enum LogSearch {6 public static func ranges(of query: String, in text: String, limit: Int = 5000) -> [NSRange] {7 let q = query.trimmingCharacters(in: .whitespacesAndNewlines)8 guard !q.isEmpty else { return [] }9 let ns = text as NSString10 var out: [NSRange] = []11 var search = NSRange(location: 0, length: ns.length)12 while search.length > 0, out.count < limit {13 let r = ns.range(of: q, options: [.caseInsensitive, .literal], range: search)14 if r.location == NSNotFound { break }15 out.append(r)16 let next = r.location + max(r.length, 1)17 search = NSRange(location: next, length: ns.length - next)18 }19 return out20 }2122 /// Index after `current` going forward or backward, wrapping around; nil when there is no match.23 public static func step(from current: Int, count: Int, forward: Bool) -> Int? {24 guard count > 0 else { return nil }25 return ((current + (forward ? 1 : -1)) % count + count) % count26 }27}2829/// Bounded log reading of one service through the typed action `service.logs.tail` (there is no other way to read30/// logs: no free-form command). Each request is an ordinary, audited action; "follow" simply repeats it.31@MainActor32@Observable33public final class LogsTailModel {34 public enum Phase: Sendable, Equatable {35 case preparing36 /// The catalog cannot be read (501/503/403/offline).37 case catalogUnavailable(UnavailableReason)38 /// `service.logs.tail` is absent from the catalog.39 case typeMissing40 /// The type exists with `available=false`.41 case typeDisabled(reason: String?)42 case ready43 }4445 public static let typeName = "service.logs.tail"4647 public let serviceID: String48 public let serviceName: String49 public private(set) var phase: Phase = .preparing50 public private(set) var catalogError: APIError?51 public private(set) var type: API.ActionType?52 /// Text of the most recent tail that produced output (kept on screen while the next one runs).53 public private(set) var text = ""54 public private(set) var receivedAt: Date?55 public private(set) var isRequesting = false56 /// Why the last request was refused or failed (`403`, `422 agent_offline`, ...), with its correlation id.57 public private(set) var requestError: APIError?58 public private(set) var lastAction: API.Action?59 public private(set) var truncated = false60 public private(set) var requestCount = 061 public var follow = false { didSet { if follow != oldValue { followChanged() } } }62 public var followInterval: TimeInterval = 563 /// Value of the line-count parameter, when the schema declares one.64 public var lineCount: Int?6566 @ObservationIgnored private let session: AppSession67 @ObservationIgnored private var followTask: Task<Void, Never>?68 @ObservationIgnored private var run: ActionRunModel?69 @ObservationIgnored private var values: [String: JSONValue] = [:]7071 public init(serviceID: String, serviceName: String, session: AppSession) {72 self.serviceID = serviceID73 self.serviceName = serviceName74 self.session = session75 }7677 /// The integer parameter that bounds the number of lines, if the catalog's schema has one.78 public var lineField: SchemaField? {79 guard let type else { return nil }80 let fields = SchemaField.fields(from: JSONValue(type.paramsSchema.additionalProperties))81 return fields.first { f in82 if case .integer = f.kind { return ["lines", "line_count", "tail", "limit", "n", "max_lines"].contains(f.name) }83 return false84 }85 }8687 public var lineRange: ClosedRange<Int> {88 if case .integer(let lo, let hi)? = lineField?.kind { return max(1, lo ?? 1)...max(max(1, lo ?? 1), hi ?? 500) }89 return 1...50090 }9192 /// `outcome_unknown`: the command was delivered but its result never came back.93 public var outcomeUnknown: Bool { lastAction?.outcomeUnknown ?? false }9495 public func prepare() async {96 phase = .preparing97 await session.actions.types.loadIfNeeded(maxAge: 300)98 guard session.actions.types.value != nil else {99 catalogError = session.actions.types.state.error100 phase = .catalogUnavailable(session.actions.types.state.unavailableReason ?? .serviceUnavailable(code: catalogError?.code ?? "unavailable"))101 return102 }103 guard let t = session.actions.type(named: Self.typeName), t.targetKinds.contains(.service) else { phase = .typeMissing; return }104 type = t105 guard t.available else { phase = .typeDisabled(reason: t.unavailableReason); return }106 if let f = lineField, lineCount == nil { lineCount = f.defaultValue?.intValue ?? min(200, lineRange.upperBound) }107 phase = .ready108 }109110 /// Requests one tail and follows it to its end.111 public func request() async {112 guard phase == .ready, let type, !isRequesting else { return }113 isRequesting = true114 defer { isRequesting = false }115 requestError = nil116 var preset = values117 if let f = lineField, let n = lineCount { preset[f.name] = .number(Double(min(max(n, lineRange.lowerBound), lineRange.upperBound))) }118 let form = ActionFormModel(type: type, target: .init(kind: .service, id: serviceID), targetLabel: serviceName, presetParams: preset)119 requestCount += 1120 guard let action = await form.submit(using: session.actions) else {121 requestError = form.error ?? APIError(code: "client.incomplete", message: "The log request is incomplete: \(form.missingFields.joined(separator: ", "))")122 return123 }124 lastAction = action125 let runner = ActionRunModel(actionID: action.id, session: session)126 run = runner127 runner.start()128 while !runner.isFinished, !Task.isCancelled {129 try? await Task.sleep(for: .milliseconds(250))130 if runner.detail.state.error != nil, runner.action == nil { break }131 publish(from: runner, final: false)132 }133 await session.actions.refreshOutput(for: action.id)134 publish(from: runner, final: true)135 runner.stop()136 }137138 private func publish(from runner: ActionRunModel, final: Bool) {139 if let a = runner.action { lastAction = a }140 let out = runner.output.text141 if !out.isEmpty || final {142 if !out.isEmpty || lastAction?.state == .succeeded { text = out; receivedAt = Date() }143 truncated = runner.output.truncated144 }145 if final, let a = runner.action, a.state != .succeeded {146 requestError = APIError(status: nil, code: a.errorCode ?? a.state.rawValue, message: a.errorMessage ?? a.state.label, correlationID: a.correlationId)147 } else if final, runner.action == nil, let e = runner.detail.state.error {148 requestError = e149 }150 }151152 private func followChanged() {153 followTask?.cancel()154 followTask = nil155 guard follow else { return }156 followTask = Task { [weak self] in157 while !Task.isCancelled {158 guard let self else { return }159 await self.request()160 // A refusal will not fix itself by repeating: stop following and leave the reason on screen.161 if let e = self.requestError, e.status != nil { self.follow = false; return }162 try? await Task.sleep(for: .seconds(self.followInterval))163 }164 }165 }166167 /// Stops following (window closed).168 public func stop() {169 follow = false170 followTask?.cancel()171 followTask = nil172 run?.stop()173 }174}175