-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
216 lines (193 loc) · 5.93 KB
/
main.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
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
// Command playground runs a TinyGo compiler as an API that can be used from a
// web application.
package main
// This file implements the HTTP frontend.
import (
"compress/gzip"
"context"
"crypto/sha256"
"encoding/hex"
"flag"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"cloud.google.com/go/storage"
)
const (
cacheTypeLocal = iota + 1 // Cache to a local directory
cacheTypeGCS // Google Cloud Storage
)
var (
// The channel to submit compile jobs to.
compilerChan chan compilerJob
// The cache directory where cached wasm files are stored.
cacheDir string
// The cache type: local or Google Cloud Storage.
cacheType int
bucket *storage.BucketHandle
firebaseCredentials string
)
func main() {
// Create a build cache directory.
userCacheDir, err := os.UserCacheDir()
if err != nil {
log.Fatalln("could not find temporary directory:", err)
}
cacheDir = filepath.Join(userCacheDir, "tinygo-playground")
err = os.MkdirAll(cacheDir, 0777)
if err != nil {
log.Fatalln("could not create temporary directory:", err)
}
dir := flag.String("dir", ".", "which directory to serve from")
cacheTypeFlag := flag.String("cache-type", "local", "cache type (local, gcs)")
bucketNameFlag := flag.String("bucket-name", "", "Google Cloud Storage bucket name")
flag.StringVar(&firebaseCredentials, "firebase-credentials", "", "path to JSON file with Firebase credentials")
flag.Parse()
switch *cacheTypeFlag {
case "local":
cacheType = cacheTypeLocal
case "gcs":
cacheType = cacheTypeGCS
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
log.Fatalln("could not create Google Cloud Storage client:", err)
}
bucket = client.Bucket(*bucketNameFlag)
default:
log.Fatalln("unrecognized cache type:", *cacheTypeFlag)
}
// Start the compiler goroutine in the background, that will serialize all
// compile jobs.
compilerChan = make(chan compilerJob)
go backgroundCompiler(compilerChan)
// Run the web server.
http.HandleFunc("/api/compile", handleCompile)
http.HandleFunc("/api/share", handleShare)
http.Handle("/", addHeaders(http.FileServer(http.Dir(*dir))))
log.Print("Serving " + *dir + " on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
func addHeaders(fs http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Add headers that enable greater accuracy of performance.now() in
// Firefox.
w.Header().Add("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Add("Cross-Origin-Embedder-Policy", "require-corp")
fs.ServeHTTP(w, r)
}
}
// handleCompile handles the /api/compile API endpoint. It first tries to serve
// from a cache and if that fails, compiles the submitted source code directly.
func handleCompile(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
var source []byte
if strings.HasPrefix(r.Header.Get("Content-Type"), "text/plain") {
// Read the source from the POST request.
var err error
source, err = ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
} else {
// Read the source from a form parameter.
source = []byte(r.FormValue("code"))
}
// Hash the source code, used for the build cache.
sourceHashRaw := sha256.Sum256([]byte(source))
sourceHash := hex.EncodeToString(sourceHashRaw[:])
// Check 'format' parameter.
format := r.FormValue("format")
if format == "" {
// backwards compatibility (the format should be specified)
format = "wasm"
}
switch format {
case "wasm", "wasi":
// Run code in the browser.
case "elf", "hex", "uf2":
// Build a firmware that can be flashed directly to a development board.
default:
// Unrecognized format. Disallow to be sure (might introduce security
// issues otherwise).
w.Write([]byte("unrecognized format"))
w.WriteHeader(http.StatusBadRequest)
return
}
// Check 'compiler' parameter.
compiler := r.FormValue("compiler")
if compiler == "" {
compiler = "tinygo" // legacy fallback
}
switch compiler {
case "go", "tinygo":
default:
// Unrecognized compiler.
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("unrecognized compiler"))
return
}
// Attempt to serve directly from the directory with cached files.
filename := filepath.Join(cacheDir, "build-"+compiler+"-"+r.FormValue("target")+"-"+sourceHash+"."+format)
fp, err := os.Open(filename)
if err == nil {
// File was already cached! Serve it directly.
defer fp.Close()
sendCompiledResult(w, fp, format)
return
}
// Create a new compiler job, which will be executed in a single goroutine
// (to avoid overloading the system).
job := compilerJob{
Source: source,
SourceHash: sourceHash,
Filename: filename,
Compiler: compiler,
Target: r.FormValue("target"),
Format: format,
Context: r.Context(),
ResultFile: make(chan string),
ResultErrors: make(chan []byte),
}
// Send the job for execution.
compilerChan <- job
// See how well that went, when it finishes.
select {
case filename := <-job.ResultFile:
// Succesful compilation.
fp, err := os.Open(filename)
if err != nil {
log.Println("could not open compiled file:", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer fp.Close()
sendCompiledResult(w, fp, format)
case buf := <-job.ResultErrors:
// Failed compilation.
w.Write(buf)
}
}
// sendCompiledResult streams a wasm file while gzipping it during transfer.
func sendCompiledResult(w http.ResponseWriter, fp *os.File, format string) {
switch format {
case "wasm", "wasi":
w.Header().Set("Content-Type", "application/wasm")
default:
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename=firmware."+format)
}
w.Header().Set("Content-Encoding", "gzip")
gw := gzip.NewWriter(w)
_, err := io.Copy(gw, fp)
if err != nil {
log.Println("could not read compiled file:", err)
return
}
gw.Close()
}