An open-source, faster Devin alternative
TypeScript
widen sentry capture beyond panic recovery (#181)
Mohamed Habibcf606e925ee3
diff --git a/cmd/server/main.go b/cmd/server/main.goindex 47150ba8..f2b97f97 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -319,7 +319,7 @@ func main() {// Background maintenance tasksif opts.Store != nil && redisRegistry != nil {- go func() {+ observability.Go("maintenance-loop", func() {ticker := time.NewTicker(60 * time.Second)defer ticker.Stop()for range ticker.C {@@ -329,6 +329,7 @@ func main() {recovered, err := opts.Store.RecoverStaleMigrations(ctx, 60*time.Second)if err != nil {log.Printf("maintenance: stale migration recovery error: %v", err)+ observability.CaptureError(err, "area", "maintenance", "op", "recover_stale_migrations")} else if recovered > 0 {log.Printf("maintenance: reverted %d stale migrations", recovered)}@@ -341,11 +342,12 @@ func main() {orphaned, err := opts.Store.MarkOrphanedSandboxes(ctx, liveWorkers)if err != nil {log.Printf("maintenance: orphan reconciliation error: %v", err)+ observability.CaptureError(err, "area", "maintenance", "op", "mark_orphaned_sandboxes")} else if orphaned > 0 {log.Printf("maintenance: marked %d sandboxes as error (worker lost)", orphaned)}}- }()+ })}// Initialize control plane subdomain proxy (server mode only).diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex fdab4e29..ddcd8ff2 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -234,8 +234,8 @@ func main() {// Wire checkpoint store into QEMU manager for base image archival + checkpoint rebasingif checkpointStore != nil && qemuMgr != nil {qemuMgr.SetCheckpointStore(checkpointStore)- go qemuMgr.UploadBaseImageIfNew()- go qemuMgr.MigrateStaleCheckpoints()+ observability.Go("upload-base-image", qemuMgr.UploadBaseImageIfNew)+ observability.Go("migrate-stale-checkpoints", qemuMgr.MigrateStaleCheckpoints)}// PostgreSQL store@@ -306,7 +306,9 @@ func main() {// Rolling agent upgrade: wake hibernated sandboxes with old agent, upgrade, re-hibernate.// Runs in background so worker starts serving immediately.if qemuMgr != nil && checkpointStore != nil {- go qemuMgr.RollingUpgradeHibernated(checkpointStore, 2)+ observability.Go("rolling-upgrade-hibernated", func() {+ qemuMgr.RollingUpgradeHibernated(checkpointStore, 2)+ })}// Metricsdiff --git a/internal/api/router.go b/internal/api/router.goindex 55c6b5e2..36ca3a15 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -21,6 +21,7 @@ import ("github.com/opensandbox/opensandbox/internal/cloudflare""github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage"@@ -136,7 +137,9 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o}}- // Global middleware+ // Global middleware. Sentry goes first so it can attach request context and+ // observe panics before echo's Recover middleware converts them to 500s.+ e.Use(observability.EchoMiddleware())e.Use(middleware.Recover())e.Use(middleware.Logger())e.Use(middleware.CORS())diff --git a/internal/observability/capture.go b/internal/observability/capture.gonew file mode 100644index 00000000..4d6530d9--- /dev/null+++ b/internal/observability/capture.go@@ -0,0 +1,60 @@+package observability++import (+ "fmt"+ "log"+ "runtime/debug"++ "github.com/getsentry/sentry-go"+)++// CaptureError sends err to Sentry. Safe to call when Sentry is not+// initialized (no-ops). Extra tags can be supplied as key/value pairs.+func CaptureError(err error, tags ...string) {+ if err == nil {+ return+ }+ hub := sentry.CurrentHub()+ if hub.Client() == nil {+ return+ }+ hub.WithScope(func(scope *sentry.Scope) {+ for i := 0; i+1 < len(tags); i += 2 {+ scope.SetTag(tags[i], tags[i+1])+ }+ hub.CaptureException(err)+ })+}++// Go runs fn in a new goroutine, capturing any panic to Sentry. Use this+// instead of bare `go func(){...}()` for long-lived background loops so that+// a panic in the loop is reported before the goroutine dies.+//+// The name argument is attached as a tag so the event is easy to find.+func Go(name string, fn func()) {+ go func() {+ defer func() {+ if r := recover(); r != nil {+ log.Printf("observability: goroutine %q panicked: %v\n%s", name, r, debug.Stack())+ hub := sentry.CurrentHub()+ if hub.Client() == nil {+ return+ }+ hub.WithScope(func(scope *sentry.Scope) {+ scope.SetTag("goroutine", name)+ hub.Recover(r)+ })+ }+ }()+ fn()+ }()+}++// Errorf captures a formatted error message to Sentry as a new error and+// logs it locally. Useful at error sites that currently use log.Printf but+// want to also surface the event in Sentry.+func Errorf(format string, args ...any) {+ msg := fmt.Sprintf(format, args...)+ log.Print(msg)+ CaptureError(fmt.Errorf("%s", msg))+}diff --git a/internal/observability/echo.go b/internal/observability/echo.gonew file mode 100644index 00000000..ccbad3d4--- /dev/null+++ b/internal/observability/echo.go@@ -0,0 +1,50 @@+package observability++import (+ "time"++ "github.com/getsentry/sentry-go"+ "github.com/labstack/echo/v4"+)++// EchoMiddleware returns an echo middleware that:+// - recovers panics, ships them to Sentry, then re-panics so echo's own+// Recover middleware can render the 500 response+// - captures handler errors that resolve to HTTP 5xx (or non-HTTPError values)+//+// It is safe to use when Sentry is not initialized — capture calls no-op.+func EchoMiddleware() echo.MiddlewareFunc {+ return func(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ hub := sentry.CurrentHub().Clone()+ req := c.Request()++ hub.Scope().SetRequest(req)+ hub.Scope().SetTag("http.route", c.Path())+ hub.Scope().SetTag("http.method", req.Method)++ ctx := sentry.SetHubOnContext(req.Context(), hub)+ c.SetRequest(req.WithContext(ctx))++ defer func() {+ if r := recover(); r != nil {+ hub.RecoverWithContext(ctx, r)+ hub.Flush(2 * time.Second)+ panic(r) // let echo's Recover middleware respond+ }+ }()++ err := next(c)+ if err == nil {+ return nil+ }++ // Only capture server errors. Client errors (4xx) are expected flow.+ if he, ok := err.(*echo.HTTPError); ok && he.Code < 500 {+ return err+ }+ hub.CaptureException(err)+ return err+ }+ }+}diff --git a/internal/observability/grpc.go b/internal/observability/grpc.gonew file mode 100644index 00000000..af3cba9f--- /dev/null+++ b/internal/observability/grpc.go@@ -0,0 +1,92 @@+package observability++import (+ "context"+ "time"++ "github.com/getsentry/sentry-go"+ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status"+)++// UnaryServerInterceptor returns a gRPC unary interceptor that captures+// server-side errors and panics to Sentry. Client errors (InvalidArgument,+// NotFound, AlreadyExists, PermissionDenied, Unauthenticated, FailedPrecondition,+// OutOfRange, Canceled, DeadlineExceeded) are not captured — they usually+// represent expected flow, not bugs.+func UnaryServerInterceptor() grpc.UnaryServerInterceptor {+ return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {+ hub := sentry.CurrentHub().Clone()+ hub.Scope().SetTag("grpc.method", info.FullMethod)+ ctx = sentry.SetHubOnContext(ctx, hub)++ defer func() {+ if r := recover(); r != nil {+ hub.RecoverWithContext(ctx, r)+ hub.Flush(2 * time.Second)+ panic(r)+ }+ }()++ resp, err = handler(ctx, req)+ if err != nil && shouldCaptureGRPC(err) {+ hub.CaptureException(err)+ }+ return resp, err+ }+}++// StreamServerInterceptor returns a gRPC stream interceptor mirroring+// UnaryServerInterceptor's behavior for streaming RPCs.+func StreamServerInterceptor() grpc.StreamServerInterceptor {+ return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {+ hub := sentry.CurrentHub().Clone()+ hub.Scope().SetTag("grpc.method", info.FullMethod)+ hub.Scope().SetTag("grpc.stream", "true")+ ctx := sentry.SetHubOnContext(ss.Context(), hub)++ defer func() {+ if r := recover(); r != nil {+ hub.RecoverWithContext(ctx, r)+ hub.Flush(2 * time.Second)+ panic(r)+ }+ }()++ wrapped := &wrappedStream{ServerStream: ss, ctx: ctx}+ err = handler(srv, wrapped)+ if err != nil && shouldCaptureGRPC(err) {+ hub.CaptureException(err)+ }+ return err+ }+}++// shouldCaptureGRPC returns true for error codes that represent real server+// problems, not expected client-side conditions.+func shouldCaptureGRPC(err error) bool {+ code := status.Code(err)+ switch code {+ case codes.OK,+ codes.Canceled,+ codes.InvalidArgument,+ codes.NotFound,+ codes.AlreadyExists,+ codes.PermissionDenied,+ codes.Unauthenticated,+ codes.FailedPrecondition,+ codes.OutOfRange,+ codes.DeadlineExceeded,+ codes.Aborted:+ return false+ }+ return true+}++type wrappedStream struct {+ grpc.ServerStream+ ctx context.Context+}++func (w *wrappedStream) Context() context.Context { return w.ctx }diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 54cba080..a5cf7bf3 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -21,6 +21,7 @@ import ("github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/grpctls"+ "github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/sparse""github.com/opensandbox/opensandbox/internal/storage"@@ -78,6 +79,8 @@ func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sanTime: 30 * time.Second,Timeout: 10 * time.Second,}),+ grpc.UnaryInterceptor(observability.UnaryServerInterceptor()),+ grpc.StreamInterceptor(observability.StreamServerInterceptor()),}// Enable mTLS if configureddiff --git a/internal/worker/http_server.go b/internal/worker/http_server.goindex e7e8b613..58e13bbc 100644--- a/internal/worker/http_server.go+++ b/internal/worker/http_server.go@@ -6,6 +6,7 @@ import ("github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware""github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/observability""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox")@@ -40,7 +41,9 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sansandboxDomain: sandboxDomain,}- // Global middleware+ // Global middleware. Sentry goes first so it can observe panics and+ // attach request context before echo's Recover middleware handles them.+ e.Use(observability.EchoMiddleware())e.Use(middleware.Recover())e.Use(middleware.Logger())e.Use(middleware.CORS())