// Package server implements the labd HTTP API on the generated ogen server. package server import ( "context" "encoding/hex" "errors" "fmt" "log/slog" "math" "net/http" "time" "github.com/google/uuid" ogenerrors "github.com/ogen-go/ogen/ogenerrors" "lincodex/labd/internal/api" "lincodex/labd/internal/lab" "lincodex/labd/internal/pool" "lincodex/labd/internal/template" ) // Labs is the lab manager; pool.Manager implements it. type Labs interface { Create(id uuid.UUID, request pool.CreateRequest) (lab.Lab, bool, error) Get(id uuid.UUID) (lab.Lab, error) Delete(id uuid.UUID) (lab.Lab, bool, error) ConsoleToken(id uuid.UUID, node string) (string, time.Time, error) Check(ctx context.Context, id uuid.UUID) (pool.CheckResult, error) } // Handler implements the generated api.Handler. type Handler struct { labs Labs ready func() bool retryAfter time.Duration logger *slog.Logger } var _ api.Handler = (*Handler)(nil) // NewHandler returns the API handler. func NewHandler(labs Labs, ready func() bool, retryAfter time.Duration, logger *slog.Logger) *Handler { return &Handler{labs: labs, ready: ready, retryAfter: retryAfter, logger: logger} } // GetLabdHealthz reports that the process responds. func (h *Handler) GetLabdHealthz(context.Context) (*api.LabdHealthResponse, error) { return &api.LabdHealthResponse{Status: api.LabdHealthResponseStatusOk}, nil } // GetLabdReadyz reports whether labs can be created and deleted. func (h *Handler) GetLabdReadyz(context.Context) (api.GetLabdReadyzRes, error) { if h.ready() { return &api.GetLabdReadyzOK{Status: api.LabdReadinessResponseStatusReady}, nil } return &api.GetLabdReadyzServiceUnavailable{Status: api.LabdReadinessResponseStatusNotReady}, nil } // CreateLab admits a lab or returns the lab with the same ID and payload. func (h *Handler) CreateLab(_ context.Context, req *api.LabCreateRequest, params api.CreateLabParams) (api.CreateLabRes, error) { seed, err := hex.DecodeString(req.Seed) if err != nil || len(seed) != template.SeedBytes { return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.", invalidField(api.ProblemFieldLocationBody, "/seed")) } record, created, err := h.labs.Create(params.LabID, pool.CreateRequest{ TemplateID: string(req.TemplateID), TemplateVersion: int(req.TemplateVersion), Seed: [template.SeedBytes]byte(seed), Lifetime: time.Duration(req.TTLSeconds) * time.Second, }) switch { case errors.Is(err, pool.ErrBusy): return &api.LabPoolBusyHeaders{ RetryAfter: int32(min(math.Ceil(h.retryAfter.Seconds()), math.MaxInt32)), Response: newProblem(http.StatusServiceUnavailable, api.ProblemCodeLabPoolBusy, "No capacity for another lab. Retry later with the same lab ID."), }, nil case errors.Is(err, pool.ErrUnknownTemplate): return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The template or its version is unknown.", invalidField(api.ProblemFieldLocationBody, "/template_id"), invalidField(api.ProblemFieldLocationBody, "/template_version")) case errors.Is(err, pool.ErrLifetimeTooLong): return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The lifetime exceeds the maximum.", invalidField(api.ProblemFieldLocationBody, "/ttl_seconds")) case errors.Is(err, pool.ErrPayloadMismatch): return nil, problemError(http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, "A lab with this ID exists with a different payload.") case errors.Is(err, pool.ErrIDCollision): return nil, problemError(http.StatusConflict, api.ProblemCodeStateConflict, "The lab ID collides with another lab. Use another lab ID.") case err != nil: return nil, fmt.Errorf("server.Handler.CreateLab - create: %w", err) } status := toLabStatus(record) if created { accepted := api.CreateLabAccepted(status) return &accepted, nil } existing := api.CreateLabOK(status) return &existing, nil } // GetLab returns the state of a lab. func (h *Handler) GetLab(_ context.Context, params api.GetLabParams) (*api.LabStatus, error) { record, err := h.labs.Get(params.LabID) if err != nil { return nil, h.labError("GetLab", err) } status := toLabStatus(record) return &status, nil } // DeleteLab ends a lab before its timer. func (h *Handler) DeleteLab(_ context.Context, params api.DeleteLabParams) (api.DeleteLabRes, error) { record, changed, err := h.labs.Delete(params.LabID) if err != nil { return nil, h.labError("DeleteLab", err) } status := toLabStatus(record) if changed { accepted := api.DeleteLabAccepted(status) return &accepted, nil } existing := api.DeleteLabOK(status) return &existing, nil } // CreateLabConsoleToken issues a console token for one node. func (h *Handler) CreateLabConsoleToken(_ context.Context, req *api.ConsoleTokenRequest, params api.CreateLabConsoleTokenParams) (*api.ConsoleTokenHeaders, error) { token, expiresAt, err := h.labs.ConsoleToken(params.LabID, string(req.Node)) if errors.Is(err, pool.ErrUnknownNode) { return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The lab has no such node.", invalidField(api.ProblemFieldLocationBody, "/node")) } if err != nil { return nil, h.labError("CreateLabConsoleToken", err) } return &api.ConsoleTokenHeaders{ CacheControl: api.CreateLabConsoleTokenCreatedCacheControlNoStore, Response: api.ConsoleToken{ Token: token, Node: req.Node, ExpiresAt: expiresAt, AttachPath: "/v1/labs/" + params.LabID.String() + "/console", }, }, nil } // CheckLab runs the checker of the template against a ready lab. func (h *Handler) CheckLab(ctx context.Context, params api.CheckLabParams) (*api.LabCheckResult, error) { result, err := h.labs.Check(ctx, params.LabID) if errors.Is(err, pool.ErrCheckUnavailable) { h.logger.WarnContext(ctx, "lab check unavailable", slog.String("lab_id", params.LabID.String()), slog.String("error", err.Error())) return nil, problemError(http.StatusServiceUnavailable, api.ProblemCodeLabUnavailable, "The lab could not be evaluated. Nothing was checked.") } if err != nil { return nil, h.labError("CheckLab", err) } converted := api.LabCheckResult{LabID: params.LabID, CheckedAt: result.CheckedAt, Criteria: make([]api.CriterionResult, 0, len(result.Criteria))} for _, criterion := range result.Criteria { converted.Criteria = append(converted.Criteria, api.CriterionResult{ID: api.CriterionId(criterion.ID), Passed: criterion.Passed}) if criterion.Passed { converted.Score++ } } converted.MaxScore = int32(len(result.Criteria)) //nolint:gosec // Criteria are bounded by the template package. return &converted, nil } // labError maps the errors that several operations share. func (h *Handler) labError(operation string, err error) error { switch { case errors.Is(err, pool.ErrNotFound): return problemError(http.StatusNotFound, api.ProblemCodeNotFound, "The provisioner holds no lab with this ID.") case errors.Is(err, pool.ErrNotReady): return problemError(http.StatusConflict, api.ProblemCodeStateConflict, "The lab is not ready.") default: return fmt.Errorf("server.Handler.%s: %w", operation, err) } } // NewError maps errors of handlers and of the security check to problems. func (h *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode { var securityErr *ogenerrors.SecurityError if errors.As(err, &securityErr) { return problemError(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token.") } h.logger.ErrorContext(ctx, "request failed", slog.String("error_type", fmt.Sprintf("%T", err))) return problemError(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.") } // toLabStatus converts a record. It copies only the fields of the contract: // no address, instance, bridge, or seed leaves labd. func toLabStatus(record lab.Lab) api.LabStatus { status := api.LabStatus{ LabID: record.ID, State: api.LabState(record.State), TemplateID: api.TemplateId(record.TemplateID), TemplateVersion: int32(record.TemplateVersion), //nolint:gosec // Template versions are at most 10000. CreatedAt: record.CreatedAt, ExpiresAt: record.ExpiresAt, Nodes: make([]api.LabNode, 0, len(record.Nodes)), } if !record.ReadyAt.IsZero() { status.ReadyAt = api.NewOptDateTime(record.ReadyAt) } if !record.DeletedAt.IsZero() { status.DeletedAt = api.NewOptDateTime(record.DeletedAt) } if record.FailureReason != "" { status.FailureReason = api.NewOptLabFailureReason(api.LabFailureReason(record.FailureReason)) } for _, node := range record.Nodes { status.Nodes = append(status.Nodes, api.LabNode{Name: api.NodeName(node.Name), Kind: api.NodeKind(node.Kind)}) } return status }