-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathcontroller.go
More file actions
323 lines (295 loc) · 11.1 KB
/
Copy pathcontroller.go
File metadata and controls
323 lines (295 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package gitlab
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/common/logger"
)
const responseErrorKey = "error"
// Controller handles HTTP endpoints for GitLab integration.
type Controller struct {
service *Service
logger *logger.Logger
}
// NewController creates a new GitLab controller.
func NewController(svc *Service, log *logger.Logger) *Controller {
return &Controller{service: svc, logger: log}
}
// RegisterHTTPRoutes registers the v1 HTTP surface.
func (c *Controller) RegisterHTTPRoutes(router *gin.Engine) {
api := router.Group("/api/v1/gitlab")
api.GET("/status", c.httpGetStatus)
api.POST("/token", c.httpConfigureToken)
api.DELETE("/token", c.httpClearToken)
api.POST("/host", c.httpConfigureHost)
api.GET("/mrs/feedback", c.httpGetMRFeedback)
api.POST("/mrs/discussions/notes", c.httpCreateDiscussionNote)
api.POST("/mrs/discussions/resolve", c.httpResolveDiscussion)
api.GET("/workspaces/:workspaceID/task-mrs", c.httpListWorkspaceTaskMRs)
api.GET("/tasks/:taskID/mrs", c.httpListTaskMRs)
api.POST("/tasks/:taskID/mrs/sync", c.httpSyncTaskMR)
api.GET("/user/mrs", c.httpSearchUserMRs)
api.GET("/user/issues", c.httpSearchUserIssues)
c.RegisterWatchHTTPRoutes(router)
}
// RegisterRoutes is the package-level entrypoint mirroring github.RegisterRoutes.
func RegisterRoutes(router *gin.Engine, svc *Service, log *logger.Logger) {
NewController(svc, log).RegisterHTTPRoutes(router)
}
func (c *Controller) httpGetStatus(ctx *gin.Context) {
status, err := c.service.GetStatus(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, status)
}
func (c *Controller) httpConfigureToken(ctx *gin.Context) {
var req ConfigureTokenRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "invalid payload: token is required"})
return
}
if err := c.service.ConfigureToken(ctx.Request.Context(), req.Token); err != nil {
// errors.Is against the package-level sentinel — durable across
// future rewording / wrapping of the ConfigureToken error message.
if errors.Is(err, ErrInvalidToken) {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"configured": true})
}
func (c *Controller) httpClearToken(ctx *gin.Context) {
if err := c.service.ClearToken(ctx.Request.Context()); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"cleared": true})
}
func (c *Controller) httpConfigureHost(ctx *gin.Context) {
var req ConfigureHostRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "invalid payload: host is required"})
return
}
if err := c.service.ConfigureHost(ctx.Request.Context(), req.Host); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"configured": true, "host": c.service.Host()})
}
func (c *Controller) httpGetMRFeedback(ctx *gin.Context) {
projectPath, iid, err := parseProjectAndIID(ctx)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: err.Error()})
return
}
feedback, err := c.service.GetMRFeedback(ctx.Request.Context(), projectPath, iid)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, feedback)
}
func (c *Controller) httpCreateDiscussionNote(ctx *gin.Context) {
var req struct {
Project string `json:"project" binding:"required"`
IID int `json:"iid" binding:"required"`
DiscussionID string `json:"discussion_id" binding:"required"`
Body string `json:"body" binding:"required"`
}
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "invalid payload"})
return
}
note, err := c.service.CreateMRDiscussionNote(ctx.Request.Context(), req.Project, req.IID, req.DiscussionID, req.Body)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, note)
}
func (c *Controller) httpResolveDiscussion(ctx *gin.Context) {
var req struct {
Project string `json:"project" binding:"required"`
IID int `json:"iid" binding:"required"`
DiscussionID string `json:"discussion_id" binding:"required"`
}
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "invalid payload"})
return
}
if err := c.service.ResolveMRDiscussion(ctx.Request.Context(), req.Project, req.IID, req.DiscussionID); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"resolved": true})
}
// parseProjectAndIID reads ?project=<path>&iid=<n> query params and validates
// them. project is the namespace/path slug (URL-decoded by Gin); iid must be
// a positive integer.
func parseProjectAndIID(ctx *gin.Context) (string, int, error) {
project := ctx.Query("project")
if project == "" {
return "", 0, errors.New("project query param required")
}
iidStr := ctx.Query("iid")
if iidStr == "" {
return "", 0, errors.New("iid query param required")
}
iid, err := strconv.Atoi(iidStr)
if err != nil || iid <= 0 {
return "", 0, errors.New("iid must be a positive integer")
}
return project, iid, nil
}
// SyncTaskMRRequest is the JSON body for POST /tasks/:taskID/mrs/sync.
// project_path is "namespace/path"; iid is the MR's per-project sequential id;
// repository_id is the kandev repository UUID (empty for single-repo tasks).
type SyncTaskMRRequest struct {
ProjectPath string `json:"project_path" binding:"required"`
IID int `json:"iid" binding:"required"`
RepositoryID string `json:"repository_id"`
}
func (c *Controller) httpListWorkspaceTaskMRs(ctx *gin.Context) {
wsID := ctx.Param("workspaceID")
if wsID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "workspaceID required"})
return
}
taskMRs, err := c.service.ListTaskMRsByWorkspace(ctx.Request.Context(), wsID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, TaskMRsResponse{TaskMRs: taskMRs})
}
func (c *Controller) httpListTaskMRs(ctx *gin.Context) {
taskID := ctx.Param("taskID")
if taskID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "taskID required"})
return
}
mrs, err := c.service.ListTaskMRsByTask(ctx.Request.Context(), taskID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"task_mrs": mrs})
}
func (c *Controller) httpSyncTaskMR(ctx *gin.Context) {
taskID := ctx.Param("taskID")
if taskID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "taskID required"})
return
}
var req SyncTaskMRRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "invalid payload: project_path and iid required"})
return
}
row, err := c.service.SyncTaskMR(ctx.Request.Context(), taskID, req.RepositoryID, req.ProjectPath, req.IID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, row)
}
// httpSearchUserMRs surfaces the configured user's MR queue. filter is one
// of "assigned_to_me", "created_by_me", "review_requested" (the /gitlab
// page's tab values), or a raw GitLab API filter in `key=value` form;
// custom_query passes through verbatim for power users and disables tab
// translation entirely.
func (c *Controller) httpSearchUserMRs(ctx *gin.Context) {
page, perPage := paginationFromQuery(ctx)
filter := ctx.Query("filter")
customQuery := ctx.Query("custom_query")
if customQuery == "" {
translated, err := c.translateMRFilter(ctx, filter)
if err != nil {
// translateMRFilter has already written the HTTP error.
return
}
if translated != "" {
filter = translated
}
}
result, err := c.service.Client().SearchMRsPaged(
ctx.Request.Context(), filter, customQuery, page, perPage,
)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, result)
}
// httpSearchUserIssues surfaces the configured user's issue queue. filter
// supports "assigned_to_me" and "created_by_me" (the /gitlab page's issue
// tabs). "review_requested" is explicitly rejected with 400 — GitLab has no
// reviewer-assigned concept for issues, and silently serving the global
// unscoped listing would re-introduce the bug this translator layer was
// added to prevent.
func (c *Controller) httpSearchUserIssues(ctx *gin.Context) {
page, perPage := paginationFromQuery(ctx)
filter := ctx.Query("filter")
customQuery := ctx.Query("custom_query")
if customQuery == "" {
if filter == filterTokenReviewRequested {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "review_requested is not supported for issues"})
return
}
if translated := translateUserSearchFilter(filter, ""); translated != "" {
filter = translated
}
}
result, err := c.service.Client().ListIssuesPaged(
ctx.Request.Context(), filter, customQuery, page, perPage,
)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, result)
}
// translateMRFilter resolves the authenticated user (only when the
// review_requested tab needs it) and runs the filter through
// translateUserSearchFilter. On a username-lookup failure — including a
// successful call that returns no username (NoopClient, an unexpected
// GitLab response) — it writes a 500 to ctx and returns an error so the
// caller can short-circuit. Silently falling back to an unfiltered listing
// would re-introduce the very bug this translation layer was added to
// prevent.
func (c *Controller) translateMRFilter(ctx *gin.Context, filter string) (string, error) {
var username string
if filter == filterTokenReviewRequested {
u, err := c.service.Client().GetAuthenticatedUser(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return "", err
}
if u == "" {
err := errors.New("cannot resolve authenticated GitLab user")
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return "", err
}
username = u
}
return translateUserSearchFilter(filter, username), nil
}
// paginationFromQuery reads ?page=&per_page= with the same clamps SearchMRsPaged
// applies internally — surfaced here so 400s on bad input are uniform.
func paginationFromQuery(ctx *gin.Context) (int, int) {
page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
if page < 1 {
page = 1
}
perPage, _ := strconv.Atoi(ctx.DefaultQuery("per_page", "50"))
if perPage <= 0 {
perPage = 50
}
return page, perPage
}