feat: parse runner from ctx

This commit is contained in:
Jason Song 2022-10-10 14:53:21 +08:00
parent 0993c40c4f
commit e21c07cc55
2 changed files with 40 additions and 1 deletions

View File

@ -5,11 +5,14 @@
package grpc
import (
"context"
"net/http"
"strings"
"code.gitea.io/gitea/models/bots"
"gitea.com/gitea/proto-go/ping/v1/pingv1connect"
"gitea.com/gitea/proto-go/runner/v1/runnerv1connect"
"github.com/bufbuild/connect-go"
grpcreflect "github.com/bufbuild/connect-grpcreflect-go"
"google.golang.org/grpc/health/grpc_health_v1"
@ -41,3 +44,37 @@ func V1AlphaRoute() (string, http.Handler) {
compress1KB,
)
}
var withRunner = connect.WithInterceptors(connect.UnaryInterceptorFunc(func(unaryFunc connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, request connect.AnyRequest) (connect.AnyResponse, error) {
if methodName(request) == "Register" {
return unaryFunc(ctx, request)
}
uuid := request.Header().Get("X-Runner-Token") // TODO: shouldn't be X-Runner-Token, maybe X-Runner-UUID
// TODO: get runner from db, refuse request if it doesn't exist
r := &bots.Runner{
UUID: uuid,
}
ctx = context.WithValue(ctx, runnerCtxKey{}, r)
return unaryFunc(ctx, request)
}
}))
func methodName(req connect.AnyRequest) string {
splits := strings.Split(req.Spec().Procedure, "/")
if len(splits) > 0 {
return splits[len(splits)-1]
}
return ""
}
type runnerCtxKey struct{}
func GetRunner(ctx context.Context) *bots.Runner {
if v := ctx.Value(runnerCtxKey{}); v != nil {
if r, ok := v.(*bots.Runner); ok {
return r
}
}
return nil
}

View File

@ -9,6 +9,7 @@ import (
"code.gitea.io/gitea/routers/api/bots/runner"
"code.gitea.io/gitea/routers/api/bots/scheduler/queue"
"gitea.com/gitea/proto-go/runner/v1/runnerv1connect"
)
@ -20,5 +21,6 @@ func RunnerRoute() (string, http.Handler) {
return runnerv1connect.NewRunnerServiceHandler(
runnerService,
compress1KB,
withRunner,
)
}