-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinstance.go
291 lines (230 loc) · 8.02 KB
/
instance.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
package robin
import (
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"go.trulyao.dev/robin/generator"
)
type (
Instance struct {
// Knobs for typescript code generation
codegenOptions *CodegenOptions
// Internal pointer to the current robin instance
robin *Robin
// Port to run the server on
port int
// Route to run the robin handler on
route string
}
CorsOptions struct {
// Allowed origins
Origins []string
// Allowed headers
Headers []string
// Allowed methods
Methods []string
// Exposed headers
ExposedHeaders []string
// Allow credentials
AllowCredentials bool
// Max age
MaxAge int
// Preflight headers
PreflightHeaders map[string]string
}
RestApiOptions struct {
// Enable RESTful endpoints as alternatives to the defualt RPC procedures
Enable bool
// Prefix for the RESTful endpoints (default is `/api`)
Prefix string
// Whether to attach a 404 handler to the RESTful endpoints (enabled by default)
DisableNotFoundHandler bool
}
ServeOptions struct {
// Port to run the server on
Port int
// Route to run the robin handler on
Route string
// CORS options
CorsOptions *CorsOptions
// REST options
// NOTE: Json API endpoints carry an RPC-style notation by default, if you need to customise this, use the `Alias()` method on the prodecure
RestApiOptions *RestApiOptions
}
)
func PreflightHandler(w http.ResponseWriter, opts *CorsOptions) {
if opts.PreflightHeaders != nil {
for k, v := range opts.PreflightHeaders {
w.Header().Set(k, v)
}
return
}
w.Header().Set("Access-Control-Allow-Origin", strings.Join(opts.Origins, ","))
w.Header().
Set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
}
func CorsHandler(w http.ResponseWriter, opts *CorsOptions) {
w.Header().Set("Access-Control-Allow-Origin", strings.Join(opts.Origins, ","))
w.Header().Set("Access-Control-Allow-Headers", strings.Join(opts.Headers, ","))
w.Header().Set("Access-Control-Allow-Methods", strings.Join(opts.Methods, ","))
w.Header().Set("Access-Control-Expose-Headers", strings.Join(opts.ExposedHeaders, ","))
w.Header().Set("Access-Control-Allow-Credentials", fmt.Sprintf("%t", opts.AllowCredentials))
if opts.MaxAge > 0 {
w.Header().Set("Access-Control-Max-Age", fmt.Sprintf("%d", opts.MaxAge))
}
}
// Robin returns the internal robin instance which allowes for more control over the instance if ever needed
func (i *Instance) Robin() *Robin { return i.robin }
// Serve starts the robin server on the specified port
func (i *Instance) Serve(opts ...ServeOptions) error {
corsOpts := &CorsOptions{
Origins: []string{"*"},
Headers: []string{"Content-Type", "Authorization"},
Methods: []string{"POST", "OPTIONS"},
}
var (
restApiOpts *RestApiOptions
config *ServeOptions
)
if len(opts) > 0 {
config = &opts[0]
optsPort := config.Port
if optsPort > 65535 {
return errors.New("invalid port provided")
}
if optsPort > 0 {
if optsPort < 1024 {
slog.Warn("⚠️ Running robin on a privileged port", slog.Int("port", optsPort))
}
i.port = optsPort
}
i.route = trimUrlPath(config.Route)
// WARNING: If the REST API is enabled, we cannot attach the route to `/` since we need that for the 404 endpoint
if i.route == "" && opts[0].RestApiOptions != nil && opts[0].RestApiOptions.Enable {
slog.Warn("⚠ Robin cannot be attached to the root path at `/` when RESTful endpoints are enabled, using `/_robin` instead. You can customise this by setting the `Route` option in the `ServeOptions` struct.")
i.route = "_robin"
}
if config.CorsOptions != nil {
corsOpts = config.CorsOptions
}
if config.RestApiOptions != nil {
restApiOpts = config.RestApiOptions
}
}
mux := http.NewServeMux()
mux.HandleFunc("POST /"+i.route, func(w http.ResponseWriter, r *http.Request) {
CorsHandler(w, corsOpts)
i.Handler()(w, r)
})
// Handle CORS preflight requests
mux.HandleFunc("/"+i.route, func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
PreflightHandler(w, corsOpts)
return
}
})
i.AttachRestEndpoints(mux, restApiOpts)
slog.Info(
"📡 Robin server is listening",
slog.Int("port", i.port),
slog.String("route", "/"+i.route),
)
return http.ListenAndServe(fmt.Sprintf(":%d", i.port), mux)
}
// Handler returns the robin handler to be used with a custom (mux) router
func (i *Instance) Handler() http.HandlerFunc {
return i.robin.serveHTTP
}
// SetPort sets the port to run the server on (default is 8081; to avoid conflicts with other services)
// WARNING: this only applies when calling `Serve()`, if you're using the default handler, you can set the port directly on the `http.Server` instance, you may have to update the client side to reflect the new port
func (i *Instance) SetPort(port int) {
i.port = port
}
// SetRoute sets the route to run the robin handler on (default is `/_robin`)
// WARNING: this only applies when calling `Serve()`, if you're using the default handler, you can set the route using a mux router or similar, ensure that the client side reflects the new route
func (i *Instance) SetRoute(route string) {
i.route = route
}
// Export exports the typescript schema (and bindings; if enabled) to the specified path
func (i *Instance) Export(optPath ...string) error {
if !i.codegenOptions.GenerateSchema && !i.codegenOptions.GenerateBindings {
return nil
}
// Figure out what path to use depending on user configurations
path := i.codegenOptions.Path
if len(optPath) > 0 {
path = optPath[0]
}
// Ensure the path meets all out requirements
if err := i.validatePath(path); err != nil {
return err
}
// Generate the types
g := generator.New(i.robin.procedures.List())
schemaString, err := g.GenerateSchema()
if err != nil {
return err
}
// Write the schema to a file if it's enabled
if i.codegenOptions.GenerateSchema && len(schemaString) > 0 {
if err := i.writeSchemaToFile(path, strings.TrimSpace(schemaString)); err != nil {
return err
}
}
// Generate the methods if they're enabled and write them to a file
if i.codegenOptions.GenerateBindings {
bindingsString, err := g.GenerateBindings(generator.GenerateBindingsOpts{
IncludeSchema: !i.codegenOptions.GenerateSchema,
Schema: schemaString,
UseUnionResult: i.codegenOptions.UseUnionResult,
ThrowOnError: i.codegenOptions.ThrowOnError,
})
if err != nil {
return err
}
if err := i.writeBindingsToFile(path, bindingsString); err != nil {
return err
}
}
return nil
}
func (i *Instance) writeBindingsToFile(path, bindings string) error {
filePath := fmt.Sprintf("%s/bindings.ts", path)
if err := os.WriteFile(filePath, []byte(bindings), 0o644); err != nil {
return fmt.Errorf("failed to write bindings to file: %s", err.Error())
}
slog.Info("📦 Typescript bindings exported successfully", slog.String("path", filePath))
return nil
}
func (i *Instance) writeSchemaToFile(path, schema string) error {
filePath := fmt.Sprintf("%s/schema.ts", path)
if err := os.WriteFile(filePath, []byte(schema), 0o644); err != nil {
return fmt.Errorf("failed to write schema to file: %s", err.Error())
}
slog.Info("📦 Typescript schema exported successfully", slog.String("path", filePath))
return nil
}
func (i *Instance) validatePath(path string) error {
if strings.TrimSpace(path) == "" {
return errors.New(
"no bindings export path provided, you can pass this to the `Export` method after calling `Build()` or as part of the opts during the instance creation with `robin.New(...)`",
)
}
// Check that the path provided exists and is a directory
stat, err := os.Stat(path)
if err != nil {
return fmt.Errorf("failed to stat bindings path: %v", err)
}
if !stat.IsDir() {
return errors.New("provided path is not a directory")
}
return nil
}
func trimUrlPath(path string) string {
return strings.Trim(strings.Trim(path, "/"), " ")
}