package server import ( "context" "errors" "os" "os/exec" "syscall" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // Live output flow of a run: output is pushed as soon as it arrives, oldest // first, while the session's watchers keep their queues short // (chatShellBacklog frames). While chatShellWindow bytes wait unpushed the // command's output is not read, so the command waits for its watchers. A // watcher that has not drained for chatShellStall stops holding it: the // output then skips to the newest chunk, a gap the client shows. While output // streams, a frame waits up to chatShellRetry for more to join it. const ( chatShellBacklog = 8 chatShellWindow = 256 << 10 chatShellStall = 3 * time.Second chatShellRetry = 2 * time.Millisecond ) // supervise reads one command's merged output (or terminal stream), streams // it live, saves it periodically and records how the command ended. It owns // the reader. func (r *chatShellRunner) supervise(p *chatShellProcess, reader *os.File) { defer r.wg.Done() defer close(p.done) readDone, exitedCh := make(chan struct{}), make(chan struct{}) go func() { defer close(readDone) buffer := make([]byte, 32<<10) for { p.awaitPushed(exitedCh) n, err := reader.Read(buffer) if n > 0 { p.mu.Lock() if !p.closed { p.out.write(buffer[:n]) } p.mu.Unlock() signalChatShell(p.wake) } if err != nil { return } } }() waitDone := make(chan error, 1) go func() { waitDone <- p.cmd.Wait() }() pid := p.cmd.Process.Pid flush := time.NewTicker(r.flush) defer flush.Stop() lastSaved := r.now() var waitErr error var drainDone, retry <-chan time.Time var flow chatShellFlow exited, drained, shutdown := false, false, false base := r.base.Done() push := func() { retry = nil if r.pushOutput(p, &flow) { retry = time.After(chatShellRetry) } } for !exited || !drained { select { case <-p.wake: push() case <-retry: push() case <-flush.C: push() if r.now().Sub(lastSaved) >= r.persist { lastSaved = r.now() r.save(p.snapshot(protocol.ChatShellRunRetained)) } case waitErr = <-waitDone: exited = true close(exitedCh) // Descendants may hold the pipe or terminal open; read what // they write briefly, then stop reading. A terminal may not // support deadlines, so the timer also ends the wait. _ = reader.SetReadDeadline(time.Now().Add(chatShellDrain)) drainDone = time.After(chatShellDrain + chatShellDrain/2) case <-drainDone: drained = true readDone = nil case <-readDone: drained = true readDone = nil case <-base: base = nil shutdown = true _ = syscall.Kill(-pid, syscall.SIGKILL) } } // Nothing in the command's group outlives it. _ = syscall.Kill(-pid, syscall.SIGKILL) p.mu.Lock() reader.Close() p.closed = true p.mu.Unlock() for r.emitOutput(p, true) { } p.mu.Lock() finishChatShellRecord(&p.record, waitErr, p.stopped, shutdown || r.base.Err() != nil, r.now()) p.mu.Unlock() record := p.snapshot(protocol.ChatShellRunRetained) r.save(record) r.mu.Lock() delete(r.active, p.record.ID) r.mu.Unlock() r.publishRun(record) } // finishChatShellRecord records how a command ended. A requested stop wins // over the exit status it caused; a server shutdown marks it interrupted. func finishChatShellRecord(record *protocol.ChatShellRunRecord, waitErr error, stopped, shutdown bool, now time.Time) { record.EndedAt = now.UnixMilli() record.DurationMS = max(record.EndedAt-record.StartedAt, 0) var exitErr *exec.ExitError switch { case waitErr == nil: code := 0 record.ExitCode = &code case errors.As(waitErr, &exitErr): if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() { record.Signal = status.Signal().String() } else { code := exitErr.ExitCode() record.ExitCode = &code } default: record.Error = waitErr.Error() } switch { case shutdown: record.Status = protocol.ChatShellRunInterrupted record.Error = chatShellInterruptedReason case stopped: record.Status = protocol.ChatShellRunStopped case record.Error != "": record.Status = protocol.ChatShellRunFailed default: record.Status = protocol.ChatShellRunExited } } // chatShellFlow is one run's live push state: held is when its watchers // were first found behind, paced when a stalled push last went out, last // when a frame last went out. type chatShellFlow struct { held, paced, last time.Time } // pushOutput pushes the unpushed output, oldest first, while the session's // watchers drain; it reports whether output still waits for them. Watchers // behind for chatShellStall get the old pacing until they catch up: the // newest chunk once per flush interval, the rest skipped (a gap). func (r *chatShellRunner) pushOutput(p *chatShellProcess, flow *chatShellFlow) bool { for { if r.backlog != nil && r.backlog(p.sessionID()) >= chatShellBacklog { now := time.Now() if flow.held.IsZero() { flow.held = now } if now.Sub(flow.held) < chatShellStall { return true } p.mu.Lock() p.out.skipUnemitted(protocol.ChatShellRunChunkLimit) p.mu.Unlock() signalChatShell(p.room) if now.Sub(flow.paced) >= r.flush { flow.paced = now r.emitOutput(p, false) } return true } flow.held = time.Time{} p.mu.Lock() waiting := p.out.unemitted() p.mu.Unlock() if waiting > 0 && waiting < protocol.ChatShellRunChunkLimit && time.Since(flow.last) < chatShellRetry { return true // streaming: let the rest gather into one frame } if !r.emitOutput(p, false) { return false } flow.last = time.Now() } } // emitOutput pushes the oldest output not pushed yet (one frame) and // reports whether there was any. func (r *chatShellRunner) emitOutput(p *chatShellProcess, final bool) bool { p.mu.Lock() text, offset, end, ok := p.out.pending(protocol.ChatShellRunChunkLimit, final) sessionID, runID := p.record.SessionID, p.record.ID p.mu.Unlock() if !ok { return false } signalChatShell(p.room) if r.publish != nil { r.publish(sessionID, protocol.ChatShellRunEventFrame{SessionID: sessionID, RunID: runID, Output: text, Offset: offset, End: end}) } return true } func (p *chatShellProcess) sessionID() string { p.mu.Lock() defer p.mu.Unlock() return p.record.SessionID } // awaitPushed holds the reader while chatShellWindow bytes wait unpushed, // until the command exited (its output is then drained regardless). func (p *chatShellProcess) awaitPushed(exited <-chan struct{}) { for { p.mu.Lock() waiting := p.out.unemitted() >= chatShellWindow p.mu.Unlock() if !waiting { return } select { case <-p.room: case <-exited: return } } } func signalChatShell(ch chan struct{}) { select { case ch <- struct{}{}: default: } } // save persists a record; a shutdown's base context is already canceled, so // it uses its own bounded context. func (r *chatShellRunner) save(record protocol.ChatShellRunRecord) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() _ = r.store.SaveChatShellRun(ctx, record, protocol.ChatShellRunHistory) }