SPB Git

Repository Public

ServerConfiguration.swift 8.8 KB 199 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Local Chat9// File             : Services/LocalAPIServer/Sources/ServerConfiguration.swift10// Description      : Local API server settings, errors, per-client rate11//                    limiting and the bounded request log (never stores prompt12//                    content).13// Module           : Services14// Repository       : https://git.spboucher.ai/local-chat15// Created          : 2026-11-2016// Last Modified    : 2026-11-2017//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import LocalChatCore9293public struct ServerConfiguration: Codable, Sendable, Hashable {94    public var port: UInt16                 // 0 = any free port95    public var exposeOnLAN: Bool            // false = loopback only (127.0.0.1)96    public var requireAuth: Bool            // ignored (forced on) when exposeOnLAN is true97    public var rateLimitPerMinute: Int      // requests per minute per key (or per client address); 0 = unlimited98    public var allowedOrigins: [String]     // browser origins allowed by CORS, e.g. "http://localhost:3000"; empty = none99    public var maxBodyBytes: Int100101    public init(port: UInt16 = 8765, exposeOnLAN: Bool = false, requireAuth: Bool = false, rateLimitPerMinute: Int = 120,102                allowedOrigins: [String] = [], maxBodyBytes: Int = 64 * 1_048_576) {103        self.port = port; self.exposeOnLAN = exposeOnLAN; self.requireAuth = requireAuth; self.rateLimitPerMinute = rateLimitPerMinute104        self.allowedOrigins = allowedOrigins; self.maxBodyBytes = maxBodyBytes105    }106107    /// A server reachable from the network always requires an API key.108    public var authenticationRequired: Bool { requireAuth || exposeOnLAN }109}110111public enum ServerError: LocalizedError, Sendable, Equatable {112    case portInUse(UInt16)113    case alreadyRunning114    case startFailed(String)115    public var errorDescription: String? {116        switch self {117        case .portInUse(let p): "Port \(p) is already in use by another application. Choose another port."118        case .alreadyRunning: "The server is already running."119        case .startFailed(let m): "The server could not start: \(m)"120        }121    }122}123124/// Token bucket per client: `limit` requests per minute, bursts up to `limit`.125public actor RateLimiter {126    private struct Bucket { var tokens: Double; var updated: Date }127    private var buckets: [String: Bucket] = [:]128    public let limitPerMinute: Int129    public init(limitPerMinute: Int) { self.limitPerMinute = limitPerMinute }130131    /// Returns nil when the request may proceed, else the number of seconds to wait.132    public func check(_ client: String, now: Date = Date()) -> Int? {133        guard limitPerMinute > 0 else { return nil }134        let capacity = Double(limitPerMinute), rate = capacity / 60135        var bucket = buckets[client] ?? Bucket(tokens: capacity, updated: now)136        bucket.tokens = min(capacity, bucket.tokens + max(0, now.timeIntervalSince(bucket.updated)) * rate); bucket.updated = now137        defer {138            buckets[client] = bucket139            if buckets.count > 4096 { buckets = buckets.filter { now.timeIntervalSince($0.value.updated) < 120 } }140        }141        if bucket.tokens >= 1 { bucket.tokens -= 1; return nil }142        return max(1, Int(((1 - bucket.tokens) / rate).rounded(.up)))143    }144}145146public struct RequestLogEntry: Sendable, Hashable, Identifiable, Codable {147    public var id: UUID148    public var time: Date149    public var method: String150    public var path: String151    public var status: Int152    public var keyLabel: String?153    public var clientAddress: String?154    public var duration: TimeInterval155    public var model: String?156    public var streamed: Bool157    public var promptTokens: Int?158    public var completionTokens: Int?159    public var tokensPerSecond: Double?160    public var error: String?161    public init(id: UUID = UUID(), time: Date = Date(), method: String, path: String, status: Int, keyLabel: String? = nil, clientAddress: String? = nil,162                duration: TimeInterval = 0, model: String? = nil, streamed: Bool = false, promptTokens: Int? = nil, completionTokens: Int? = nil,163                tokensPerSecond: Double? = nil, error: String? = nil) {164        self.id = id; self.time = time; self.method = method; self.path = path; self.status = status; self.keyLabel = keyLabel165        self.clientAddress = clientAddress; self.duration = duration; self.model = model; self.streamed = streamed166        self.promptTokens = promptTokens; self.completionTokens = completionTokens; self.tokensPerSecond = tokensPerSecond; self.error = error167    }168}169170/// Bounded ring buffer of request diagnostics, observable live.171public actor RequestLog {172    public let capacity: Int173    private var entries: [RequestLogEntry] = []174    private var observers: [UUID: AsyncStream<RequestLogEntry>.Continuation] = [:]175    public private(set) var totalRequests = 0176177    public init(capacity: Int = 500) { self.capacity = max(1, capacity) }178179    public func append(_ entry: RequestLogEntry) {180        entries.append(entry); totalRequests += 1181        if entries.count > capacity { entries.removeFirst(entries.count - capacity) }182        for observer in observers.values { observer.yield(entry) }183    }184185    /// Oldest first.186    public func snapshot() -> [RequestLogEntry] { entries }187    public func clear() { entries.removeAll() }188189    /// Entries logged from now on.190    public func stream() -> AsyncStream<RequestLogEntry> {191        let id = UUID()192        return AsyncStream(bufferingPolicy: .bufferingNewest(200)) { continuation in193            observers[id] = continuation194            continuation.onTermination = { _ in Task { await self.removeObserver(id) } }195        }196    }197    private func removeObserver(_ id: UUID) { observers[id] = nil }198}199
Files main
Menu

Theme