/
engine.go
107 lines (83 loc) · 2.11 KB
/
engine.go
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
package dagger
import (
"context"
"net/http"
"net/http/httptest"
"sync"
"dagger.io/dagger"
engineclient "github.com/dagger/dagger/engine/client"
contextx "github.com/octohelm/x/context"
)
type Client = dagger.Client
type Platform = dagger.Platform
type Params = engineclient.Params
var ScopeContext = contextx.New[Scope](contextx.WithDefaultsFunc(func() Scope {
return Scope{}
}))
type Scope struct {
Platform Platform
ID string
}
type Engine interface {
Scope() Scope
Shutdown(ctx context.Context) error
Do(ctx context.Context, do func(ctx context.Context, client *Client) error) error
}
func NewEngine(scope Scope, params Params) Engine {
return &engineImpl{scope: scope, params: params}
}
type engineImpl struct {
scope Scope
params Params
engineClient *engineclient.Client
err error
once sync.Once
mu sync.RWMutex
}
func (e *engineImpl) Shutdown(ctx context.Context) error {
if e.engineClient != nil {
return e.engineClient.Close()
}
return nil
}
func (e *engineImpl) Scope() Scope {
return e.scope
}
func (e *engineImpl) conn(ctx context.Context) (Conn, error) {
e.mu.Lock()
defer e.mu.Unlock()
e.once.Do(func() {
e.engineClient, _, e.err = engineclient.Connect(ctx, e.params)
})
return EngineConn(e.engineClient), e.err
}
func (e *engineImpl) Do(ctx context.Context, do func(ctx context.Context, client *Client) error) error {
engineConn, err := e.conn(ctx)
if err != nil {
return err
}
c, err := dagger.Connect(ctx, dagger.WithConn(engineConn), dagger.WithSkipCompatibilityCheck())
if err != nil {
return err
}
defer c.Close()
return do(ScopeContext.Inject(ctx, e.scope), c)
}
func EngineConn(engineClient *engineclient.Client) Conn {
return func(req *http.Request) (*http.Response, error) {
req.SetBasicAuth(engineClient.SecretToken, "")
resp := httptest.NewRecorder()
engineClient.ServeHTTP(resp, req)
return resp.Result(), nil
}
}
type Conn func(*http.Request) (*http.Response, error)
func (f Conn) Do(r *http.Request) (*http.Response, error) {
return f(r)
}
func (f Conn) Host() string {
return ":mem:"
}
func (f Conn) Close() error {
return nil
}