-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
interpreter.go
761 lines (688 loc) · 20.4 KB
/
interpreter.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
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
package interpreter
import (
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
"github.com/ysugimoto/falco/ast"
"github.com/ysugimoto/falco/interpreter/cache"
"github.com/ysugimoto/falco/interpreter/context"
"github.com/ysugimoto/falco/interpreter/exception"
"github.com/ysugimoto/falco/interpreter/limitations"
"github.com/ysugimoto/falco/interpreter/process"
"github.com/ysugimoto/falco/interpreter/value"
"github.com/ysugimoto/falco/interpreter/variable"
"github.com/ysugimoto/falco/lexer"
"github.com/ysugimoto/falco/parser"
)
type Interpreter struct {
vars variable.Variable
localVars variable.LocalVariables
lock sync.Mutex
options []context.Option
ctx *context.Context
process *process.Process
cache *cache.Cache
Debugger Debugger
IdentResolver func(v string) value.Value
TestingState State
}
func New(options ...context.Option) *Interpreter {
return &Interpreter{
options: options,
cache: cache.New(),
localVars: variable.LocalVariables{},
Debugger: DefaultDebugger{},
TestingState: NONE,
}
}
func (i *Interpreter) SetScope(scope context.Scope) {
i.ctx.Scope = scope
switch scope {
case context.RecvScope:
i.vars = variable.NewRecvScopeVariables(i.ctx)
case context.HashScope:
i.vars = variable.NewHashScopeVariables(i.ctx)
case context.HitScope:
i.vars = variable.NewHitScopeVariables(i.ctx)
case context.MissScope:
i.vars = variable.NewMissScopeVariables(i.ctx)
case context.PassScope:
i.vars = variable.NewPassScopeVariables(i.ctx)
case context.FetchScope:
i.vars = variable.NewFetchScopeVariables(i.ctx)
case context.DeliverScope:
i.vars = variable.NewDeliverScopeVariables(i.ctx)
case context.ErrorScope:
i.vars = variable.NewErrorScopeVariables(i.ctx)
case context.LogScope:
i.vars = variable.NewLogScopeVariables(i.ctx)
}
}
func (i *Interpreter) restart() error {
i.ctx.Restarts++
i.Debugger.Message(fmt.Sprintf("Restarted (%d) time", i.ctx.Restarts))
i.ctx.BackendRequest = nil
i.ctx.BackendResponse = nil
i.ctx.Object = nil
i.ctx.Response = nil
if err := i.ProcessRecv(); err != nil {
return err
}
return nil
}
func (i *Interpreter) ProcessInit(r *http.Request) error {
ctx := context.New(i.options...)
main, err := ctx.Resolver.MainVCL()
if err != nil {
i.Debugger.Message(err.Error())
return err
}
if err := limitations.CheckFastlyVCLLimitation(main.Data); err != nil {
i.Debugger.Message(err.Error())
return err
}
vcl, err := parser.New(
lexer.NewFromString(main.Data, lexer.WithFile(main.Name)),
).ParseVCL()
if err != nil {
// parse error
i.Debugger.Message(err.Error())
return err
}
// If remote snippets exists, prepare parse and prepend to main VCL
if ctx.FastlySnippets != nil {
for _, snip := range ctx.FastlySnippets.EmbedSnippets() {
s, err := parser.New(
lexer.NewFromString(snip.Data, lexer.WithFile(snip.Name)),
).ParseVCL()
if err != nil {
// parse error
i.Debugger.Message(err.Error())
return err
}
vcl.Statements = append(s.Statements, vcl.Statements...)
}
}
ctx.RequestStartTime = time.Now()
i.ctx = ctx
i.ctx.Request = r
r.Header.Set("Host", r.Host)
// OriginalHost value may be overridden. If not empty, set the request value
if i.ctx.OriginalHost == "" {
i.ctx.OriginalHost = r.Host
}
i.process = process.New()
i.ctx.Scope = context.InitScope
i.vars = variable.NewAllScopeVariables(i.ctx)
statements, err := i.resolveIncludeStatement(vcl.Statements, true)
if err != nil {
return err
}
if err := i.ProcessDeclarations(statements); err != nil {
return err
}
if err := limitations.CheckFastlyResourceLimit(i.ctx); err != nil {
return err
}
return nil
}
func (i *Interpreter) ProcessDeclarations(statements []ast.Statement) error {
// Process root declarations and statements.
// Must process backends first because they're referenced by directors.
// https://developer.fastly.com/reference/vcl/declarations/
if err := i.ProcessBackends(statements); err != nil {
return err
}
for _, stmt := range statements {
switch t := stmt.(type) {
case *ast.AclDeclaration:
i.Debugger.Run(stmt)
if _, ok := i.ctx.Acls[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "ACL %s is duplicated", t.Name.Value)
}
i.ctx.Acls[t.Name.Value] = &value.Acl{Value: t, Literal: true}
case *ast.DirectorDeclaration:
i.Debugger.Run(stmt)
// Director should treat as backend
if _, ok := i.ctx.Backends[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "Director %s is duplicated in backend definition", t.Name.Value)
}
dc, err := i.getDirectorConfig(t)
if err != nil {
return errors.WithStack(err)
}
i.ctx.Backends[t.Name.Value] = &value.Backend{Director: dc, Literal: true}
case *ast.TableDeclaration:
i.Debugger.Run(stmt)
if _, ok := i.ctx.Tables[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "Table %s is duplicated", t.Name.Value)
}
i.ctx.Tables[t.Name.Value] = t
case *ast.SubroutineDeclaration:
i.Debugger.Run(stmt)
if t.ReturnType != nil {
if _, ok := i.ctx.SubroutineFunctions[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "Subroutine %s is duplicated", t.Name.Value)
}
i.ctx.SubroutineFunctions[t.Name.Value] = t
continue
}
exists, ok := i.ctx.Subroutines[t.Name.Value]
if !ok {
i.ctx.Subroutines[t.Name.Value] = t
continue
}
// Duplicated fastly reserved subroutines should be concatenated
// ref: https://developer.fastly.com/reference/vcl/subroutines/#concatenation
if _, ok := context.FastlyReservedSubroutine[t.Name.Value]; ok {
exists.Block.Statements = append(exists.Block.Statements, t.Block.Statements...)
continue
}
// Other custom user subroutine could not be duplicated
return exception.Runtime(&t.Token, "Subroutine %s is duplicated", t.Name.Value)
case *ast.PenaltyboxDeclaration:
i.Debugger.Run(stmt)
if _, ok := i.ctx.Penaltyboxes[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "Penaltybox %s is duplicated", t.Name.Value)
}
i.ctx.Penaltyboxes[t.Name.Value] = t
case *ast.RatecounterDeclaration:
i.Debugger.Run(stmt)
if _, ok := i.ctx.Ratecounters[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "Ratecounter %s is duplicated", t.Name.Value)
}
i.ctx.Ratecounters[t.Name.Value] = t
}
}
return nil
}
func (i *Interpreter) ProcessBackends(statements []ast.Statement) error {
for _, stmt := range statements {
t, ok := stmt.(*ast.BackendDeclaration)
if !ok {
continue
}
i.Debugger.Run(stmt)
h := &atomic.Bool{}
h.Store(true)
// Determine default backend
if i.ctx.Backend == nil {
i.ctx.Backend = &value.Backend{Value: t, Literal: true, Healthy: h}
}
if _, ok := i.ctx.Backends[t.Name.Value]; ok {
return exception.Runtime(&t.Token, "Backend %s is duplicated", t.Name.Value)
}
i.ctx.Backends[t.Name.Value] = &value.Backend{Value: t, Literal: true, Healthy: h}
}
return nil
}
func (i *Interpreter) ProcessRecv() error {
i.SetScope(context.RecvScope)
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
var err error
var state State
sub, ok := i.ctx.Subroutines[context.FastlyVclNameRecv]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
} else {
state = PASS
}
switch state {
case PASS:
i.ctx.State = "MISS"
i.Debugger.Message(fmt.Sprintf("Move state: %s -> HASH", i.ctx.Scope))
if err = i.ProcessHash(); err != nil {
return errors.WithStack(err)
}
i.Debugger.Message(fmt.Sprintf("Move state: %s -> PASS", i.ctx.Scope))
err = i.ProcessPass()
case ERROR:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> ERROR", i.ctx.Scope))
err = i.ProcessError()
case RESTART:
err = i.restart()
case LOOKUP, NONE:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> HASH", i.ctx.Scope))
if err = i.ProcessHash(); err != nil {
return errors.WithStack(err)
}
if v := i.cache.Get(i.ctx.RequestHash.Value); v != nil {
i.process.Cached = true
i.ctx.State = "HIT"
i.ctx.CacheHitItem = v
i.ctx.Object = i.cloneResponse(v.Response)
i.Debugger.Message(fmt.Sprintf("Move state: %s -> HIT", i.ctx.Scope))
err = i.ProcessHit()
} else {
i.ctx.State = "MISS"
i.Debugger.Message(fmt.Sprintf("Move state: %s -> MISS", i.ctx.Scope))
err = i.ProcessMiss()
}
default:
return exception.Runtime(
&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in RECV",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessHash() error {
i.SetScope(context.HashScope)
// Make default VCL hash string
// https://developer.fastly.com/reference/vcl/subroutines/hash/
i.ctx.RequestHash = &value.String{
Value: i.ctx.Request.URL.String(),
}
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
if sub, ok := i.ctx.Subroutines[context.FastlyVclNameHash]; ok {
if state, err := i.ProcessSubroutine(sub, DebugPass); err != nil {
return errors.WithStack(err)
} else if state != HASH && state != NONE {
return exception.Runtime(
&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in HASH",
sub.Name.Value,
state,
)
}
}
return nil
}
func (i *Interpreter) ProcessMiss() error {
i.SetScope(context.MissScope)
if i.ctx.Backend == nil {
return exception.Runtime(nil, "No backend determined in MISS")
}
var err error
if i.ctx.Backend.Director != nil {
i.ctx.BackendRequest, err = i.createDirectorRequest(i.ctx, i.ctx.Backend.Director)
} else {
i.ctx.BackendRequest, err = i.createBackendRequest(i.ctx, i.ctx.Backend)
}
if err != nil {
return errors.WithStack(err)
}
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
state := FETCH
sub, ok := i.ctx.Subroutines[context.FastlyVclNameMiss]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
if state == NONE {
state = FETCH
}
}
switch state {
case DELIVER_STALE:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> DELIVER", i.ctx.Scope))
err = i.ProcessDeliver()
case PASS:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> PASS", i.ctx.Scope))
err = i.ProcessPass()
case ERROR:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> ERROR", i.ctx.Scope))
err = i.ProcessError()
case FETCH:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> FETCH", i.ctx.Scope))
err = i.ProcessFetch()
default:
return exception.Runtime(
&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in MISS",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessHit() error {
i.SetScope(context.HitScope)
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
var err error
state := DELIVER
sub, ok := i.ctx.Subroutines[context.FastlyVclNameHit]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
if state == NONE {
state = DELIVER
}
}
// Update cache lifetime because cache object statue may be changed by setting obj.ttl
if i.ctx.ObjectTTL.Value > 0 {
i.ctx.CacheHitItem.Update(i.ctx.ObjectTTL.Value)
}
switch state {
case DELIVER:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> DELIVER", i.ctx.Scope))
err = i.ProcessDeliver()
case PASS:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> PASS", i.ctx.Scope))
err = i.ProcessPass()
case ERROR:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> ERROR", i.ctx.Scope))
err = i.ProcessError()
case RESTART:
err = i.restart()
default:
return exception.Runtime(
&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in HIT",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessPass() error {
i.SetScope(context.PassScope)
if i.ctx.Backend == nil {
return exception.Runtime(nil, "No backend determined in PASS")
}
var err error
if i.ctx.Backend.Director != nil {
i.ctx.BackendRequest, err = i.createDirectorRequest(i.ctx, i.ctx.Backend.Director)
} else {
i.ctx.BackendRequest, err = i.createBackendRequest(i.ctx, i.ctx.Backend)
}
if err != nil {
return errors.WithStack(err)
}
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
state := PASS
sub, ok := i.ctx.Subroutines[context.FastlyVclNamePass]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
if state == NONE {
state = PASS
}
}
switch state {
case PASS:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> FETCH", i.ctx.Scope))
err = i.ProcessFetch()
case ERROR:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> ERROR", i.ctx.Scope))
err = i.ProcessError()
default:
return exception.Runtime(
&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in PASS",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessFetch() error {
i.SetScope(context.FetchScope)
if i.ctx.BackendRequest == nil {
return exception.System("No backend determined on FETCH")
}
// Send request to backend
var err error
i.ctx.BackendResponse, err = i.sendBackendRequest(i.ctx.Backend)
if err != nil {
return errors.WithStack(err)
}
// Mark request process has ended
i.ctx.RequestEndTime = time.Now()
// Set cacheable strategy
isCacheable := cache.IsCacheableStatusCode(i.ctx.BackendResponse.StatusCode)
i.ctx.BackendResponseCacheable = &value.Boolean{Value: isCacheable}
if isCacheable {
i.ctx.BackendResponseTTL = &value.RTime{
Value: i.determineCacheTTL(i.ctx.BackendResponse),
}
}
// TODO: consider stale-white-revalidate and stale-if-error TTL
// Update cache
defer func() {
resp := i.cloneResponse(i.ctx.BackendResponse)
// Note: compare BackendResponseCacheable value
// because this value will be changed by user in vcl_fetch directive
if i.ctx.BackendResponseCacheable.Value {
if i.ctx.BackendResponseTTL.Value.Seconds() > 0 {
now := time.Now()
i.cache.Set(i.ctx.RequestHash.String(), &cache.CacheItem{
Response: resp,
Expires: now.Add(i.ctx.BackendResponseTTL.Value),
EntryTime: now,
})
}
}
}()
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
state := DELIVER
sub, ok := i.ctx.Subroutines[context.FastlyVclNameFetch]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
if state == NONE {
state = DELIVER
}
}
switch state {
case DELIVER, DELIVER_STALE, PASS:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> DELIVER", i.ctx.Scope))
err = i.ProcessDeliver()
case ERROR:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> ERROR", i.ctx.Scope))
err = i.ProcessError()
case RESTART:
err = i.restart()
default:
return exception.Runtime(&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in FETCH",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessError() error {
i.SetScope(context.ErrorScope)
// If process goes through the error directive, response will be generated locally
// @see: https://developer.fastly.com/reference/vcl/variables/client-response/resp-is-locally-generated/
i.ctx.IsLocallyGenerated = &value.Boolean{Value: true}
i.ctx.Object = &http.Response{
StatusCode: int(i.ctx.ObjectStatus.Value),
Status: http.StatusText(int(i.ctx.ObjectStatus.Value)),
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 1,
Header: http.Header{},
Body: io.NopCloser(strings.NewReader(i.ctx.ObjectResponse.Value)),
ContentLength: int64(len(i.ctx.ObjectResponse.Value)),
Request: i.ctx.Request,
}
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
var err error
state := DELIVER
sub, ok := i.ctx.Subroutines[context.FastlyVclNameError]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
if state == NONE {
state = DELIVER
}
}
switch state {
case DELIVER:
i.Debugger.Message(fmt.Sprintf("Move state: %s -> DELIVER", i.ctx.Scope))
err = i.ProcessDeliver()
case RESTART:
err = i.restart()
default:
return exception.Runtime(&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in ERROR",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessDeliver() error {
i.SetScope(context.DeliverScope)
if i.ctx.Object != nil {
i.ctx.Response = i.cloneResponse(i.ctx.Object)
} else if i.ctx.BackendResponse != nil {
i.ctx.Response = i.cloneResponse(i.ctx.BackendResponse)
}
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
var err error
state := LOG
sub, ok := i.ctx.Subroutines[context.FastlyVclNameDeliver]
if ok {
state, err = i.ProcessSubroutine(sub, DebugPass)
if err != nil {
return errors.WithStack(err)
}
if state == NONE {
state = LOG
}
}
switch state {
case RESTART:
err = i.restart()
case LOG, DELIVER:
// When ESI is triggered in FETCH directive, execute ESI
if i.ctx.TriggerESI {
if err := i.executeESI(); err != nil {
return errors.WithStack(err)
}
}
// Add Fastly related server info but values are falco's one
i.ctx.Response.Header.Set("X-Served-By", cache.LocalDatacenterString)
i.ctx.Response.Header.Set("X-Cache", i.ctx.State)
// Additionally set cache related headers
if i.ctx.CacheHitItem != nil {
i.ctx.Response.Header.Set("X-Cache-Hits", fmt.Sprint(i.ctx.CacheHitItem.Hits))
i.ctx.Response.Header.Set("Age", fmt.Sprintf("%.0f", time.Since(i.ctx.CacheHitItem.EntryTime).Seconds()))
} else {
i.ctx.Response.Header.Set("X-Cache-Hits", "0")
}
// When Fastly-Debug header is present, add debug header but values are fakes
if i.ctx.Request.Header.Get("Fastly-Debug") != "" {
i.ctx.Response.Header.Set(
"Fastly-Debug-Path",
fmt.Sprintf("(D %s 0) (F %s 0)", cache.LocalDatacenterString, cache.LocalDatacenterString),
)
cacheHit := "M"
if i.ctx.State == "HIT" {
cacheHit = "H"
}
i.ctx.Response.Header.Set(
"Fastly-Debug-TTL",
fmt.Sprintf("(%s %s %.3f %.3f %d)", cacheHit, cache.LocalDatacenterString, 0.000, 0.000, 0),
)
}
i.Debugger.Message(fmt.Sprintf("Move state: %s -> LOG", i.ctx.Scope))
err = i.ProcessLog()
default:
return exception.Runtime(&sub.GetMeta().Token,
"Subroutine %s returned unexpected state %s in DELIVER",
sub.Name.Value,
state,
)
}
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (i *Interpreter) ProcessLog() error {
i.SetScope(context.LogScope)
if i.ctx.Response == nil {
if i.ctx.Object != nil {
v := *i.ctx.Object
i.ctx.Response = &v
} else if i.ctx.BackendResponse != nil {
v := *i.ctx.BackendResponse
i.ctx.Response = &v
}
}
// Simulate Fastly statement lifecycle
// see: https://developer.fastly.com/learning/vcl/using/#the-vcl-request-lifecycle
if sub, ok := i.ctx.Subroutines[context.FastlyVclNameLog]; ok {
if _, err := i.ProcessSubroutine(sub, DebugPass); err != nil {
return errors.WithStack(err)
}
}
return nil
}
var expiresValueLayout = "Mon, 02 Jan 2006 15:04:05 MST"
func (i *Interpreter) determineCacheTTL(resp *http.Response) time.Duration {
if v := resp.Header.Get("Surrogate-Control"); v != "" {
if strings.HasPrefix(v, "max-age=") {
if dur, err := time.ParseDuration(strings.TrimPrefix(v, "max-age=") + "s"); err == nil {
return dur
}
}
}
if v := resp.Header.Get("Cache-Control"); v != "" {
if strings.HasPrefix(v, "s-maxage=") {
if dur, err := time.ParseDuration(strings.TrimPrefix(v, "s-maxage=") + "s"); err == nil {
return dur
}
}
if strings.HasPrefix(v, "max-age=") {
if dur, err := time.ParseDuration(strings.TrimPrefix(v, "max-age=") + "s"); err == nil {
return dur
}
}
}
if v := resp.Header.Get("Expires"); v != "" {
if d, err := time.Parse(expiresValueLayout, v); err == nil {
return time.Until(d)
}
}
return time.Duration(2 * time.Minute)
}