package daemon import ( "context" "errors" "fmt" "io" "net/http" "strings" "sync" "time" "albedo/cli/internal/daemon/protocol" ) const completedActionTimeout = 200 * time.Second type ReloadRequest struct{ Target string } type SessionReloadResult protocol.ReloadResult type KernelUpgradeResult protocol.KernelUpgradeResult type KernelRestartResult protocol.KernelRestartResult type CompactionResult protocol.CompactionResult func ReloadSession(ctx context.Context, conn *Connection, id string, request ReloadRequest) (SessionReloadResult, error) { var w protocol.ReloadResult err := executeMutation(ctx, conn, operation{Name: "reload session", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewReloadSessionRequestWithBody(base, id, "application/json", body) }, Body: protocol.ReloadRequest{Target: optionalText(request.Target)}, Policy: noRecovery, Timeout: completedActionTimeout}, []int{200}, func(data []byte, _ int) error { if err := decodeRequired(data, &w); err != nil { return err } if w.CachePolicy != nil && (w.CachePolicy.State != "refreshed" && w.CachePolicy.State != "failed" || (w.CachePolicy.State == "failed") != (w.CachePolicy.Failure != nil)) { return fieldError("cache policy reload outcome") } return nil }) return SessionReloadResult(w), err } func (r SessionReloadResult) Message() string { message := "Reload completed." if r.Session != nil { if r.Session.State != "applied" { message = "Session reload " + r.Session.State + "." } if r.Session.RestartRequired { message += " Kernel restart required." } if r.Session.Failure != nil { message = r.Session.Failure.Detail } for _, warning := range r.Session.Warnings { message += " " + warning.Detail } } for _, model := range r.Models { if model.Failure != nil { message += " " + model.Failure.Detail } } if r.CachePolicy != nil && r.CachePolicy.Failure != nil { message += " Cache policy reload failed: " + r.CachePolicy.Failure.Detail } return message } func UpgradeKernel(ctx context.Context, conn *Connection, id string) (KernelUpgradeResult, error) { var w protocol.KernelUpgradeResult err := executeMutation(ctx, conn, operation{Name: "upgrade kernel", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewUpgradeKernelRequestWithBody(base, id, "application/json", body) }, Body: struct{}{}, Policy: noRecovery, Timeout: completedActionTimeout}, []int{200}, func(data []byte, _ int) error { return decodeRequired(data, &w) }) return KernelUpgradeResult(w), err } func (r KernelUpgradeResult) Message() string { var message strings.Builder fmt.Fprintf(&message, "Kernel %s; %d background jobs stopped.", r.State, len(r.StoppedJobs)) for _, warning := range r.Warnings { message.WriteByte(' ') message.WriteString(warning.Detail) } if r.Failure != nil { message.WriteByte(' ') message.WriteString(r.Failure.Detail) } return message.String() } func RestartKernel(ctx context.Context, conn *Connection, id string) (KernelRestartResult, error) { var w protocol.KernelRestartResult err := executeMutation(ctx, conn, operation{Name: "restart kernel", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewRestartKernelRequestWithBody(base, id, "application/json", body) }, Body: struct{}{}, Policy: noRecovery, Timeout: completedActionTimeout}, []int{200}, func(data []byte, _ int) error { return decodeRequired(data, &w) }) return KernelRestartResult(w), err } func (r KernelRestartResult) Message() string { return fmt.Sprintf("Kernel restarted; %d background jobs stopped, %d cells ended.", len(r.StoppedJobs), len(r.EndedCells)) } func CompactSession(ctx context.Context, conn *Connection, id, strategy string) (CompactionResult, error) { return CompactSessionWithToken(ctx, conn, id, strategy, "") } type compactionClient struct{ session, token string } type pendingCompaction struct { mu sync.Mutex handle *OperationHandle strategy string } // CompactSessionWithToken lets an ACP attachment holder compact its own session. func CompactSessionWithToken(ctx context.Context, conn *Connection, id, strategy, token string) (CompactionResult, error) { ctx, cancel := context.WithTimeout(ctx, completedActionTimeout) defer cancel() key := compactionClient{id, token} entry, _ := conn.compactions.LoadOrStore(key, &pendingCompaction{}) pending := entry.(*pendingCompaction) if !pending.mu.TryLock() { return CompactionResult{}, errors.New("compaction is already being observed") } defer pending.mu.Unlock() if active, ok := conn.compactions.Load(key); !ok || active != pending { return CompactionResult{}, errors.New("compaction has already been observed") } var err error resumed := pending.handle != nil if !resumed { pending.handle, err = NewCompaction(id, strategy, token) if err != nil { conn.compactions.CompareAndDelete(key, pending) return CompactionResult{}, err } pending.strategy = strategy } handle := pending.handle if strategy != pending.strategy { return CompactionResult{}, fmt.Errorf("resolve compaction %s before changing its intent", handle.ID()) } submitted := !resumed var receipt protocol.CompactionReceipt if resumed { receipt, err = ReadCompaction(ctx, conn, handle) if api, ok := errors.AsType[*APIError](err); ok && api.Code == "compaction_unknown" { submitted = true receipt, err = SubmitCompaction(ctx, conn, handle) } } else { receipt, err = SubmitCompaction(ctx, conn, handle) } if err != nil { if submitted { if _, uncertain := errors.AsType[*UncertainOutcomeError](err); !uncertain && !IsOperationExpired(err) { conn.compactions.CompareAndDelete(key, pending) } } return CompactionResult{}, err } for delay := 200 * time.Millisecond; receipt.State == "running"; delay = min(2*time.Second, delay*2) { timer := time.NewTimer(delay) select { case <-ctx.Done(): timer.Stop() return CompactionResult{}, uncertainOperation(handle.operation, ctx.Err()) case <-timer.C: } receipt, err = ReadCompaction(ctx, conn, handle) if err != nil { return CompactionResult{}, uncertainOperation(handle.operation, err) } } conn.compactions.CompareAndDelete(key, pending) if receipt.State == "interrupted" { return CompactionResult{}, fmt.Errorf("compaction %s was interrupted; inspect context before starting another action", handle.ID()) } if receipt.Result == nil { return CompactionResult{}, fieldError("compaction result") } return CompactionResult(*receipt.Result), nil } // NewCompaction freezes an identity and intent that can be retained across an // uncertain response. SubmitCompaction may repeat only this same handle. func NewCompaction(session, strategy, token string) (*OperationHandle, error) { id, err := operationID() if err != nil { return nil, err } params := &protocol.PutCompactionParams{} if token != "" { params.AlbedoAttachmentToken = &token } handle := &OperationHandle{id: id, sessionID: session, kind: "compaction", attachmentToken: token} handle.operation = operation{Name: "compact session", Body: protocol.CompactionRequest{Strategy: optionalText(strategy)}, Policy: noRecovery, Handle: handle, BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewPutCompactionRequestWithBody(base, session, id, params, "application/json", body) }} return handle, nil } func ReadCompaction(ctx context.Context, conn *Connection, handle *OperationHandle) (protocol.CompactionReceipt, error) { var receipt protocol.CompactionReceipt if handle == nil || handle.kind != "compaction" { return receipt, errors.New("compaction handle required") } err := executeRead(ctx, conn, operation{Name: "read compaction", Policy: readRecovery, BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { params := &protocol.GetCompactionParams{AlbedoAttachmentToken: optionalText(handle.attachmentToken)} return protocol.NewGetCompactionRequest(base, handle.sessionID, handle.id, params) }}, func(data []byte) error { return decodeCompaction(data, handle, &receipt) }) return receipt, err } func decodeCompaction(data []byte, handle *OperationHandle, receipt *protocol.CompactionReceipt) error { if err := decodeRequired(data, receipt); err != nil { return err } if receipt.ID != handle.id || receipt.SessionID != handle.sessionID { return fieldError("compaction identity") } switch receipt.State { case "running", "interrupted": if receipt.Result != nil { return fieldError("compaction result") } case "completed": if receipt.Result == nil { return fieldError("compaction result") } default: return fieldError("compaction state") } return nil } func SubmitCompaction(ctx context.Context, conn *Connection, handle *OperationHandle) (protocol.CompactionReceipt, error) { if handle == nil || handle.kind != "compaction" { return protocol.CompactionReceipt{}, errors.New("compaction handle required") } return executeReceipt(ctx, conn, handle, []int{200, 202}, func(data []byte, _ int) (protocol.CompactionReceipt, error) { var receipt protocol.CompactionReceipt err := decodeCompaction(data, handle, &receipt) return receipt, err }, func(ctx context.Context) (protocol.CompactionReceipt, bool, error) { receipt, err := ReadCompaction(ctx, conn, handle) return receipt, err == nil, err }) } func (r CompactionResult) Message() string { message := "Context " + r.State + "." if r.Observation != nil { message += fmt.Sprintf(" %d entries evicted.", r.Observation.EvictedEntries) } if r.Failure != nil { message += " " + r.Failure.Detail } return message }