fix(server): handle router setup panic and return error

* return error from New function if route registration panics
* add googleDispatch to handle model:action routing
This commit is contained in:
2026-04-11 21:03:29 +02:00
parent c5608bf5cd
commit c12e16c9f7
4 changed files with 52 additions and 9 deletions

View File

@@ -18,14 +18,22 @@ import (
)
// New builds and returns a configured bunrouter.Router.
// Returns an error if route registration panics (e.g. conflicting routes).
func New(
cfg *config.Config,
clients map[string]embedclient.Client,
adp adapter.Adapter,
reg *metrics.Registry,
logger *zap.Logger,
) *bunrouter.Router {
router := bunrouter.New(
) (router *bunrouter.Router, err error) {
defer func() {
if r := recover(); r != nil {
logger.Error("panic during router setup", zap.Any("recover", r))
err = fmt.Errorf("router setup panic: %v", r)
}
}()
router = bunrouter.New(
bunrouter.WithMiddleware(authMiddleware(cfg.Server.APIKeys)),
bunrouter.WithMiddleware(traceMiddleware()),
bunrouter.WithMiddleware(metricsMiddleware(reg, adp)),
@@ -35,8 +43,10 @@ func New(
h := &handler{cfg: cfg, clients: clients, adapter: adp, logger: logger}
router.POST("/v1/embeddings", h.openAIEmbeddings)
router.POST("/v1/models/:model:embedContent", h.googleEmbedContent)
router.POST("/v1/models/:model:batchEmbedContents", h.googleBatchEmbedContents)
// Google API uses a literal colon as a method separator (e.g. /v1/models/foo:embedContent).
// bunrouter can't distinguish two routes with the same :param prefix, so a single wildcard
// captures the full "model:action" segment and dispatches internally.
router.POST("/v1/models/*modelaction", h.googleDispatch)
// OpenAPI spec + docs
router.GET("/openapi.yaml", spec.SpecHandler())
@@ -59,7 +69,7 @@ func New(
}
}
return router
return router, nil
}
// authMiddleware rejects requests without a valid Bearer token when api_keys is configured.