Skip to content

Commit 772feea

Browse files
committed
Merge remote-tracking branch 'giteaofficial/main'
* giteaofficial/main: Add a transaction to `pickTask` (go-gitea#33543) Fix context usage (go-gitea#33554)
2 parents 2383151 + 06f1065 commit 772feea

File tree

14 files changed

+126
-113
lines changed

14 files changed

+126
-113
lines changed

routers/api/actions/runner/runner.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func (s *Service) FetchTask(
156156
// if the task version in request is not equal to the version in db,
157157
// it means there may still be some tasks not be assgined.
158158
// try to pick a task for the runner that send the request.
159-
if t, ok, err := pickTask(ctx, runner); err != nil {
159+
if t, ok, err := actions_service.PickTask(ctx, runner); err != nil {
160160
log.Error("pick task failed: %v", err)
161161
return nil, status.Errorf(codes.Internal, "pick task: %v", err)
162162
} else if ok {

routers/api/actions/runner/utils.go

Lines changed: 0 additions & 95 deletions
This file was deleted.

routers/install/install.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func Contexter() func(next http.Handler) http.Handler {
6464
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
6565
base := context.NewBaseContext(resp, req)
6666
ctx := context.NewWebContext(base, rnd, session.GetSession(req))
67-
ctx.SetContextValue(context.WebContextKey, ctx)
67+
ctx.SetContextValue(context.WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
6868
ctx.Data.MergeFrom(middleware.CommonTemplateContextData())
6969
ctx.Data.MergeFrom(reqctx.ContextData{
7070
"Title": ctx.Locale.Tr("install.install"),

routers/private/internal.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ func Routes() *web.Router {
8888
// Fortunately, the LFS handlers are able to handle requests without a complete web context
8989
common.AddOwnerRepoGitLFSRoutes(r, func(ctx *context.PrivateContext) {
9090
webContext := &context.Context{Base: ctx.Base}
91-
ctx.SetContextValue(context.WebContextKey, webContext)
91+
ctx.SetContextValue(context.WebContextKey, webContext) // FIXME: this is not ideal but no other way at the moment
9292
})
9393
})
9494

routers/web/web.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1637,7 +1637,7 @@ func registerRoutes(m *web.Router) {
16371637
}
16381638

16391639
m.NotFound(func(w http.ResponseWriter, req *http.Request) {
1640-
ctx := context.GetWebContext(req)
1640+
ctx := context.GetWebContext(req.Context())
16411641
defer routing.RecordFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound"))()
16421642
ctx.NotFound("", nil)
16431643
})

services/actions/task.go

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package actions
5+
6+
import (
7+
"context"
8+
"fmt"
9+
10+
actions_model "code.gitea.io/gitea/models/actions"
11+
"code.gitea.io/gitea/models/db"
12+
secret_model "code.gitea.io/gitea/models/secret"
13+
14+
runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
15+
"google.golang.org/protobuf/types/known/structpb"
16+
)
17+
18+
func PickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv1.Task, bool, error) {
19+
var (
20+
task *runnerv1.Task
21+
job *actions_model.ActionRunJob
22+
)
23+
24+
if err := db.WithTx(ctx, func(ctx context.Context) error {
25+
t, ok, err := actions_model.CreateTaskForRunner(ctx, runner)
26+
if err != nil {
27+
return fmt.Errorf("CreateTaskForRunner: %w", err)
28+
}
29+
if !ok {
30+
return nil
31+
}
32+
33+
if err := t.LoadAttributes(ctx); err != nil {
34+
return fmt.Errorf("task LoadAttributes: %w", err)
35+
}
36+
job = t.Job
37+
38+
secrets, err := secret_model.GetSecretsOfTask(ctx, t)
39+
if err != nil {
40+
return fmt.Errorf("GetSecretsOfTask: %w", err)
41+
}
42+
43+
vars, err := actions_model.GetVariablesOfRun(ctx, t.Job.Run)
44+
if err != nil {
45+
return fmt.Errorf("GetVariablesOfRun: %w", err)
46+
}
47+
48+
needs, err := findTaskNeeds(ctx, job)
49+
if err != nil {
50+
return fmt.Errorf("findTaskNeeds: %w", err)
51+
}
52+
53+
taskContext, err := generateTaskContext(t)
54+
if err != nil {
55+
return fmt.Errorf("generateTaskContext: %w", err)
56+
}
57+
58+
task = &runnerv1.Task{
59+
Id: t.ID,
60+
WorkflowPayload: t.Job.WorkflowPayload,
61+
Context: taskContext,
62+
Secrets: secrets,
63+
Vars: vars,
64+
Needs: needs,
65+
}
66+
67+
return nil
68+
}); err != nil {
69+
return nil, false, err
70+
}
71+
72+
if task == nil {
73+
return nil, false, nil
74+
}
75+
76+
CreateCommitStatus(ctx, job)
77+
78+
return task, true, nil
79+
}
80+
81+
func generateTaskContext(t *actions_model.ActionTask) (*structpb.Struct, error) {
82+
giteaRuntimeToken, err := CreateAuthorizationToken(t.ID, t.Job.RunID, t.JobID)
83+
if err != nil {
84+
return nil, err
85+
}
86+
87+
gitCtx := GenerateGiteaContext(t.Job.Run, t.Job)
88+
gitCtx["token"] = t.Token
89+
gitCtx["gitea_runtime_token"] = giteaRuntimeToken
90+
91+
return structpb.NewStruct(gitCtx)
92+
}
93+
94+
func findTaskNeeds(ctx context.Context, taskJob *actions_model.ActionRunJob) (map[string]*runnerv1.TaskNeed, error) {
95+
taskNeeds, err := FindTaskNeeds(ctx, taskJob)
96+
if err != nil {
97+
return nil, err
98+
}
99+
ret := make(map[string]*runnerv1.TaskNeed, len(taskNeeds))
100+
for jobID, taskNeed := range taskNeeds {
101+
ret[jobID] = &runnerv1.TaskNeed{
102+
Outputs: taskNeed.Outputs,
103+
Result: runnerv1.Result(taskNeed.Result),
104+
}
105+
}
106+
return ret, nil
107+
}

services/auth/auth.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ func handleSignIn(resp http.ResponseWriter, req *http.Request, sess SessionStore
149149
middleware.SetLocaleCookie(resp, user.Language, 0)
150150

151151
// force to generate a new CSRF token
152-
if ctx := gitea_context.GetWebContext(req); ctx != nil {
152+
if ctx := gitea_context.GetWebContext(req.Context()); ctx != nil {
153153
ctx.Csrf.PrepareForSessionUser(ctx)
154154
}
155155
}

services/auth/sspi.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore,
8888
store.GetData()["EnableSSPI"] = true
8989
// in this case, the Verify function is called in Gitea's web context
9090
// FIXME: it doesn't look good to render the page here, why not redirect?
91-
gitea_context.GetWebContext(req).HTML(http.StatusUnauthorized, tplSignIn)
91+
gitea_context.GetWebContext(req.Context()).HTML(http.StatusUnauthorized, tplSignIn)
9292
return nil, err
9393
}
9494
if outToken != "" {

services/context/context.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,9 @@ type webContextKeyType struct{}
7979

8080
var WebContextKey = webContextKeyType{}
8181

82-
func GetWebContext(req *http.Request) *Context {
83-
ctx, _ := req.Context().Value(WebContextKey).(*Context)
84-
return ctx
82+
func GetWebContext(ctx context.Context) *Context {
83+
webCtx, _ := ctx.Value(WebContextKey).(*Context)
84+
return webCtx
8585
}
8686

8787
// ValidateContext is a special context for form validation middleware. It may be different from other contexts.
@@ -135,6 +135,7 @@ func NewWebContext(base *Base, render Render, session session.Store) *Context {
135135
}
136136
ctx.TemplateContext = NewTemplateContextForWeb(ctx)
137137
ctx.Flash = &middleware.Flash{DataStore: ctx, Values: url.Values{}}
138+
ctx.SetContextValue(WebContextKey, ctx)
138139
return ctx
139140
}
140141

@@ -165,7 +166,7 @@ func Contexter() func(next http.Handler) http.Handler {
165166
ctx.PageData = map[string]any{}
166167
ctx.Data["PageData"] = ctx.PageData
167168

168-
ctx.Base.SetContextValue(WebContextKey, ctx)
169+
ctx.Base.SetContextValue(WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
169170
ctx.Csrf = NewCSRFProtector(csrfOpts)
170171

171172
// get the last flash message from cookie

services/context/package.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func PackageContexter() func(next http.Handler) http.Handler {
156156
base := NewBaseContext(resp, req)
157157
// it is still needed when rendering 500 page in a package handler
158158
ctx := NewWebContext(base, renderer, nil)
159-
ctx.SetContextValue(WebContextKey, ctx)
159+
ctx.SetContextValue(WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
160160
next.ServeHTTP(ctx.Resp, ctx.Req)
161161
})
162162
}

services/contexttest/context_tests.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ func MockContext(t *testing.T, reqPath string, opts ...MockContextOption) (*cont
6767

6868
chiCtx := chi.NewRouteContext()
6969
ctx := context.NewWebContext(base, opt.Render, nil)
70-
ctx.SetContextValue(context.WebContextKey, ctx)
70+
ctx.SetContextValue(context.WebContextKey, ctx) // FIXME: this should be removed because NewWebContext should already set it
7171
ctx.SetContextValue(chi.RouteCtxKey, chiCtx)
7272
if opt.SessionStore != nil {
7373
ctx.SetContextValue(session.MockStoreContextKey, opt.SessionStore)

services/markup/renderhelper.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ func FormalRenderHelperFuncs() *markup.RenderHelperFuncs {
2121
return false
2222
}
2323

24-
giteaCtx, ok := ctx.(*gitea_context.Context)
25-
if !ok {
24+
giteaCtx := gitea_context.GetWebContext(ctx)
25+
if giteaCtx == nil {
2626
// when using general context, use user's visibility to check
2727
return mentionedUser.Visibility.IsPublic()
2828
}

services/markup/renderhelper_codepreview.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ func renderRepoFileCodePreview(ctx context.Context, opts markup.RenderCodePrevie
3636
return "", err
3737
}
3838

39-
webCtx, ok := ctx.Value(gitea_context.WebContextKey).(*gitea_context.Context)
40-
if !ok {
39+
webCtx := gitea_context.GetWebContext(ctx)
40+
if webCtx == nil {
4141
return "", fmt.Errorf("context is not a web context")
4242
}
4343
doer := webCtx.Doer

services/markup/renderhelper_issueicontitle.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ import (
1818
)
1919

2020
func renderRepoIssueIconTitle(ctx context.Context, opts markup.RenderIssueIconTitleOptions) (_ template.HTML, err error) {
21-
webCtx, ok := ctx.Value(gitea_context.WebContextKey).(*gitea_context.Context)
22-
if !ok {
21+
webCtx := gitea_context.GetWebContext(ctx)
22+
if webCtx == nil {
2323
return "", fmt.Errorf("context is not a web context")
2424
}
2525

0 commit comments

Comments
 (0)