Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
234 lines (197 loc) · 6.51 KB
/
Copy pathclient.go
File metadata and controls
234 lines (197 loc) · 6.51 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
package e2b
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// ClientConfig configures a new Client.
type ClientConfig struct {
// APIKey is the E2B API key. If empty, the E2B_API_KEY environment variable is used.
APIKey string
// APIBaseURL overrides the default API base URL.
APIBaseURL string
// SandboxDomain overrides the default sandbox domain.
SandboxDomain string
// HTTPClient is the HTTP client used for API requests.
// If nil, http.DefaultClient is used.
HTTPClient *http.Client
}
// Client is the E2B API client. Create one with NewClient and reuse it
// for all operations — it holds shared configuration like the API key.
type Client struct {
apiKey string
apiBaseURL string
sandboxDomain string
httpClient *http.Client
}
// NewClient creates a new E2B client. If no config is provided,
// the API key is read from the E2B_API_KEY environment variable.
func NewClient(cfgs ...ClientConfig) (*Client, error) {
var cfg ClientConfig
if len(cfgs) > 0 {
cfg = cfgs[0]
}
apiKey := resolveAPIKey(cfg.APIKey)
if apiKey == "" {
return nil, &Error{Message: "API key is required: set ClientConfig.APIKey or the E2B_API_KEY environment variable"}
}
httpClient := cfg.HTTPClient
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
apiKey: apiKey,
apiBaseURL: resolveAPIBaseURL(cfg.APIBaseURL),
sandboxDomain: resolveSandboxDomain(cfg.SandboxDomain),
httpClient: httpClient,
}, nil
}
// NewSandbox creates a new E2B sandbox microVM.
// The caller should call Close when the sandbox is no longer needed.
func (c *Client) NewSandbox(ctx context.Context, cfgs ...SandboxConfig) (*Sandbox, error) {
var cfg SandboxConfig
if len(cfgs) > 0 {
cfg = cfgs[0]
}
template := cfg.Template
if template == "" {
template = DefaultTemplate
}
timeout := cfg.Timeout
if timeout == 0 {
timeout = DefaultTimeout
}
body, err := json.Marshal(createRequest{
TemplateID: template,
Timeout: timeout,
EnvVars: cfg.EnvVars,
Secure: cfg.Secure,
AllowInternetAccess: cfg.AllowInternetAccess,
Network: cfg.Network,
})
if err != nil {
return nil, fmt.Errorf("e2b: marshal create request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.apiBaseURL+"/sandboxes", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("e2b: build create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send create request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode == http.StatusNotFound {
return nil, &Error{StatusCode: resp.StatusCode, Message: fmt.Sprintf("template not found: %s", template)}
}
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var cr createResponse
if err := json.NewDecoder(resp.Body).Decode(&cr); err != nil {
return nil, fmt.Errorf("e2b: decode create response: %w", err)
}
sbx := &Sandbox{
ID: cr.SandboxID,
TrafficAccessToken: cr.TrafficAccessToken,
accessToken: cr.EnvdAccessToken,
client: c,
}
sbx.Commands = newCommandService(sbx)
sbx.Filesystem = newFilesystemService(sbx)
return sbx, nil
}
// ListSandboxes returns all running sandboxes for this client's API key.
func (c *Client) ListSandboxes(ctx context.Context) ([]SandboxInfo, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiBaseURL+"/sandboxes", nil)
if err != nil {
return nil, fmt.Errorf("e2b: build list request: %w", err)
}
req.Header.Set("X-API-Key", c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send list request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var items []SandboxInfo
if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
return nil, fmt.Errorf("e2b: decode list response: %w", err)
}
return items, nil
}
type listSnapshotsParams struct {
sandboxID string
limit int
nextToken string
}
// ListSnapshotsOption configures a ListSnapshots request.
type ListSnapshotsOption func(*listSnapshotsParams)
// WithSnapshotSandboxID filters snapshots by the source sandbox ID.
func WithSnapshotSandboxID(id string) ListSnapshotsOption {
return func(p *listSnapshotsParams) { p.sandboxID = id }
}
// WithSnapshotLimit sets the maximum number of snapshots to return (default 100).
func WithSnapshotLimit(n int) ListSnapshotsOption {
return func(p *listSnapshotsParams) { p.limit = n }
}
// WithSnapshotNextToken sets the pagination token from a previous ListSnapshotsResult.
func WithSnapshotNextToken(token string) ListSnapshotsOption {
return func(p *listSnapshotsParams) { p.nextToken = token }
}
// ListSnapshotsResult holds the result of a ListSnapshots call, including pagination.
type ListSnapshotsResult struct {
Snapshots []SnapshotInfo
NextToken string
}
// ListSnapshots returns snapshots for this client's API key.
func (c *Client) ListSnapshots(ctx context.Context, opts ...ListSnapshotsOption) (*ListSnapshotsResult, error) {
var p listSnapshotsParams
for _, o := range opts {
o(&p)
}
u := c.apiBaseURL + "/snapshots"
sep := '?'
if p.sandboxID != "" {
u += string(sep) + "sandboxID=" + p.sandboxID
sep = '&'
}
if p.limit > 0 {
u += string(sep) + "limit=" + fmt.Sprintf("%d", p.limit)
sep = '&'
}
if p.nextToken != "" {
u += string(sep) + "nextToken=" + p.nextToken
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, fmt.Errorf("e2b: build list snapshots request: %w", err)
}
req.Header.Set("X-API-Key", c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send list snapshots request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var snapshots []SnapshotInfo
if err := json.NewDecoder(resp.Body).Decode(&snapshots); err != nil {
return nil, fmt.Errorf("e2b: decode list snapshots response: %w", err)
}
return &ListSnapshotsResult{
Snapshots: snapshots,
NextToken: resp.Header.Get("X-Next-Token"),
}, nil
}