Files
archie/internal/webui/tasks_sandbox.go
T
sam 0a37b551f5
Quality / check (push) Successful in 3m47s
deploy / gate (push) Successful in 4m32s
deploy / archied-image (push) Successful in 2m51s
deploy / agent-image (push) Successful in 10s
deploy / dist-zip (push) Skipped
refactor(webui): extract the tasks resource module (#1778)
2026-11-03 08:06:56 +11:00

72 lines
2.6 KiB
Go

package webui
import (
"context"
"io"
"net/http"
"strings"
"golang.org/x/net/websocket"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// SandboxView follows a running task attempt's sandbox output, read-only. A
// finished or unknown attempt is refused with a gRPC status whose message
// states why. The implementation belongs to a process that owns containers;
// the dashboard consumes it over a contract and never links one. Nil answers
// 503.
type SandboxView interface {
OpenRun(ctx context.Context, orgID string, taskID, attempt int64) (io.ReadCloser, error)
}
// handleTaskSandbox streams a running attempt's sandbox output to a WebSocket.
// Reading it is the same authority as reading the task's log, decided before
// this handler runs. Input from the browser is discarded: a view has no stdin.
func (a *tasksAPI) handleTaskSandbox(w http.ResponseWriter, r *http.Request) {
if a.sandbox == nil {
http.Error(w, "sandbox view not configured", http.StatusServiceUnavailable)
return
}
if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired)
return
}
t, attempt, ok := a.taskAttemptTarget(w, r)
if !ok {
return
}
// The refusal rides the socket as text, not as an HTTP status: a browser
// WebSocket cannot read a failed upgrade's body, and the operator's only
// honest account of why there is no view is the daemon's stated reason.
//nolint:contextcheck // websocket.Handler has no context parameter; the handler derives its context from ws.Request()
websocket.Handler(func(ws *websocket.Conn) {
defer func() { _ = ws.Close() }()
ctx, cancel := context.WithCancel(ws.Request().Context())
defer cancel()
go func() { _, _ = io.Copy(io.Discard, ws); cancel() }()
view, err := a.sandbox.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt))
if err != nil {
a.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt)
_, _ = io.WriteString(ws, sandboxRefusal(err))
return
}
defer func() { _ = view.Close() }()
stopClose := context.AfterFunc(ctx, func() { _ = view.Close() })
defer stopClose()
ws.PayloadType = websocket.BinaryFrame
if _, err := io.Copy(ws, view); err != nil && ctx.Err() == nil {
_ = websocket.Message.Send(ws, sandboxRefusal(err))
}
}).ServeHTTP(w, r)
}
// sandboxRefusal is the reason shown to the operator.
func sandboxRefusal(err error) string {
if st, ok := status.FromError(err); ok && st.Message() != "" {
return st.Message()
}
return "the sandbox view is unavailable"
}