BroV Ops: two addresses (home LAN and outside via Traefik), picked automatically
- OpsClient probes /api/health on the home address, then the outside one, keeps the one that answered for a minute and re-probes after any failure (the home router has no NAT loopback, so at home only the LAN address works, away only the outside one). Settings: «Адрес дома» + «Адрес снаружи». - ops/deploy/TRAEFIK.md: instructions for publishing /api/ via Traefik (HTTPS, /api/ only, Authorization untouched, rate limit, ≥150 s timeouts for /api/say, checks). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -76,7 +76,8 @@ struct OpsRoutine: Identifiable, Equatable {
|
||||
@MainActor
|
||||
final class OpsClient: ObservableObject {
|
||||
static let shared = OpsClient()
|
||||
static let urlKey = "opsURL"
|
||||
static let urlKey = "opsURL" // at home: http://192.168.10.106:8787
|
||||
static let extKey = "opsURLExternal" // away: https://ops.sanjeev.ru (Traefik)
|
||||
static let tokenKey = "brov-ops-token"
|
||||
|
||||
@Published var agenda = OpsAgenda()
|
||||
@@ -98,6 +99,36 @@ final class OpsClient: ObservableObject {
|
||||
var baseURL: String {
|
||||
(UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
var externalURL: String {
|
||||
(UserDefaults.standard.string(forKey: Self.extKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
private var candidates: [String] {
|
||||
[baseURL, externalURL].map { $0.hasSuffix("/") ? String($0.dropLast()) : $0 }.filter { !$0.isEmpty }
|
||||
}
|
||||
|
||||
/// The address that answered last (home LAN or the outside one), re-checked every minute
|
||||
/// and after any failure. The home router can't reach its own public address, so at home
|
||||
/// only the LAN one works, away only the outside one.
|
||||
private var activeBase: String?
|
||||
private var activeCheckedAt = Date.distantPast
|
||||
@Published var via: String = "" // «дома» / «снаружи», for the UI
|
||||
|
||||
private func pickBase() async -> String? {
|
||||
if let a = activeBase, Date().timeIntervalSince(activeCheckedAt) < 60 { return a }
|
||||
for base in candidates {
|
||||
guard let url = URL(string: base + "/api/health") else { continue }
|
||||
var req = URLRequest(url: url, timeoutInterval: 3)
|
||||
req.cachePolicy = .reloadIgnoringLocalCacheData
|
||||
if let (_, resp) = try? await URLSession.shared.data(for: req), (resp as? HTTPURLResponse)?.statusCode == 200 {
|
||||
activeBase = base
|
||||
activeCheckedAt = Date()
|
||||
via = base == candidates.first && !baseURL.isEmpty ? "дома" : "снаружи"
|
||||
return base
|
||||
}
|
||||
}
|
||||
activeBase = nil
|
||||
return nil
|
||||
}
|
||||
/// Read once from the Keychain, updated by Settings.
|
||||
var token: String = OpsClient.loadToken()
|
||||
|
||||
@@ -115,10 +146,11 @@ final class OpsClient: ObservableObject {
|
||||
}
|
||||
return Keychain.load(key: tokenKey) ?? ""
|
||||
}
|
||||
var configured: Bool { !baseURL.isEmpty && !token.isEmpty }
|
||||
var configured: Bool { !candidates.isEmpty && !token.isEmpty }
|
||||
|
||||
private func request(_ path: String, body: [String: Any]? = nil, timeout: TimeInterval = 8) async -> Any? {
|
||||
guard configured, let url = URL(string: baseURL + path) else { reachable = nil; return nil }
|
||||
guard configured else { reachable = nil; return nil }
|
||||
guard let base = await pickBase(), let url = URL(string: base + path) else { reachable = false; return nil }
|
||||
var req = URLRequest(url: url, timeoutInterval: timeout)
|
||||
req.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
|
||||
if let body {
|
||||
@@ -133,6 +165,7 @@ final class OpsClient: ObservableObject {
|
||||
return try JSONSerialization.jsonObject(with: data)
|
||||
} catch {
|
||||
reachable = false
|
||||
activeBase = nil // try the other address next time
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -156,6 +189,8 @@ final class OpsClient: ObservableObject {
|
||||
agenda = a
|
||||
}
|
||||
|
||||
func forgetAddress() { activeBase = nil }
|
||||
|
||||
func refreshAll() async {
|
||||
await refresh()
|
||||
if let arr = await request(showDone ? "/api/tasks?all=1" : "/api/tasks") as? [[String: Any]] {
|
||||
@@ -304,7 +339,7 @@ struct OpsPanel: View {
|
||||
if !ops.configured {
|
||||
note("Сервис дел не подключён: Настройки → Чат → «Дела (хоумлаб)».", "#B0B5BE")
|
||||
} else if ops.reachable == false {
|
||||
note("Сервис дел не отвечает. Ты не дома? Включи сеть «Дом» в 🌐.", "#FB923C")
|
||||
note("Сервис дел не отвечает ни по домашнему адресу, ни по внешнему (Настройки → Чат → «Дела»).", "#FB923C")
|
||||
}
|
||||
|
||||
HStack(spacing: 6) {
|
||||
@@ -548,26 +583,30 @@ struct OpsRow: View {
|
||||
|
||||
struct OpsSettingsBox: View {
|
||||
@State private var url = UserDefaults.standard.string(forKey: OpsClient.urlKey) ?? ""
|
||||
@State private var ext = UserDefaults.standard.string(forKey: OpsClient.extKey) ?? ""
|
||||
@State private var token = Keychain.load(key: OpsClient.tokenKey) ?? ""
|
||||
@State private var status: String?
|
||||
|
||||
var body: some View {
|
||||
GroupBox("Дела (хоумлаб)") {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Сервис дел на виртуалке хоумлаба: задачи, подписки, регламент. Адрес вида http://192.168.10.50:8787, токен — API_TOKEN из /etc/brov-ops/config.env на ВМ (хранится в Связке ключей).")
|
||||
Text("Сервис дел на виртуалке хоумлаба. Два адреса: домашний (http://192.168.10.106:8787) и снаружи через Traefik (https://ops.sanjeev.ru) — BroV сам берёт тот, что отвечает. Токен — API_TOKEN из /etc/brov-ops/config.env на ВМ (хранится в Связке ключей).")
|
||||
.font(.system(size: 11)).foregroundColor(.secondary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
TextField("Адрес сервиса", text: $url).textFieldStyle(.roundedBorder)
|
||||
TextField("Адрес дома", text: $url).textFieldStyle(.roundedBorder)
|
||||
TextField("Адрес снаружи (необязательно)", text: $ext).textFieldStyle(.roundedBorder)
|
||||
SecureField("Токен", text: $token).textFieldStyle(.roundedBorder)
|
||||
HStack {
|
||||
Button("Сохранить и проверить") {
|
||||
UserDefaults.standard.set(url.trimmingCharacters(in: .whitespacesAndNewlines), forKey: OpsClient.urlKey)
|
||||
UserDefaults.standard.set(ext.trimmingCharacters(in: .whitespacesAndNewlines), forKey: OpsClient.extKey)
|
||||
OpsClient.shared.forgetAddress()
|
||||
let t = token.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
Keychain.save(key: OpsClient.tokenKey, value: t)
|
||||
OpsClient.shared.token = t
|
||||
Task {
|
||||
await OpsClient.shared.refresh()
|
||||
status = OpsClient.shared.reachable == true ? "✓ Подключено" : "✗ Не отвечает или неверный токен"
|
||||
status = OpsClient.shared.reachable == true ? "✓ Подключено (\(OpsClient.shared.via))" : "✗ Не отвечает или неверный токен"
|
||||
}
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
|
||||
Reference in New Issue
Block a user