/
server.go
336 lines (266 loc) · 8.42 KB
/
server.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
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
package functions
import (
"fmt"
"io/fs"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/nhost/cli/environment"
"github.com/nhost/cli/logger"
"github.com/nhost/cli/nhost"
"github.com/nhost/cli/util"
"github.com/sirupsen/logrus"
)
//
// Functions Server
//
// The server will read environment variables on runtime
// from the attached environment, if any.
// And the environment variables in the locally saved
// .env.development file.
type Server struct {
// Server specific logger
log *logrus.Logger
// It's inherently an HTTP server under the hood.
*http.Server
// Server configuration
config *ServerConfig
// (Optional) Environment to attach to this server.
environment *environment.Environment
}
// Server configuration that the user can decide to load inside the functions server.
type ServerConfig struct {
// Base route on which the handle function should listen to.
// If not supplied, "/" is chosen by default.
Handle string
// (Optional) Environment to attach to this server.
Environment *environment.Environment
// Port on which to run the server
Port string
// Overwrite the list of any files to avoid during path/tree walking.
// If left empty, the default list of files to avoid will be used.
FilesToAvoid []string
// Directory where NodeJS functions must be built.
// This must be the location where node_modules exists.
// If left empty, the default Nhost working directory is used.
BuildDir string
// Server specific logger.
// In nil, then common Nhost logger is used.
Log *logrus.Logger
Mux *http.ServeMux
}
// Intializes and returns a new functions server.
func New(config *ServerConfig) *Server {
// Initialize the temporary directory
tempDir, _ = ioutil.TempDir("", "")
if config.Port == "" {
config.Port = fmt.Sprint(util.GetPort(3000, 3999))
}
if config.Handle == "" {
config.Handle = "/"
}
if config.BuildDir == "" {
config.BuildDir = util.WORKING_DIR
}
if config.FilesToAvoid == nil {
config.FilesToAvoid = defaultFilesToAvoid
}
if config.Log == nil {
config.Log = &logger.Log
}
if config.Mux == nil {
config.Mux = http.NewServeMux()
}
server := &Server{
environment: config.Environment,
config: config,
log: config.Log,
Server: &http.Server{Addr: ":" + config.Port, Handler: config.Mux},
}
// Remove the temporary directory on server shutdown
server.RegisterOnShutdown(func() {
util.DeleteAllPaths(tempDir)
})
// Attach the request handler
server.config.Mux.HandleFunc(config.Handle, server.FunctionHandler)
/*
functionMux.HandleFunc(functionHandler, func(w http.ResponseWriter, r *http.Request) {
// If the Nhost specific handler route exists,
// trim it to get the original service URL
r.URL.Path = strings.TrimPrefix(r.URL.Path, functionHandler)
// Serve the request
handler(w, r)
})
*/
return server
}
// Main handler function that will handle all our incoming requests.
func (s *Server) FunctionHandler(w http.ResponseWriter, r *http.Request) {
f := Function{
log: s.log,
buildDir: s.config.BuildDir,
}
getRoute := func(path string, item fs.FileInfo, err error) error {
if len(f.Path) > 0 || item.IsDir() {
return nil
}
// Initialize the base directory
base, file := filepath.Split(strings.TrimPrefix(path, nhost.API_DIR))
base = filepath.Clean(base)
for _, itemToAvoid := range s.config.FilesToAvoid {
if strings.Contains(path, itemToAvoid) {
return nil
}
}
if fileNameWithoutExtension(item.Name()) != "" {
if r.URL.Path == base {
if fileNameWithoutExtension(file) == "index" {
f.Path = path
f.Route = r.URL.Path
f.Base = base
f.File = item
}
} else {
if filepath.Join(base, fileNameWithoutExtension(file)) == r.URL.Path {
f.Path = path
f.Route = r.URL.Path
f.Base = base
f.File = item
}
}
}
return nil
}
if err := filepath.Walk(nhost.API_DIR, getRoute); err != nil {
s.log.WithField("component", "server").Debug(err)
s.log.WithField("component", "server").Error("No function found on this route")
}
// If no function file has been found,
// then return 404 error
if len(f.Path) == 0 {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
// Validate whether the function has been built before
preBuilt := false
// Uncomment the following to enable caching
/*
for index, item := range functions {
// check whether it's the same function file
if item.Path == f.Path {
// now compare modification time of function file
// with it's cached copy
if f.File.ModTime().Equal(item.File.ModTime()) {
s.log.WithField("route", f.Route).Debug("Found cached copy of function")
f = item
preBuilt = true
} else {
// if file has been modified, clean the cache location
s.log.Debug("Removing temporary directory from: ", filepath.Dir(item.Build))
if err := os.RemoveAll(filepath.Dir(item.Build)); err != nil {
if _, ok := err.(*os.PathError); ok {
s.log.Debug("failed to remove temp directory: ", err)
}
}
// delete the saved function from array
functions = remove(functions, index)
}
break
}
}
*/
if !preBuilt {
// cache the function file to temporary directory
if err := os.MkdirAll(filepath.Join(tempDir, f.Base), os.ModePerm); err != nil {
s.log.WithField("route", f.Route).Debug(err)
s.log.WithField("route", f.Route).Error("Failed to prepare location to cache function file")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if err := f.Prepare(); err != nil {
s.log.WithField("route", f.Route).Debug(err)
s.log.WithField("route", f.Route).Error("Failed to build the function")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// save the function before serving it
functions = append(functions, f)
}
//
// Handle Environment Variables
//
// If environment variables haven't been loaded
// then load them from .env.development
if len(envVars) == 0 {
envVars, _ = nhost.Env()
}
// If the environment is active,
// assign runtime environment variables
if s.environment.State == environment.Active {
// Load environment specific runtime variables
runtimeVars := util.RuntimeVars(s.environment.Port, false)
for key, value := range runtimeVars {
os.Setenv(key, fmt.Sprint(value))
}
asArray := util.MapToStringArray(runtimeVars)
envVars = append(envVars, asArray...)
}
switch filepath.Ext(f.Path) {
case ".js", ".ts":
// start the NodeJS server
nodeCLI, err := exec.LookPath("node")
if err != nil {
s.log.WithField("runtime", "NodeJS").Debug(err)
s.log.WithField("runtime", "NodeJS").Error("Runtime not installed")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// initialize random port to serve the file
jsPort := util.GetPort(9401, 9500)
// prepare the node server configuration
if err := f.BuildNodeServer(jsPort); err != nil {
s.log.WithField("runtime", "NodeJS").Debug(err)
s.log.WithField("runtime", "NodeJS").Error("Failed to start the runtime server")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// prepare the execution command
cmd := exec.Cmd{
Path: nodeCLI,
Env: envVars,
Args: []string{nodeCLI, f.ServerConfig},
Stdout: os.Stdout,
Stderr: os.Stderr,
}
// begin the comand execution
if err := cmd.Start(); err != nil {
s.log.WithField("runtime", "NodeJS").Debug(err)
s.log.WithField("runtime", "NodeJS").Error("Failed to start the runtime server")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// update request URL
q := r.URL.Query()
// url, _ := url.Parse(fmt.Sprintf("%s://localhost:%v%s", r.URL.Scheme, jsPort, r.URL.Path))
url, _ := url.Parse(fmt.Sprintf("http://localhost:%v%s", jsPort, r.URL.Path))
r.URL = url
r.URL.RawQuery = q.Encode()
// serve
f.Handler(w, r)
// kill the command execution once the req is served
if err := cmd.Process.Kill(); err != nil {
status.Errorln("failed to kill process: " + err.Error())
}
// delete the node server configuration
if err := os.Remove(f.ServerConfig); err != nil {
s.log.WithField("runtime", "NodeJS").Debug(err)
}
case ".go":
// serve
f.Handler(w, r)
}
}