-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclient.go
More file actions
554 lines (497 loc) · 18 KB
/
Copy pathclient.go
File metadata and controls
554 lines (497 loc) · 18 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
// Package devlake provides an HTTP client for the DevLake REST API.
package devlake
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Client wraps HTTP calls to the DevLake backend API.
type Client struct {
BaseURL string
HTTPClient *http.Client
}
// NewClient creates a Client for the given base URL.
func NewClient(baseURL string) *Client {
return &Client{
BaseURL: baseURL,
HTTPClient: &http.Client{
Timeout: 90 * time.Second,
},
}
}
// Ping checks if the DevLake backend is reachable.
func (c *Client) Ping() error {
resp, err := c.HTTPClient.Get(c.BaseURL + "/ping")
if err != nil {
return fmt.Errorf("cannot reach DevLake at %s/ping: %w", c.BaseURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("DevLake returned status %d from /ping", resp.StatusCode)
}
return nil
}
// Connection represents a DevLake plugin connection.
type Connection struct {
ID int `json:"id"`
Name string `json:"name"`
Endpoint string `json:"endpoint,omitempty"`
Proxy string `json:"proxy,omitempty"`
Token string `json:"token,omitempty"`
Organization string `json:"organization,omitempty"`
Enterprise string `json:"enterprise,omitempty"`
}
// ConnectionUpdateRequest is the payload for PATCH /plugins/{plugin}/connections/{id}.
// Fields with omitempty are only included in the request when non-empty,
// enabling sparse updates (only changed fields are sent).
type ConnectionUpdateRequest struct {
Name string `json:"name,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Proxy string `json:"proxy,omitempty"`
AuthMethod string `json:"authMethod,omitempty"`
Token string `json:"token,omitempty"`
Organization string `json:"organization,omitempty"`
Enterprise string `json:"enterprise,omitempty"`
}
// ConnectionCreateRequest is the payload for creating a plugin connection.
type ConnectionCreateRequest struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
Proxy string `json:"proxy,omitempty"`
AuthMethod string `json:"authMethod"`
Token string `json:"token,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
EnableGraphql bool `json:"enableGraphql,omitempty"`
RateLimitPerHour int `json:"rateLimitPerHour"`
Organization string `json:"organization,omitempty"`
Enterprise string `json:"enterprise,omitempty"`
TokenExpiresAt string `json:"tokenExpiresAt,omitempty"`
RefreshTokenExpiresAt string `json:"refreshTokenExpiresAt,omitempty"`
}
// ConnectionTestRequest is the payload for testing a connection before creating.
type ConnectionTestRequest struct {
Name string `json:"name"`
Endpoint string `json:"endpoint"`
AuthMethod string `json:"authMethod"`
Token string `json:"token,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
EnableGraphql bool `json:"enableGraphql,omitempty"`
RateLimitPerHour int `json:"rateLimitPerHour"`
Proxy string `json:"proxy"`
Organization string `json:"organization,omitempty"`
Enterprise string `json:"enterprise,omitempty"`
}
// ConnectionTestResult is the response from testing a connection.
type ConnectionTestResult struct {
Success bool `json:"success"`
Message string `json:"message"`
}
// ListConnections returns all connections for a plugin (e.g. "github", "gh-copilot").
func (c *Client) ListConnections(plugin string) ([]Connection, error) {
resp, err := c.HTTPClient.Get(fmt.Sprintf("%s/plugins/%s/connections", c.BaseURL, plugin))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("list connections returned %d: %s", resp.StatusCode, body)
}
var conns []Connection
if err := json.Unmarshal(body, &conns); err != nil {
return nil, err
}
return conns, nil
}
// FindConnectionByName returns the first connection matching the given name, or nil.
func (c *Client) FindConnectionByName(plugin, name string) (*Connection, error) {
conns, err := c.ListConnections(plugin)
if err != nil {
return nil, err
}
for _, conn := range conns {
if conn.Name == name {
return &conn, nil
}
}
return nil, nil
}
// TestConnection tests connection parameters before creating.
func (c *Client) TestConnection(plugin string, req *ConnectionTestRequest) (*ConnectionTestResult, error) {
return doPost[ConnectionTestResult](c, fmt.Sprintf("/plugins/%s/test", plugin), req)
}
// CreateConnection creates a new connection for the given plugin.
func (c *Client) CreateConnection(plugin string, req *ConnectionCreateRequest) (*Connection, error) {
return doPost[Connection](c, fmt.Sprintf("/plugins/%s/connections", plugin), req)
}
// DeleteConnection deletes a plugin connection by ID.
func (c *Client) DeleteConnection(plugin string, connID int) error {
url := fmt.Sprintf("%s/plugins/%s/connections/%d", c.BaseURL, plugin, connID)
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return err
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("connection not found: plugin=%s id=%d", plugin, connID)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("DELETE /plugins/%s/connections/%d returned %d: %s", plugin, connID, resp.StatusCode, body)
}
return nil
}
// TestSavedConnection tests an already-created connection by ID.
func (c *Client) TestSavedConnection(plugin string, connID int) (*ConnectionTestResult, error) {
url := fmt.Sprintf("%s/plugins/%s/connections/%d/test", c.BaseURL, plugin, connID)
reqBody := bytes.NewBufferString("{}")
resp, err := c.HTTPClient.Post(url, "application/json", reqBody)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
var result ConnectionTestResult
if err := json.Unmarshal(body, &result); err != nil {
// Non-JSON response is ok — treat as success if status 200
if resp.StatusCode == http.StatusOK {
return &ConnectionTestResult{Success: true}, nil
}
return nil, fmt.Errorf("test connection returned %d: %s", resp.StatusCode, body)
}
return &result, nil
}
// GetConnection retrieves a single connection by plugin and ID.
func (c *Client) GetConnection(plugin string, connID int) (*Connection, error) {
return doGet[Connection](c, fmt.Sprintf("/plugins/%s/connections/%d", plugin, connID))
}
// UpdateConnection patches an existing connection for the given plugin.
func (c *Client) UpdateConnection(plugin string, connID int, req *ConnectionUpdateRequest) (*Connection, error) {
return doPatch[Connection](c, fmt.Sprintf("/plugins/%s/connections/%d", plugin, connID), req)
}
// HealthStatus represents the response from /health or /ping.
type HealthStatus struct {
Status string `json:"status"`
}
// Health returns the DevLake health status.
func (c *Client) Health() (*HealthStatus, error) {
resp, err := c.HTTPClient.Get(c.BaseURL + "/ping")
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
var hs HealthStatus
_ = json.Unmarshal(body, &hs)
if resp.StatusCode == http.StatusOK {
if hs.Status == "" {
hs.Status = "ok"
}
return &hs, nil
}
return nil, fmt.Errorf("health check returned %d: %s", resp.StatusCode, body)
}
// doPost is a generic helper for POST requests that return JSON.
func doPost[T any](c *Client, path string, payload any) (*T, error) {
jsonBody, err := json.Marshal(payload)
if err != nil {
return nil, err
}
url := c.BaseURL + path
resp, err := c.HTTPClient.Post(url, "application/json", bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("POST %s returned %d: %s", path, resp.StatusCode, body)
}
var result T
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
// doGet is a generic helper for GET requests that return JSON.
func doGet[T any](c *Client, path string) (*T, error) {
resp, err := c.HTTPClient.Get(c.BaseURL + path)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GET %s returned %d: %s", path, resp.StatusCode, body)
}
var result T
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
// doPut is a generic helper for PUT requests that return JSON.
func doPut[T any](c *Client, path string, payload any) (*T, error) {
jsonBody, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPut, c.BaseURL+path, bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return nil, fmt.Errorf("PUT %s returned %d: %s", path, resp.StatusCode, body)
}
var result T
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
// doPatch is a generic helper for PATCH requests that return JSON.
func doPatch[T any](c *Client, path string, payload any) (*T, error) {
jsonBody, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPatch, c.BaseURL+path, bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("PATCH %s returned %d: %s", path, resp.StatusCode, body)
}
var result T
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
// CreateScopeConfig creates a scope config for a plugin connection.
func (c *Client) CreateScopeConfig(plugin string, connID int, cfg *ScopeConfig) (*ScopeConfig, error) {
return doPost[ScopeConfig](c, fmt.Sprintf("/plugins/%s/connections/%d/scope-configs", plugin, connID), cfg)
}
// ListScopeConfigs returns all scope configs for a plugin connection.
func (c *Client) ListScopeConfigs(plugin string, connID int) ([]ScopeConfig, error) {
result, err := doGet[[]ScopeConfig](c, fmt.Sprintf("/plugins/%s/connections/%d/scope-configs", plugin, connID))
if err != nil {
return nil, err
}
return *result, nil
}
// PutScopes batch-upserts scopes for a plugin connection.
func (c *Client) PutScopes(plugin string, connID int, req *ScopeBatchRequest) error {
_, err := doPut[json.RawMessage](c, fmt.Sprintf("/plugins/%s/connections/%d/scopes", plugin, connID), req)
return err
}
// ListScopes returns the scopes configured on a plugin connection.
func (c *Client) ListScopes(plugin string, connID int) (*ScopeListResponse, error) {
return doGet[ScopeListResponse](c, fmt.Sprintf("/plugins/%s/connections/%d/scopes?pageSize=100&page=1", plugin, connID))
}
// ListProjects returns all DevLake projects.
func (c *Client) ListProjects() ([]Project, error) {
result, err := doGet[ProjectListResponse](c, "/projects")
if err != nil {
return nil, err
}
return result.Projects, nil
}
// DeleteProject deletes a project by name.
func (c *Client) DeleteProject(name string) error {
url := fmt.Sprintf("%s/projects/%s", c.BaseURL, name)
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return err
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("project not found: %s", name)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("DELETE /projects/%s returned %d: %s", name, resp.StatusCode, body)
}
return nil
}
// DeleteScope removes a scope from a plugin connection.
func (c *Client) DeleteScope(plugin string, connID int, scopeID string) error {
url := fmt.Sprintf("%s/plugins/%s/connections/%d/scopes/%s", c.BaseURL, plugin, connID, url.PathEscape(scopeID))
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return err
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("scope not found: plugin=%s connID=%d scopeID=%s", plugin, connID, scopeID)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("DELETE /plugins/%s/connections/%d/scopes/%s returned %d: %s", plugin, connID, scopeID, resp.StatusCode, body)
}
return nil
}
// CreateProject creates a new DevLake project.
func (c *Client) CreateProject(project *Project) (*Project, error) {
return doPost[Project](c, "/projects", project)
}
// GetProject retrieves a project by name.
func (c *Client) GetProject(name string) (*Project, error) {
return doGet[Project](c, fmt.Sprintf("/projects/%s", name))
}
// PatchBlueprint updates a blueprint by ID.
func (c *Client) PatchBlueprint(id int, patch *BlueprintPatch) (*Blueprint, error) {
return doPatch[Blueprint](c, fmt.Sprintf("/blueprints/%d", id), patch)
}
// TriggerBlueprint triggers a blueprint to run and returns the pipeline.
func (c *Client) TriggerBlueprint(id int) (*Pipeline, error) {
return doPost[Pipeline](c, fmt.Sprintf("/blueprints/%d/trigger", id), struct{}{})
}
// GetPipeline retrieves a pipeline by ID.
func (c *Client) GetPipeline(id int) (*Pipeline, error) {
return doGet[Pipeline](c, fmt.Sprintf("/pipelines/%d", id))
}
// ListRemoteScopes queries the DevLake remote-scope API for a plugin connection.
// groupID and pageToken are optional (pass "" to omit).
func (c *Client) ListRemoteScopes(plugin string, connID int, groupID, pageToken string) (*RemoteScopeResponse, error) {
path := fmt.Sprintf("/plugins/%s/connections/%d/remote-scopes", plugin, connID)
q := url.Values{}
if groupID != "" {
q.Set("groupId", groupID)
}
if pageToken != "" {
q.Set("pageToken", pageToken)
}
if len(q) > 0 {
path += "?" + q.Encode()
}
return doGet[RemoteScopeResponse](c, path)
}
// SearchRemoteScopes queries the DevLake search-remote-scopes API for a plugin connection.
// page and pageSize control pagination; pass 0 to use DevLake defaults.
func (c *Client) SearchRemoteScopes(plugin string, connID int, search string, page, pageSize int) (*RemoteScopeResponse, error) {
path := fmt.Sprintf("/plugins/%s/connections/%d/search-remote-scopes", plugin, connID)
q := url.Values{}
if search != "" {
q.Set("search", search)
}
if page > 0 {
q.Set("page", fmt.Sprintf("%d", page))
}
if pageSize > 0 {
q.Set("pageSize", fmt.Sprintf("%d", pageSize))
}
if len(q) > 0 {
path += "?" + q.Encode()
}
return doGet[RemoteScopeResponse](c, path)
}
// TriggerMigration triggers the DevLake database migration endpoint.
func (c *Client) TriggerMigration() error {
resp, err := c.HTTPClient.Get(c.BaseURL + "/proceed-db-migration")
if err != nil {
return fmt.Errorf("triggering migration: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
bodyText := strings.TrimSpace(string(body))
if bodyText != "" {
return fmt.Errorf("DevLake returned status %d: %s", resp.StatusCode, bodyText)
}
return fmt.Errorf("DevLake returned status %d", resp.StatusCode)
}
return nil
}
// PipelineListResponse is the response from GET /pipelines.
type PipelineListResponse struct {
Pipelines []Pipeline `json:"pipelines"`
Count int64 `json:"count"`
}
// ListPipelines returns pipelines with optional query parameters.
// status can be empty, "TASK_CREATED", "TASK_RUNNING", "TASK_COMPLETED", "TASK_FAILED", etc.
// blueprintID filters by blueprint (0 = no filter).
// page and pageSize control pagination (0 = use defaults).
func (c *Client) ListPipelines(status string, blueprintID, page, pageSize int) (*PipelineListResponse, error) {
path := "/pipelines"
q := url.Values{}
if status != "" {
q.Set("status", status)
}
if blueprintID > 0 {
q.Set("blueprint_id", fmt.Sprintf("%d", blueprintID))
}
if page > 0 {
q.Set("page", fmt.Sprintf("%d", page))
}
if pageSize > 0 {
q.Set("pagesize", fmt.Sprintf("%d", pageSize))
}
if len(q) > 0 {
path += "?" + q.Encode()
}
return doGet[PipelineListResponse](c, path)
}