-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathrust.go
More file actions
236 lines (202 loc) · 5.18 KB
/
rust.go
File metadata and controls
236 lines (202 loc) · 5.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
package rust
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/BurntSushi/toml"
"github.com/sst/sst/v3/internal/fs"
"github.com/sst/sst/v3/pkg/process"
"github.com/sst/sst/v3/pkg/runtime"
)
type Runtime struct {
mut sync.Mutex
directories map[string]string
}
type Worker struct {
stdout io.ReadCloser
stderr io.ReadCloser
cmd *exec.Cmd
}
func (w *Worker) Stop() {
process.Kill(w.cmd.Process)
}
func (w *Worker) Logs() io.ReadCloser {
reader, writer := io.Pipe()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
_, _ = io.Copy(writer, w.stdout)
}()
go func() {
defer wg.Done()
_, _ = io.Copy(writer, w.stderr)
}()
go func() {
wg.Wait()
defer writer.Close()
}()
return reader
}
func New() *Runtime {
return &Runtime{
directories: map[string]string{},
}
}
func (r *Runtime) Match(runtime string) bool {
return runtime == "rust"
}
type Properties struct {
Architecture string `json:"architecture"`
}
type CargoToml struct {
Package struct {
Name string `toml:"name"`
} `toml:"package"`
}
func (r *Runtime) Build(ctx context.Context, input *runtime.BuildInput) (*runtime.BuildOutput, error) {
r.mut.Lock()
defer r.mut.Unlock()
var properties Properties
json.Unmarshal(input.Properties, &properties)
if err := r.ValidateHandler(input); err != nil {
return nil, err
}
// split handler into path and function name
parts := strings.Split(input.Handler, ".")
handler := strings.Join(parts[:len(parts)-1], ".")
// Locate cargo.toml/Cargo.toml
cargotomlpath, err := fs.FindUp(handler, "cargo.toml")
if err != nil {
cargotomlpath, err = fs.FindUp(handler, "Cargo.toml")
if err != nil {
return nil, err
}
}
// root of project
root := filepath.Dir(cargotomlpath)
// append args to the command
args := []string{}
env := os.Environ()
if input.Dev {
args = append(args, "build")
} else {
args = []string{"lambda", "build"}
args = append(args, "--release")
if properties.Architecture == "arm64" {
args = append(args, "--arm64")
}
}
cmd := process.Command("cargo", args...)
cmd.Dir = root
cmd.Env = env
slog.Info("running cargo build", "cmd", cmd.Args)
output, err := cmd.CombinedOutput()
if err != nil {
return &runtime.BuildOutput{
Errors: []string{string(output)},
}, nil
}
// get the default output of the crate
var cargotoml CargoToml
_, err = toml.DecodeFile(cargotomlpath, &cargotoml)
if err != nil {
return nil, err
}
// if binary name is not specified, use the package name
name := cargotoml.Package.Name
if len(parts) >= 2 {
name = parts[len(parts)-1]
}
binary := filepath.Join(root, "target",
map[bool]string{
true: filepath.Join("debug", name),
false: filepath.Join("lambda", name, "bootstrap"),
}[input.Dev],
)
out := filepath.Join(input.Out(), "bootstrap")
r.directories[input.FunctionID], _ = filepath.Abs(root)
if err := os.MkdirAll(filepath.Dir(out), 0755); err != nil {
return nil, fmt.Errorf("failed to create output directory: %w", err)
}
source, err := os.Open(binary)
if err != nil {
return nil, fmt.Errorf("failed to open source binary: %w", err)
}
defer source.Close()
destination, err := os.Create(out)
if err != nil {
return nil, fmt.Errorf("failed to create destination file: %w", err)
}
defer destination.Close()
if _, err := io.Copy(destination, source); err != nil {
return nil, fmt.Errorf("failed to copy binary: %w", err)
}
if err := os.Chmod(out, 0755); err != nil {
return nil, fmt.Errorf("failed to make binary executable: %w", err)
}
return &runtime.BuildOutput{
Handler: "bootstrap",
Sourcemaps: []string{},
Errors: []string{},
Out: root,
}, nil
}
func (r *Runtime) Run(ctx context.Context, input *runtime.RunInput) (runtime.Worker, error) {
cmd := process.Command(
filepath.Join(input.Build.Out, input.Build.Handler),
)
slog.Info("running server binary", "server", input.Server)
cmd.Env = input.Env
cmd.Env = append(cmd.Env, "AWS_LAMBDA_RUNTIME_API=http://"+input.Server)
cmd.Env = append(cmd.Env, "AWS_LAMBDA_FUNCTION_MEMORY_SIZE=1024")
cmd.Dir = input.Build.Out
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
cmd.Start()
return &Worker{
stdout,
stderr,
cmd,
}, nil
}
func (r *Runtime) ValidateHandler(input *runtime.BuildInput) error {
parts := strings.Split(input.Handler, ".")
handler := strings.Join(parts[:len(parts)-1], ".")
if handler != "" {
if info, err := os.Stat(handler); err != nil || !info.IsDir() {
return fmt.Errorf("handler not found: %v", input.Handler)
}
}
_, err := fs.FindUp(handler, "cargo.toml")
if err != nil {
_, err = fs.FindUp(handler, "Cargo.toml")
if err != nil {
return fmt.Errorf("handler not found: could not find Cargo.toml for handler %v", input.Handler)
}
}
return nil
}
func (r *Runtime) ShouldRebuild(functionID string, file string) bool {
// copied from go
if !strings.HasSuffix(file, ".rs") {
return false
}
match, ok := r.directories[functionID]
if !ok {
return false
}
slog.Info("checking if file needs to be rebuilt", "file", file, "match", match)
rel, err := filepath.Rel(match, file)
if err != nil {
return false
}
return !strings.HasPrefix(rel, "..")
}