Repository navigation
Expand file tree
/
Copy pathinstance.go
More file actions
485 lines (433 loc) · 15 KB
/
Copy pathinstance.go
File metadata and controls
485 lines (433 loc) · 15 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package xtemplate
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"io/fs"
"log/slog"
"maps"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/felixge/httpsnoop"
"github.com/go-sprout/sprout/sprigin"
"github.com/spf13/afero"
"github.com/google/uuid"
"github.com/tdewolff/minify/v2"
"github.com/tdewolff/minify/v2/css"
"github.com/tdewolff/minify/v2/html"
"github.com/tdewolff/minify/v2/js"
"github.com/tdewolff/minify/v2/svg"
)
// Instance is a configured, immutable, xtemplate request handler ready to
// execute templates and serve static files in response to http requests.
//
// The only way to create a valid Instance is to call the [Config.Instance]
// method. Configuration of an Instance is intended to be immutable. Instead of
// mutating a running Instance, build a new Instance from a modified Config and
// swap them.
//
// See also [Server] which manages instances and enables reloading them.
type Instance struct {
id int64
handler http.Handler
config Config
files map[string]*fileInfo
templates *template.Template
funcs template.FuncMap
bufferDot dot
flusherDot dot
stats InstanceStats
routes []InstanceRoute
closeOnce func() error
// inflight counts requests that have entered ServeHTTP and not yet returned.
// Enter is add-then-check-cancel (no mutex); see waitInFlight.
inflight atomic.Int64
}
// Instance creates a new *Instance from the given config.
// Requires a resolved template FS ([WithTemplateFS] / [WithTemplateDir]).
// Controller and ControllerRaw must be nil. Owned slices are cloned.
func (config Config) Instance() (_ *Instance, err error) {
config.SetDefaults()
config.cloneSlices()
if config.Controller != nil || len(config.ControllerRaw) != 0 {
return nil, errors.Join(
fmt.Errorf("xtemplate: Instance does not accept Controller/ControllerRaw; use Server, or clear them and set WithTemplateFS/WithTemplateDir"),
onCloseFunc(&config.onClose)(),
)
}
if config.TemplateFS == nil {
return nil, errors.Join(
fmt.Errorf("xtemplate: Instance requires a template FS (WithTemplateFS or WithTemplateDir); use Server for controllers"),
onCloseFunc(&config.onClose)(),
)
}
return config.buildInstance()
}
// invokeOnClose runs onClose callbacks in reverse order (same as Instance.Close).
func onCloseFunc(fns *[]func() error) func() error {
return func() (err error) {
for _, fn := range slices.Backward(*fns) {
err = errors.Join(err, fn())
}
return
}
}
// buildInstance builds an Instance from an already-resolved config.
// Callers must ensure TemplateFS is set and Controller / ControllerRaw are nil.
func (config *Config) buildInstance() (_ *Instance, err error) {
start := time.Now()
inst := &Instance{
config: *config,
id: nextInstanceIdentity.Add(1),
}
// Clone onClose so provider Closer appends during this build stay on this instance.
inst.config.onClose = slices.Clone(inst.config.onClose)
inst.closeOnce = sync.OnceValue(onCloseFunc(&inst.config.onClose))
defer func() {
if err != nil {
err = errors.Join(err, inst.closeOnce())
}
}()
if inst.config.Controller != nil || len(inst.config.ControllerRaw) != 0 {
return nil, fmt.Errorf("xtemplate: Controller cannot be set when building an instance (WithController is rejected on Reload)")
}
if inst.config.TemplateFS == nil {
return nil, fmt.Errorf("xtemplate: internal: buildInstance called without TemplateFS")
}
inst.config.Logger = inst.config.Logger.With(slog.Int64("instance", inst.id))
inst.config.Logger.Info("initializing")
inst.files = make(map[string]*fileInfo)
if len(inst.config.Precompress) > 0 {
for _, encoding := range inst.config.Precompress {
if _, ok := encodingExts[encoding]; !ok {
return nil, fmt.Errorf("unsupported encoding: %s", encoding)
}
}
tempdir, err := os.MkdirTemp("", "xtemplate-precompress-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir for pre-compressed files: %w", err)
}
// Remove after drain/Close to avoid race with in-flight static serves
inst.config.onClose = append(inst.config.onClose, func() error {
return os.RemoveAll(tempdir)
})
overlay := afero.NewBasePathFs(afero.NewOsFs(), tempdir)
inst.config.TemplateFS = afero.NewCopyOnWriteFs(inst.config.TemplateFS, overlay)
}
{
inst.funcs = template.FuncMap{}
maps.Copy(inst.funcs, xtemplateFuncs)
// Sprout, via the sprigin compatibility layer: Sprig names and call
// order (upper, atoi, list, dict, toJson, fromJson, unset, slice, …)
// keep working, and Sprout's canonical names are registered too.
// Deprecation warnings for legacy names and argument order go to the
// instance logger.
maps.Copy(inst.funcs, sprigin.HtmlFuncMapWith(sprigin.WithLogger(inst.config.Logger)))
for _, extra := range inst.config.FuncMaps {
maps.Copy(inst.funcs, extra)
}
}
// Funcs must be installed before any parse trees are added to the set.
inst.templates = template.New(".").Delims(inst.config.LDelim, inst.config.RDelim).Funcs(inst.funcs)
build := &builder{
Instance: inst,
router: http.NewServeMux(),
}
if build.config.Minify != nil && *build.config.Minify {
m := minify.New()
m.Add("text/css", &css.Minifier{})
m.Add("image/svg+xml", &svg.Minifier{})
m.Add("text/html", &html.Minifier{
TemplateDelims: [...]string{build.config.LDelim, build.config.RDelim},
})
m.AddRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), &js.Minifier{})
build.m = m
}
if err := afero.Walk(build.config.TemplateFS, ".", func(path_ string, d fs.FileInfo, err error) error {
path_ = strings.ReplaceAll(path_, "\\", "/")
if err != nil {
return err
}
// Don't walk hidden dirs (e.g. .git) which often hold sensitive or junk files.
if d.IsDir() {
if name := d.Name(); name != "." && strings.HasPrefix(name, ".") {
return filepath.SkipDir
}
return nil
}
if strings.HasSuffix(path_, build.config.TemplateExtension) {
err = build.addTemplateHandler(path_)
} else {
// Do not serve hidden basenames as static routes (e.g. .env,
// config/.htpasswd). Aligns with path templates, which parse hidden
// files into the namespace but register no file-based GET route.
if base := filepath.Base(path_); len(base) > 0 && base[0] == '.' {
return nil
}
err = build.addStaticFileHandler(path_)
}
return err
}); err != nil {
return nil, fmt.Errorf("error scanning files: %w", err)
}
for _, route := range build.config.Handlers {
pattern, handler := route.Pattern, route.Handler
if err := catch(fmt.Sprintf("add custom handler to servemux '%s'", pattern), func() { build.router.Handle(pattern, handler) }); err != nil {
return nil, err
}
build.routes = append(build.routes, InstanceRoute{pattern, handler})
build.stats.Routes += 1
}
dcInstance := dotXProvider{build.Instance}
dcReq := dotReqProvider{}
dcVars := dotVarsProvider{}
dcResp := dotRespProvider{}
dcFlush := &dotFlushProvider{}
var dot []Provider
{
var err error
if dot, err = resolveProviders(build.config.ProvidersRaw); err != nil {
return nil, err
}
goDot, err := materializeFactories(build.config.Providers)
if err != nil {
return nil, err
}
dot = append(dot, goDot...)
seen := map[string]bool{}
for _, d := range dot {
name := d.FieldName()
if err := validateProviderFieldName(name); err != nil {
return nil, fmt.Errorf("dot provider %T: %w", d, err)
}
if seen[name] {
return nil, fmt.Errorf("dot field name '%s' is used more than once", name)
}
seen[name] = true
}
// Process all providers for initialization and closing
for _, d := range slices.Concat([]Provider{dcInstance, dcReq, dcVars, dcResp, dcFlush}, dot) {
if di, ok := d.(Initializer); ok {
start := time.Now()
err := di.Init(build.config.Ctx)
build.config.Logger.Debug("initialized provider", "name", d.FieldName(), "type", reflect.TypeOf(d).String(), "duration", time.Since(start))
if err != nil {
return nil, fmt.Errorf("failed to initialize dot field '%s': %w", d.FieldName(), err)
}
}
// Any provider that implements Closer is added to the close list after initialization
if dc, ok := d.(Closer); ok {
inst.config.onClose = append(inst.config.onClose, func() error {
err := dc.Close()
if err != nil {
err = fmt.Errorf("failed to close provider. type=%T, field=%s: %w", d, d.FieldName(), err)
}
return err
})
}
}
}
inst.config.onClose = append(inst.config.onClose, func() error {
if n := inst.inflight.Load(); n > 0 {
inst.config.Logger.Warn("closing instance with unresolved requests",
slog.Int64("instance", inst.id),
slog.Int64("inflight", n),
)
}
return nil
})
// Builtin order: {X, Req, Vars} + configured providers + {Resp | Flush}.
if build.bufferDot, err = makeDot(slices.Concat([]Provider{dcInstance, dcReq, dcVars}, dot, []Provider{dcResp})); err != nil {
return nil, fmt.Errorf("failed to build buffer dot: %w", err)
}
if build.flusherDot, err = makeDot(slices.Concat([]Provider{dcInstance, dcReq, dcVars}, dot, []Provider{dcFlush})); err != nil {
return nil, fmt.Errorf("failed to build flusher dot: %w", err)
}
{
// Invoke all initialization templates, aka any template whose name starts
// with "INIT ".
makeDot := func() (*reflect.Value, error) {
w, r := httptest.NewRecorder(), httptest.NewRequest("", "/", nil)
return build.bufferDot.value(w, r)
}
cleanup := build.bufferDot.cleanup
buf := new(bytes.Buffer)
for _, tmpl := range build.templates.Templates() {
buf.Reset()
if strings.HasPrefix(tmpl.Name(), "INIT ") {
val, err := makeDot()
if err != nil {
return nil, fmt.Errorf("failed to initialize dot value: %w", err)
}
err = tmpl.Execute(buf, *val)
if err = cleanup(val, err); err != nil {
return nil, fmt.Errorf("initialization template '%s' failed: %w", tmpl.Name(), err)
}
// TODO: output buffer somewhere?
build.config.Logger.Debug("executed initialization template", slog.String("template_name", tmpl.Name()), slog.Int("rendered_len", buf.Len()))
build.stats.InitializationTemplates += 1
}
}
}
build.config.Logger.Info("instance loaded",
slog.Duration("load_time", time.Since(start)),
slog.Group("stats",
slog.Int("routes", build.stats.Routes),
slog.Int("templateFiles", build.stats.TemplateFiles),
slog.Int("templateDefinitions", build.stats.TemplateDefinitions),
slog.Int("initializationTemplates", build.stats.InitializationTemplates),
slog.Int("staticFiles", build.stats.StaticFiles),
slog.Int("staticFilesAlternateEncodings", build.stats.StaticFilesAlternateEncodings),
))
if config.CrossOrigin.Disabled {
build.handler = build.router
} else {
handler := http.NewCrossOriginProtection()
for _, origin := range config.CrossOrigin.TrustedOrigins {
_ = handler.AddTrustedOrigin(origin)
}
for _, pattern := range config.CrossOrigin.InsecureBypassPatterns {
handler.AddInsecureBypassPattern(pattern)
}
build.handler = handler.Handler(build.router)
}
return build.Instance, nil
}
// Counter to assign a unique id to each instance of xtemplate created when
// calling Config.Instance(). This is intended to help distinguish logs from
// multiple instances in a single process.
var nextInstanceIdentity atomic.Int64
// Id returns the id of this instance which is unique in the current
// process. This differentiates multiple instances, as the instance id
// is attached to all logs generated by the instance with the attribute name
// `xtemplate.instance`.
func (x *Instance) Id() int64 {
return x.id
}
// Close releases instance-scoped provider resources ([Closer]), then runs
// [WithOnClose] callbacks. Invocations after the first return a memoized result
// and do not call [Closer.Close] or [WithOnClose] callbacks again.
//
// If requests are still in flight (grace period expired or Stop skipped drain),
// Close logs this as a warning.
func (x *Instance) Close() error {
if x == nil {
return nil
}
return x.closeOnce()
}
// Routes returns a copy of all the routes registered with this instance.
func (x *Instance) Routes() []InstanceRoute {
return slices.Clone(x.routes)
}
// Stats returns the instance build stats.
func (x *Instance) Stats() InstanceStats {
return x.stats
}
var levelDebug2 slog.Level = slog.LevelDebug + 2
func (instance *Instance) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Add before cancel check ensures waitInFlight cannot observe inflight=0.
instance.inflight.Add(1)
if instance.config.Ctx.Err() != nil {
instance.inflight.Add(-1)
instance.config.Logger.Error("received request after xtemplate instance cancelled", slog.String("method", r.Method), slog.String("path", r.URL.Path))
http.Error(w, "server stopped", http.StatusInternalServerError)
return
}
defer instance.inflight.Add(-1)
ctx := r.Context()
rid := GetRequestId(ctx)
if rid == "" {
id, err := uuid.NewV7()
if err != nil {
instance.config.Logger.Error("failed to generate request id", slog.String("method", r.Method), slog.String("path", r.URL.Path), slog.Any("error", err))
http.Error(w, "failed to generate request id", http.StatusInternalServerError)
return
}
rid = id.String()
ctx = context.WithValue(ctx, requestIdKey, rid)
}
log := instance.config.Logger.With(slog.Group("serve",
slog.String("requestid", rid),
))
log.LogAttrs(ctx, slog.LevelDebug, "serving request",
slog.String("user-agent", r.Header.Get("User-Agent")),
slog.String("method", r.Method),
slog.String("requestPath", r.URL.Path),
)
ctx = context.WithValue(ctx, loggerKey, log)
r = r.WithContext(ctx)
metrics := httpsnoop.CaptureMetrics(instance.handler, w, r)
log.LogAttrs(ctx, levelDebug2, "request served",
slog.Group("response",
slog.Duration("duration", metrics.Duration),
slog.Int("statusCode", metrics.Code),
slog.Int64("bytes", metrics.Written),
slog.String("pattern", r.Pattern),
))
}
// waitInFlight blocks until inflight is 0 or ctx is done. Caller must cancel
// the instance context first: concurrent enters then bump the counter, see
// cancel, and decrement without running the handler. Retire is rare, so a
// short poll is enough (returns immediately when already idle).
func (instance *Instance) waitInFlight(ctx context.Context) {
if instance == nil {
return
}
if instance.inflight.Load() == 0 {
return
}
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for {
if instance.inflight.Load() == 0 {
return
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
type requestIdType struct{}
var requestIdKey = requestIdType{}
func GetRequestId(ctx context.Context) string {
// xtemplate request id
if av := ctx.Value(requestIdKey); av != nil {
if v, ok := av.(string); ok {
return v
}
}
// caddy request id
if v := ctx.Value("vars"); v != nil {
if mv, ok := v.(map[string]any); ok {
if anyrid, ok := mv["uuid"]; ok {
if rid, ok := anyrid.(string); ok {
return rid
}
}
}
}
return ""
}
type loggerType struct{}
var loggerKey = loggerType{}
func GetLogger(ctx context.Context) *slog.Logger {
log, ok := ctx.Value(loggerKey).(*slog.Logger)
if !ok {
return slog.Default()
}
return log
}