diff --git a/packages/api/internal/handlers/sandbox_timeout.go b/packages/api/internal/handlers/sandbox_timeout.go index 68408fce005..e6d99ebbe0d 100644 --- a/packages/api/internal/handlers/sandbox_timeout.go +++ b/packages/api/internal/handlers/sandbox_timeout.go @@ -1,19 +1,40 @@ package handlers import ( + "context" "fmt" "net/http" "time" "github.com/gin-gonic/gin" + "github.com/google/uuid" "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/sandbox" "github.com/e2b-dev/infra/packages/api/internal/utils" "github.com/e2b-dev/infra/packages/auth/pkg/auth" "github.com/e2b-dev/infra/packages/shared/pkg/ginutils" + "github.com/e2b-dev/infra/packages/shared/pkg/logger" "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" ) +// timeoutOrchestrator is the slice of *orchestrator.Orchestrator the timeout +// handler consumes — an interface so the 404 branch (an already-expired +// sandbox is expected, not an error) is testable without a real orchestrator. +type timeoutOrchestrator interface { + KeepAliveFor(ctx context.Context, teamID uuid.UUID, sandboxID string, duration time.Duration, allowShorter bool) (*sandbox.Sandbox, *api.APIError) +} + +// timeoutBackend returns the timeout handler's orchestrator slice, overridable +// in tests via timeoutBackendOverride. +func (a *APIStore) timeoutBackend() timeoutOrchestrator { + if a.timeoutBackendOverride != nil { + return a.timeoutBackendOverride + } + + return a.orchestrator +} + func (a *APIStore) PostSandboxesSandboxIDTimeout( c *gin.Context, sandboxID string, @@ -49,9 +70,17 @@ func (a *APIStore) PostSandboxesSandboxIDTimeout( duration = time.Duration(body.Timeout) * time.Second } - _, apiErr := a.orchestrator.KeepAliveFor(ctx, teamID, sandboxID, duration, true) + _, apiErr := a.timeoutBackend().KeepAliveFor(ctx, teamID, sandboxID, duration, true) if apiErr != nil { - telemetry.ReportError(ctx, "error when setting timeout", apiErr.Err) + // A 404 is expected: SDK cleanup calls race the sandbox's own + // expiry, so the client cannot always know it is already gone. Log + // it at INFO without a stack trace instead of ReportError (WARN + + // span error), which would bury real failures. + if apiErr.Code == http.StatusNotFound { + logger.L().Info(ctx, "sandbox not found for timeout update", logger.WithSandboxID(sandboxID)) + } else { + telemetry.ReportError(ctx, "error when setting timeout", apiErr.Err) + } a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg) return diff --git a/packages/api/internal/handlers/sandbox_timeout_notfound_test.go b/packages/api/internal/handlers/sandbox_timeout_notfound_test.go new file mode 100644 index 00000000000..1ecccb210e4 --- /dev/null +++ b/packages/api/internal/handlers/sandbox_timeout_notfound_test.go @@ -0,0 +1,115 @@ +package handlers + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/codes" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + + "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/sandbox" + "github.com/e2b-dev/infra/packages/auth/pkg/auth" +) + +// timeoutBackendStub is a timeoutOrchestrator whose KeepAliveFor always fails +// with the configured APIError. +type timeoutBackendStub struct { + err *api.APIError +} + +func (s timeoutBackendStub) KeepAliveFor(_ context.Context, _ uuid.UUID, _ string, _ time.Duration, _ bool) (*sandbox.Sandbox, *api.APIError) { + return nil, s.err +} + +// runTimeoutWithError drives PostSandboxesSandboxIDTimeout with a stubbed +// KeepAliveFor returning apiErr, recording spans so the caller can inspect +// whether the handler reported a span error. Returns the HTTP recorder and the +// single finished span. +func runTimeoutWithError(t *testing.T, apiErr *api.APIError) (*httptest.ResponseRecorder, sdktrace.ReadOnlySpan) { + t.Helper() + + recorder := tracetest.NewSpanRecorder() + provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)) + tracer := provider.Tracer("test") + + ctx, span := tracer.Start(context.Background(), "timeout") + + store := &APIStore{timeoutBackendOverride: timeoutBackendStub{err: apiErr}} + + rec := httptest.NewRecorder() + ginCtx, _ := gin.CreateTestContext(rec) + + body, err := json.Marshal(api.SandboxTimeoutRequest{Timeout: 30}) + require.NoError(t, err) + + ginCtx.Request = httptest.NewRequestWithContext(ctx, http.MethodPost, "/sandboxes/abc/timeout", bytes.NewReader(body)) + ginCtx.Request.Header.Set("Content-Type", "application/json") + auth.SetTeamInfoForTest(t, ginCtx, minimalTeamInfo()) + + store.PostSandboxesSandboxIDTimeout(ginCtx, "abc123") + + span.End() + spans := recorder.Ended() + require.Len(t, spans, 1) + + return rec, spans[0] +} + +// spanHasErrorEvent reports whether span carries an exception event, which is +// what span.RecordError (via telemetry.ReportError) adds. +func spanHasErrorEvent(span sdktrace.ReadOnlySpan) bool { + for _, e := range span.Events() { + if e.Name == "exception" { + return true + } + } + + return false +} + +// TestSandboxTimeout_NotFoundIsQuiet verifies that a 404 from KeepAliveFor is +// treated as an expected outcome: the handler returns the 404 to the client but +// does NOT call telemetry.ReportError, so no span error event is recorded. +func TestSandboxTimeout_NotFoundIsQuiet(t *testing.T) { + t.Parallel() + + rec, span := runTimeoutWithError(t, &api.APIError{ + Code: http.StatusNotFound, + ClientMsg: "sandbox not found", + Err: assert.AnError, + }) + + assert.Equal(t, http.StatusNotFound, rec.Code) + assert.False(t, spanHasErrorEvent(span), + "a 404 must not record a span error — it is an expected race, not a failure") + assert.Equal(t, codes.Unset, span.Status().Code, + "a 404 must not set the span status to Error") +} + +// TestSandboxTimeout_ServerErrorIsReported is the counterpart: a non-404 error +// still flows through telemetry.ReportError and records a span error, so real +// failures remain visible. +func TestSandboxTimeout_ServerErrorIsReported(t *testing.T) { + t.Parallel() + + rec, span := runTimeoutWithError(t, &api.APIError{ + Code: http.StatusInternalServerError, + ClientMsg: "boom", + Err: assert.AnError, + }) + + assert.Equal(t, http.StatusInternalServerError, rec.Code) + assert.True(t, spanHasErrorEvent(span), + "a 5xx must still record a span error so real failures are not hidden") +} diff --git a/packages/api/internal/handlers/store.go b/packages/api/internal/handlers/store.go index d41b7b42ff9..b9ef9bc7e67 100644 --- a/packages/api/internal/handlers/store.go +++ b/packages/api/internal/handlers/store.go @@ -210,7 +210,10 @@ type APIStore struct { // pauseBackendOverride, when non-nil, replaces the orchestrator for the // pause handler's two calls — tests use it to assert the gate's wiring // (refusal before RemoveSandbox) without a real orchestrator. - pauseBackendOverride pauseOrchestrator + pauseBackendOverride pauseOrchestrator + // timeoutBackendOverride, when non-nil, replaces the orchestrator for the + // timeout handler so the 404 branch is testable without a real orchestrator. + timeoutBackendOverride timeoutOrchestrator forkBackendOverride forkOrchestrator pauseLimiter *pauselimit.Limiter resumeBackendOverride resumeWaitOrchestrator diff --git a/packages/shared/pkg/middleware/logging.go b/packages/shared/pkg/middleware/logging.go index 5412e5e2cc7..262ced14e72 100644 --- a/packages/shared/pkg/middleware/logging.go +++ b/packages/shared/pkg/middleware/logging.go @@ -111,6 +111,11 @@ func LoggingMiddleware(logger logger.Logger, conf Config) gin.HandlerFunc { switch { case status >= http.StatusInternalServerError: level = zapcore.ErrorLevel + case status == http.StatusNotFound: + // A 404 is a normal "resource already gone / never existed" + // outcome (e.g. SDK cleanup racing sandbox expiry), not a + // client error worth a WARN in the access log. + level = zapcore.InfoLevel case status >= http.StatusBadRequest: level = zapcore.WarnLevel }