Files
pokerfreak/mac/Sources/Cockpit/ServerProzess.swift
T
mmintel 9c79d8236b Acceptance 5.11.: channel play without AFK, quiet focus, working Cockpit, stronger play
- Practice tables: 20-min session 54/54 turns at the server, control session 28 turns,
  0 timeouts; stage: 3 tables, two rounds each, clean teardown.
- Never let the clock run: an engine abstention becomes check or fold (nie_verstreichen).
- Mittler join in a fixed order (kill the duplicate, then announce), a mittler ends with its
  game, the laufwache opens no tables, stop waits for the runner to stand up.
- Focus: no lobby connections from HUD, probes or layout; "Focus Window on Turn" off.
- Tables: disconnected or sitting-out opponents do not count; a table without channel is
  closed and avoided after 45 s; the join event keeps the writer's pid (strict invariants).
- Geldwache: same room list as the runner, the table's own report, stand up before closing.
- Engine: the small blind completes the top 65 % against limpers (price per fair share);
  the calling range of a bet is as wide as the villain calls - value bets into stations.
- Cockpit: the source tree never comes from SHELL; one operating set for laufwache and
  Cockpit (sicht/start.py --client, ServerStart).
- Project lives in ~/Projects/pokerfreak (kern was a detour).
2026-11-05 16:10:43 +01:00

154 lines
5.7 KiB
Swift

import CockpitKern
import Foundation
/// Startet die Datenschicht (python3 sicht/start.py) als Kind und haelt sie am Leben.
/// Die App kennt keinen Spielverstand und keine Protokolle - alles kommt ueber den Server.
@MainActor
final class ServerProzess {
enum Zustand: Equatable {
case startet
case laeuft(ServerAdresse)
case weg(String)
case belegt(Belegt) // ein anderes Cockpit (App oder Terminal) haelt die Sperre
case abgeloest(Belegt) // wir liefen, ein anderes hat uns per --uebernehmen abgeloest
}
private(set) var zustand: Zustand = .startet { didSet { beiAenderung?(zustand) } }
var beiAenderung: ((Zustand) -> Void)?
private var prozess: Process?
private var beendet = false
private var versuche = 0
private var liefSchon = false
private var belegtGesehen: Belegt?
private var naechstesMalUebernehmen = false
private var puffer = ""
/// Klon oder Client - gilt auch fuer Laeufer, die der Server startet (`ServerStart`).
var klon: Bool
init(klon: Bool) { self.klon = klon }
func starten() {
beendet = false
guard prozess == nil else { return }
zustand = .startet
let p = Process()
// Ueber eine interaktive Login-Shell (-i liest auch ~/.zshrc): Server und Laeufer brauchen
// dieselbe Umgebung wie im Terminal. Mit nur -l fand sich ein altes node (v20, ohne
// WebSocket) vor dem aus Homebrew, und lobby/cdp.mjs scheiterte.
p.executableURL = URL(filePath: "/bin/zsh")
let uebernehmen = naechstesMalUebernehmen
naechstesMalUebernehmen = false
belegtGesehen = nil
p.arguments = ["-ilc", ServerStart.befehl(klon: klon, uebernehmen: uebernehmen),
Orte.startSkript.path(percentEncoded: false)]
p.currentDirectoryURL = Orte.shell
p.environment = ServerStart.umgebung(ProcessInfo.processInfo.environment)
let aus = Pipe()
p.standardOutput = aus
p.standardError = aus
p.standardInput = FileHandle.nullDevice
aus.fileHandleForReading.readabilityHandler = { [weak self] h in
let d = h.availableData
guard !d.isEmpty, let text = String(data: d, encoding: .utf8) else { return }
Task { @MainActor in self?.lesen(text) }
}
p.terminationHandler = { [weak self] p in
let code = p.terminationStatus
Task { @MainActor in self?.weg(code) }
}
do {
try p.run()
prozess = p
} catch {
zustand = .weg("python3 startet nicht: \(error.localizedDescription)")
nachholen()
}
}
/// Elternprozess einer PID (ps), nil wenn es sie nicht gibt.
private static func eltern(von pid: Int32) -> Int32? {
let ps = Process()
ps.executableURL = URL(filePath: "/bin/ps")
ps.arguments = ["-o", "ppid=", "-p", String(pid)]
let aus = Pipe()
ps.standardOutput = aus
ps.standardError = FileHandle.nullDevice
guard (try? ps.run()) != nil else { return nil }
ps.waitUntilExit()
let text = String(data: aus.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
return Int32(text.trimmingCharacters(in: .whitespacesAndNewlines))
}
func beenden() {
beendet = true
prozess?.terminate()
prozess = nil
}
/// Das laufende Cockpit (App oder Terminal) abloesen: es bekommt SIGINT und raeumt auf.
func uebernehmen() {
beenden()
naechstesMalUebernehmen = true
versuche = 0
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in self?.starten() }
}
func neuStarten(klon: Bool) {
self.klon = klon
beenden()
versuche = 0
// Der alte Prozess gibt den Port frei, der neue sucht sich notfalls den naechsten.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in self?.starten() }
}
private func lesen(_ text: String) {
puffer += text
while let i = puffer.firstIndex(of: "\n") {
let zeile = String(puffer[..<i]).trimmingCharacters(in: .whitespaces)
puffer.removeSubrange(...i)
if let b = Belegt(startzeile: zeile) {
belegtGesehen = b
} else if let a = ServerAdresse(startzeile: zeile) {
versuche = 0
liefSchon = true
Protokoll.schreiben("Server auf Port \(a.port)")
zustand = .laeuft(a)
} else if !zeile.isEmpty {
Protokoll.schreiben("Server: " + zeile)
letzteZeile = zeile
}
}
}
private var letzteZeile = ""
private func weg(_ code: Int32) {
prozess = nil
guard !beendet else { return }
if let b = belegtGesehen {
// Kein Neuversuch: es darf nur ein Cockpit laufen. Nur der Server einer toten App
// (Absturz, kill -9) wird ohne Rueckfrage abgeloest.
if !liefSchon, b.verwaist(elternPid: Self.eltern(von: b.pid)) {
Protokoll.schreiben("übernehme verwaisten App-Server \(b.pid)")
uebernehmen()
return
}
beendet = true
zustand = liefSchon ? .abgeloest(b) : .belegt(b)
return
}
zustand = .weg(letzteZeile.isEmpty ? "Server beendet (\(code))" : letzteZeile)
nachholen()
}
private func nachholen() {
versuche += 1
let warten = min(15.0, pow(2.0, Double(versuche)))
DispatchQueue.main.asyncAfter(deadline: .now() + warten) { [weak self] in
guard let self, !self.beendet else { return }
self.starten()
}
}
}