-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
2095 lines (1832 loc) · 56.4 KB
/
cache.go
File metadata and controls
2095 lines (1832 loc) · 56.4 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
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: EUPL-1.2
// Package cache provides a storage-agnostic, JSON-based cache backed by any io.Medium.
package cache
import (
// Note: AX-6 — structural: coreio.Medium surfaces fs.ErrNotExist/fs.DirEntry, and Lstat symlink checks use fs.ModeSymlink.
"io/fs"
// Note: AX-6 — intrinsic: coreio.Medium has no no-follow Lstat primitive or dynamic cwd lookup.
"os"
"slices"
"sync" // Note: AX-6 — structural concurrency primitive for entry-level write serialisation.
// Note: AX-6 — no core equivalent for durations or wall-clock timestamps.
"time"
"dappco.re/go/core"
coreio "dappco.re/go/io"
)
// DefaultTTL is the default cache expiry time.
//
// Usage example:
//
// c, err := cache.New(coreio.NewMockMedium(), "/tmp/cache", cache.DefaultTTL)
const DefaultTTL = 1 * time.Hour
const (
maxCacheKeyBytes = 4096
maxCachePatternBytes = 4096
maxCacheNameBytes = 255
maxCachedRequestURLBytes = 8192
maxCachedRequestMethodBytes = 32
maxCachedStatusTextBytes = 1024
maxCachedHeaderNameBytes = 256
maxCachedHeaderValueBytes = 8192
maxCachedHeaderCount = 128
)
// Cache stores JSON-encoded entries in a Medium-backed cache rooted at baseDir.
//
// c, err := cache.New(coreio.Local, "/tmp/cache", 5*time.Minute)
type Cache struct {
medium coreio.Medium
baseDir string
cacheTTL time.Duration
invalidation map[string][]InvalidateFunc
entryMu sync.RWMutex
runtime *core.Core
}
// Entry is the serialized cache record written to the backing Medium.
//
// entry := cache.Entry{
// Data: []byte(`{"foo":"bar"}`),
// CachedAt: time.Now(),
// ExpiresAt: time.Now().Add(time.Hour),
// }
type Entry struct {
Data rawJSON `json:"data"`
CachedAt time.Time `json:"cached_at"`
ExpiresAt time.Time `json:"expires_at"`
}
type rawJSON []byte
func (raw rawJSON) MarshalJSON() ([]byte, error) {
if raw == nil {
return []byte("null"), nil
}
return raw, nil
}
func (raw *rawJSON) UnmarshalJSON(data []byte) error {
if raw == nil {
return core.E("cache.rawJSON.UnmarshalJSON", "target is nil", nil)
}
*raw = append((*raw)[0:0], data...)
return nil
}
func marshalPrettyJSON(value any) (string, error) {
result := core.JSONMarshal(value)
if !result.OK {
return "", result.Value.(error)
}
return indentJSON([]byte(core.JSONMarshalString(value))), nil
}
func indentJSON(data []byte) string {
builder := core.NewBuilder()
indent := 0
inString := false
escaped := false
writeIndent := func() {
for i := 0; i < indent; i++ {
builder.WriteString(" ")
}
}
for i, c := range data {
if inString {
builder.WriteByte(c)
if escaped {
escaped = false
continue
}
switch c {
case '\\':
escaped = true
case '"':
inString = false
}
continue
}
switch c {
case '"':
inString = true
builder.WriteByte(c)
case '{', '[':
builder.WriteByte(c)
next := nextNonJSONSpace(data, i+1)
if next >= 0 && ((c == '{' && data[next] == '}') || (c == '[' && data[next] == ']')) {
continue
}
indent++
builder.WriteByte('\n')
writeIndent()
case '}', ']':
previous := previousNonJSONSpace(data, i-1)
if previous >= 0 && ((c == '}' && data[previous] == '{') || (c == ']' && data[previous] == '[')) {
builder.WriteByte(c)
continue
}
if indent > 0 {
indent--
}
builder.WriteByte('\n')
writeIndent()
builder.WriteByte(c)
case ',':
builder.WriteByte(c)
builder.WriteByte('\n')
writeIndent()
case ':':
builder.WriteString(": ")
default:
if !isJSONSpace(c) {
builder.WriteByte(c)
}
}
}
return builder.String()
}
func nextNonJSONSpace(data []byte, start int) int {
for i := start; i < len(data); i++ {
if !isJSONSpace(data[i]) {
return i
}
}
return -1
}
func previousNonJSONSpace(data []byte, start int) int {
for i := start; i >= 0; i-- {
if !isJSONSpace(data[i]) {
return i
}
}
return -1
}
func isJSONSpace(c byte) bool {
return c == ' ' || c == '\n' || c == '\r' || c == '\t'
}
// BinaryMeta is the metadata for binary cache payloads.
//
// {
// "content_type":"application/wasm",
// "size":1048576,
// "cached_at":"2026-04-14T00:00:00Z",
// "expires_at":"2026-04-15T00:00:00Z"
// }
type BinaryMeta struct {
ContentType string `json:"content_type"`
Size int64 `json:"size"`
CachedAt time.Time `json:"cached_at"`
ExpiresAt time.Time `json:"expires_at"`
}
// InvalidateFunc returns glob patterns to delete when a registered trigger fires.
//
// c.OnInvalidate("dns.tree-root-changed", func(trigger string) []string {
// return []string{"dns/*"}
// })
type InvalidateFunc func(trigger string) []string
// New creates a cache with explicit storage, root directory, and TTL.
//
// c, err := cache.New(coreio.Local, "/tmp/cache", 5*time.Minute)
// c, err = cache.New(nil, "", 0) // uses Local, .core/cache, and DefaultTTL
func New(medium coreio.Medium, baseDir string, cacheTTL time.Duration) (*Cache, error) {
if medium == nil {
medium = coreio.Local
}
if baseDir == "" {
cwd := currentDir()
if cwd == "" || cwd == "." {
return nil, core.E("cache.New", "failed to resolve current working directory", nil)
}
baseDir = normalizePath(core.JoinPath(cwd, ".core", "cache"))
} else {
baseDir = absolutePath(baseDir)
}
if cacheTTL < 0 {
return nil, core.E("cache.New", "ttl must be >= 0", nil)
}
if cacheTTL == 0 {
cacheTTL = DefaultTTL
}
if err := medium.EnsureDir(baseDir); err != nil {
return nil, core.E("cache.New", "failed to create cache directory", err)
}
return &Cache{
medium: medium,
baseDir: baseDir,
cacheTTL: cacheTTL,
invalidation: make(map[string][]InvalidateFunc),
runtime: core.New(),
}, nil
}
// Path resolves the on-disk JSON path for a cache key.
//
// path, err := c.Path("github/acme/repos")
// // => /tmp/cache/github/acme/repos.json
func (cache *Cache) Path(key string) (string, error) {
if err := cache.ensureConfigured("cache.Path"); err != nil {
return "", err
}
if err := ensureSafeKey(key); err != nil {
return "", err
}
baseDir := absolutePath(cache.baseDir)
path := absolutePath(core.JoinPath(baseDir, key+".json"))
pathPrefix := normalizePath(core.Concat(baseDir, pathSeparator()))
if path != baseDir && !core.HasPrefix(path, pathPrefix) {
return "", core.E("cache.Path", "invalid cache key: path traversal attempt", nil)
}
if err := ensureNoSymlinkPath(baseDir, path); err != nil {
return "", core.E("cache.Path", "invalid cache key: symlink escape attempt", err)
}
return path, nil
}
// entryPaths resolves the JSON and binary file paths for a cache key.
//
// jsonPath, binPath, err := c.entryPaths("github/acme/repos")
func (cache *Cache) entryPaths(key string) (string, string, error) {
jsonPath, err := cache.Path(key)
if err != nil {
return "", "", err
}
baseDir := absolutePath(cache.baseDir)
binaryPath := absolutePath(core.JoinPath(baseDir, key+".bin"))
return jsonPath, binaryPath, nil
}
// Get unmarshals the cached item into dest if it exists and has not expired.
//
// found, err := c.Get("github/acme/repos", &repos)
func (cache *Cache) Get(key string, dest any) (bool, error) {
if err := cache.ensureReady("cache.Get"); err != nil {
return false, err
}
cache.entryMu.RLock()
defer cache.entryMu.RUnlock()
path, err := cache.Path(key)
if err != nil {
return false, err
}
dataStr, err := cache.medium.Read(path)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, core.E("cache.Get", "failed to read cache file", err)
}
var entry Entry
entryResult := core.JSONUnmarshalString(dataStr, &entry)
if !entryResult.OK {
return false, core.E("cache.Get", "failed to unmarshal cache entry", entryResult.Value.(error))
}
if time.Now().After(entry.ExpiresAt) {
return false, nil
}
if err := core.JSONUnmarshal(entry.Data, dest); !err.OK {
return false, core.E("cache.Get", "failed to unmarshal cached data", err.Value.(error))
}
return true, nil
}
// Set stores a value using the cache's default TTL.
//
// err := c.Set("github/acme/repos", repos)
// err = c.Set("config/theme", "dark")
func (cache *Cache) Set(key string, data any) error {
if err := cache.ensureReady("cache.Set"); err != nil {
return err
}
return cache.set(key, data, cache.defaultTTL(), true)
}
// SetWithTTL stores a value with an explicit TTL override.
//
// err := c.SetWithTTL("dns/example.com/A", records, 5*time.Minute)
// err = c.SetWithTTL("session/token", token, 30*time.Second)
func (cache *Cache) SetWithTTL(key string, data any, ttl time.Duration) error {
if err := cache.ensureReady("cache.SetWithTTL"); err != nil {
return err
}
return cache.set(key, data, ttl, false)
}
func (cache *Cache) set(key string, data any, ttl time.Duration, useDefaultTTL bool) error {
if err := cache.ensureReady("cache.set"); err != nil {
return err
}
cache.entryMu.Lock()
defer cache.entryMu.Unlock()
path, _, err := cache.entryPaths(key)
if err != nil {
return err
}
snapshot, err := readFileSnapshot(cache.medium, path)
if err != nil {
return core.E("cache.set", "failed to inspect existing cache entry", err)
}
if err := cache.medium.EnsureDir(core.PathDir(path)); err != nil {
return core.E("cache.Set", "failed to create directory", err)
}
dataResult := core.JSONMarshal(data)
if !dataResult.OK {
return core.E("cache.Set", "failed to marshal cache data", dataResult.Value.(error))
}
if ttl < 0 {
return core.E("cache.set", "cache ttl must be >= 0", nil)
}
if ttl == 0 && useDefaultTTL {
ttl = cache.defaultTTL()
}
now := time.Now()
entry := Entry{
Data: rawJSON(dataResult.Value.([]byte)),
CachedAt: now,
ExpiresAt: now.Add(ttl),
}
entryJSON, err := marshalPrettyJSON(entry)
if err != nil {
return core.E("cache.Set", "failed to marshal cache entry", err)
}
if err := cache.medium.Write(path, entryJSON); err != nil {
_ = restoreFileSnapshot(cache.medium, snapshot)
return core.E("cache.set", "failed to write cache file", err)
}
return nil
}
// Delete removes one cached entry.
//
// err := c.Delete("github/acme/repos")
func (cache *Cache) Delete(key string) error {
if err := cache.ensureReady("cache.Delete"); err != nil {
return err
}
_, err := cache.removeEntryFiles(key)
if core.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
// removeEntryFiles deletes both the JSON metadata and sidecar binary payload for a key.
func (cache *Cache) removeEntryFiles(key string) (bool, error) {
if err := cache.ensureReady("cache.removeEntryFiles"); err != nil {
return false, err
}
cache.entryMu.Lock()
defer cache.entryMu.Unlock()
jsonPath, binaryPath, err := cache.entryPaths(key)
if err != nil {
return false, err
}
removed := false
if err := cache.medium.Delete(jsonPath); err != nil {
if !core.Is(err, fs.ErrNotExist) {
return removed, core.E("cache.removeEntryFiles", "failed to delete cache json file", err)
}
} else {
removed = true
}
if err := cache.medium.Delete(binaryPath); err != nil {
if !core.Is(err, fs.ErrNotExist) {
return removed, core.E("cache.removeEntryFiles", "failed to delete cache binary file", err)
}
} else {
removed = true
}
return removed, nil
}
// SetBinary stores raw bytes in a sidecar `.bin` file and metadata in JSON.
//
// err := c.SetBinary("wasm/my-module", wasmBytes, "application/wasm")
// err = c.SetBinary("artifacts/logo", pngBytes, "image/png")
func (cache *Cache) SetBinary(key string, data []byte, contentType string) error {
if err := cache.ensureReady("cache.SetBinary"); err != nil {
return err
}
return cache.setBinary(key, data, contentType, cache.defaultTTL(), true)
}
// SetBinaryWithTTL stores raw bytes with an explicit TTL override.
//
// err := c.SetBinaryWithTTL("responses/temp", body, "text/html", 10*time.Minute)
// err = c.SetBinaryWithTTL("dns/example.com/AAAA", raw, "application/octet-stream", 15*time.Second)
func (cache *Cache) SetBinaryWithTTL(key string, data []byte, contentType string, ttl time.Duration) error {
if err := cache.ensureReady("cache.SetBinaryWithTTL"); err != nil {
return err
}
return cache.setBinary(key, data, contentType, ttl, false)
}
func (cache *Cache) setBinary(key string, data []byte, contentType string, ttl time.Duration, useDefaultTTL bool) error {
if err := cache.ensureReady("cache.setBinary"); err != nil {
return err
}
cache.entryMu.Lock()
defer cache.entryMu.Unlock()
jsonPath, binaryPath, err := cache.entryPaths(key)
if err != nil {
return err
}
jsonSnapshot, err := readFileSnapshot(cache.medium, jsonPath)
if err != nil {
return core.E("cache.setBinary", "failed to inspect existing binary metadata", err)
}
binarySnapshot, err := readFileSnapshot(cache.medium, binaryPath)
if err != nil {
return core.E("cache.setBinary", "failed to inspect existing binary payload", err)
}
if ttl < 0 {
return core.E("cache.setBinary", "cache ttl must be >= 0", nil)
}
if ttl == 0 && useDefaultTTL {
ttl = cache.defaultTTL()
}
if err := cache.medium.EnsureDir(core.PathDir(jsonPath)); err != nil {
return core.E("cache.setBinary", "failed to create directory", err)
}
now := time.Now()
meta := BinaryMeta{
ContentType: contentType,
Size: int64(len(data)),
CachedAt: now,
ExpiresAt: now.Add(ttl),
}
metaJSON, err := marshalPrettyJSON(meta)
if err != nil {
return core.E("cache.setBinary", "failed to marshal binary metadata", err)
}
if err := cache.medium.Write(binaryPath, string(data)); err != nil {
_ = restoreFileSnapshot(cache.medium, jsonSnapshot)
_ = restoreFileSnapshot(cache.medium, binarySnapshot)
return core.E("cache.setBinary", "failed to write binary payload", err)
}
if err := cache.medium.Write(jsonPath, metaJSON); err != nil {
_ = restoreFileSnapshot(cache.medium, binarySnapshot)
_ = restoreFileSnapshot(cache.medium, jsonSnapshot)
return core.E("cache.setBinary", "failed to write binary metadata", err)
}
return nil
}
// GetBinary returns raw binary cache payload.
//
// data, found, err := c.GetBinary("wasm/my-module")
func (cache *Cache) GetBinary(key string) ([]byte, bool, error) {
if err := cache.ensureReady("cache.GetBinary"); err != nil {
return nil, false, err
}
cache.entryMu.RLock()
defer cache.entryMu.RUnlock()
metaPath, binaryPath, err := cache.entryPaths(key)
if err != nil {
return nil, false, err
}
rawMeta, err := cache.medium.Read(metaPath)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return nil, false, nil
}
return nil, false, core.E("cache.GetBinary", "failed to read binary metadata", err)
}
var meta BinaryMeta
metaResult := core.JSONUnmarshalString(rawMeta, &meta)
if !metaResult.OK {
return nil, false, core.E("cache.GetBinary", "failed to unmarshal binary metadata", metaResult.Value.(error))
}
if time.Now().After(meta.ExpiresAt) {
return nil, false, nil
}
body, err := cache.medium.Read(binaryPath)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return nil, false, nil
}
return nil, false, core.E("cache.GetBinary", "failed to read binary data", err)
}
return []byte(body), true, nil
}
// DeleteMany removes several entries in one call. Missing keys are ignored.
//
// err := c.DeleteMany("github/acme/repos", "github/acme/meta")
// err = c.DeleteMany("dns/example.com/A", "dns/example.com/AAAA")
func (cache *Cache) DeleteMany(keys ...string) error {
if err := cache.ensureReady("cache.DeleteMany"); err != nil {
return err
}
cache.entryMu.Lock()
defer cache.entryMu.Unlock()
type entryFileSet struct {
jsonPath string
binaryPath string
}
resolved := make([]entryFileSet, 0, len(keys))
for _, key := range keys {
jsonPath, binaryPath, err := cache.entryPaths(key)
if err != nil {
return err
}
resolved = append(resolved, entryFileSet{jsonPath: jsonPath, binaryPath: binaryPath})
}
for _, paths := range resolved {
if err := cache.medium.Delete(paths.jsonPath); err != nil && !core.Is(err, fs.ErrNotExist) {
return err
}
if err := cache.medium.Delete(paths.binaryPath); err != nil && !core.Is(err, fs.ErrNotExist) {
return err
}
}
return nil
}
func (cache *Cache) listJSONKeys() ([]string, error) {
keys, err := cache.collectJSONKeys("")
if err != nil {
return nil, err
}
slices.Sort(keys)
return keys, nil
}
func (cache *Cache) collectJSONKeys(prefix string) ([]string, error) {
listPath := cache.baseDir
if prefix != "" {
listPath = core.JoinPath(cache.baseDir, prefix)
}
entries, err := cache.medium.List(listPath)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return nil, nil
}
return nil, core.E("cache.collectJSONKeys", "failed to list cache directory", err)
}
var keys []string
for _, entry := range entries {
name := entry.Name()
childPrefix := name
if prefix != "" {
childPrefix = core.JoinPath(prefix, name)
}
if entry.IsDir() {
childKeys, err := cache.collectJSONKeys(childPrefix)
if err != nil {
return nil, err
}
keys = append(keys, childKeys...)
continue
}
if core.HasSuffix(name, ".json") {
keys = append(keys, core.TrimSuffix(childPrefix, ".json"))
}
}
return keys, nil
}
func (cache *Cache) keysByPattern(pattern string) ([]string, error) {
if err := ensureSafePattern(pattern); err != nil {
return nil, err
}
cache.entryMu.RLock()
defer cache.entryMu.RUnlock()
allKeys, err := cache.listJSONKeys()
if err != nil {
return nil, err
}
var matched []string
for _, key := range allKeys {
ok, err := matchKeyPattern(pattern, key)
if err != nil {
return nil, core.E("cache.keysByPattern", "failed to match pattern", err)
}
if ok {
matched = append(matched, key)
}
}
return matched, nil
}
func (cache *Cache) clearScope(prefix string) error {
keys, err := cache.keysByPattern(prefix)
if err != nil {
return err
}
descendants, err := cache.keysByPattern(prefix + "/*")
if err != nil {
return err
}
keys = append(keys, descendants...)
for _, key := range keys {
if _, err := cache.removeEntryFiles(key); err != nil {
return err
}
}
return nil
}
// matchKeyPattern reports whether key matches the glob pattern.
//
// Supported patterns per RFC §12.4:
//
// "dns/*" — all keys under dns/ (any depth)
// "dns/charon.*" — dns/charon.lthn, dns/charon.local, etc. (single segment)
// "scope_a1b2c3/*" — all keys in a specific scope (any depth)
// "exact-key" — single key (no wildcard)
func matchKeyPattern(pattern, key string) (bool, error) {
if !containsAnyGlob(pattern) {
return pattern == key, nil
}
// A trailing "/*" means "all descendants of this prefix" — any depth.
if core.HasSuffix(pattern, "/*") {
prefix := core.TrimSuffix(pattern, "/*")
if prefix == "" {
return true, nil
}
return core.HasPrefix(key, prefix+"/"), nil
}
// Otherwise match a single path segment against the last pattern segment.
patternParts := core.Split(pattern, "/")
keyParts := core.Split(key, "/")
if len(patternParts) != len(keyParts) {
return false, nil
}
for i, part := range patternParts {
if !containsAnyGlob(part) {
if part != keyParts[i] {
return false, nil
}
continue
}
ok, err := segmentMatch(part, keyParts[i])
if err != nil {
return false, err
}
if !ok {
return false, nil
}
}
return true, nil
}
// containsAnyGlob reports whether s contains any glob metacharacter.
//
// containsAnyGlob("dns/*") // true
// containsAnyGlob("exact") // false
func containsAnyGlob(s string) bool {
for _, r := range s {
if r == '*' || r == '?' || r == '[' || r == ']' {
return true
}
}
return false
}
// segmentMatch matches pattern against name within a single path segment.
// Supports '*' (any run of non-separator chars) and literal characters.
//
// segmentMatch("charon.*", "charon.lthn") // true
// segmentMatch("charon.*", "other.lthn") // false
func segmentMatch(pattern, name string) (bool, error) {
p, n := 0, 0
starP, starN := -1, 0
for n < len(name) {
if p < len(pattern) && (pattern[p] == '?' || pattern[p] == name[n]) {
p++
n++
continue
}
if p < len(pattern) && pattern[p] == '*' {
starP = p
starN = n
p++
continue
}
if starP != -1 {
p = starP + 1
starN++
n = starN
continue
}
return false, nil
}
for p < len(pattern) && pattern[p] == '*' {
p++
}
return p == len(pattern), nil
}
// OnInvalidate registers a trigger callback that returns patterns to delete.
//
// c.OnInvalidate("dns.tree-root-changed", func(trigger string) []string {
// return []string{"dns/*"}
// })
func (cache *Cache) OnInvalidate(trigger string, fn InvalidateFunc) {
if err := cache.ensureReady("cache.OnInvalidate"); err != nil {
return
}
if fn == nil {
return
}
lock := cache.runtime.Lock("cache")
lock.Mutex.Lock()
defer lock.Mutex.Unlock()
if cache.invalidation == nil {
cache.invalidation = make(map[string][]InvalidateFunc)
}
cache.invalidation[trigger] = append(cache.invalidation[trigger], fn)
}
// Invalidate executes trigger callbacks and deletes matching entries.
//
// deleted, err := c.Invalidate("dns.tree-root-changed")
func (cache *Cache) Invalidate(trigger string) (int, error) {
if err := cache.ensureReady("cache.Invalidate"); err != nil {
return 0, err
}
lock := cache.runtime.Lock("cache")
lock.Mutex.RLock()
callbacks := append([]InvalidateFunc(nil), cache.invalidation[trigger]...)
lock.Mutex.RUnlock()
total := 0
for _, callback := range callbacks {
for _, pattern := range callback(trigger) {
if pattern == "" {
continue
}
matches, err := cache.keysByPattern(pattern)
if err != nil {
return total, err
}
for _, key := range matches {
removed, err := cache.removeEntryFiles(key)
if err != nil {
return total, err
}
if removed {
total++
}
}
}
}
return total, nil
}
// Scoped returns a cache namespaced by origin hash.
//
// scoped := c.Scoped("https://app.example.com")
// _ = scoped.Set("user/profile", profile)
func (cache *Cache) Scoped(origin string) *ScopedCache {
if cache == nil {
return nil
}
return &ScopedCache{
parent: cache,
prefix: scopePrefix(origin),
}
}
// ClearScope removes cache entries for a scoped origin.
//
// err := c.ClearScope("https://app.example.com")
func (cache *Cache) ClearScope(origin string) error {
if err := cache.ensureReady("cache.ClearScope"); err != nil {
return err
}
prefix := scopePrefix(origin)
if err := ensureSafeKey(prefix); err != nil {
return err
}
return cache.clearScope(prefix)
}
func (cache *Cache) defaultTTL() time.Duration {
if cache.cacheTTL <= 0 {
return DefaultTTL
}
return cache.cacheTTL
}
func ensureSafeKey(key string) error {
if key == "" {
return core.E("cache.validateKey", "invalid empty key", nil)
}
if len(key) > maxCacheKeyBytes {
return core.E("cache.validateKey", "invalid key: too long", nil)
}
if core.Contains(key, "\\") {
return core.E("cache.validateKey", "invalid key: contains path separators", nil)
}
if hasPathDangerousBytes(key) {
return core.E("cache.validateKey", "invalid key: contains control bytes", nil)
}
for _, part := range core.Split(key, "/") {
if part == "" || part == "." || part == ".." {
return core.E("cache.validateKey", "invalid key: path traversal attempt", nil)
}
}
return nil
}
func ensureSafePattern(pattern string) error {
if pattern == "" {
return core.E("cache.validatePattern", "invalid empty pattern", nil)
}
if len(pattern) > maxCachePatternBytes {
return core.E("cache.validatePattern", "invalid pattern: too long", nil)
}
if core.Contains(pattern, "\\") || hasPathDangerousBytes(pattern) {
return core.E("cache.validatePattern", "invalid pattern: contains control bytes", nil)
}
return nil
}
func ensureNoSymlinkPath(baseDir, path string) error {
if err := rejectSymlink(baseDir); err != nil {
return err
}
if path == baseDir {
return nil
}
rel := core.TrimPrefix(path, normalizePath(core.Concat(baseDir, pathSeparator())))
if rel == path {
return nil
}
current := baseDir
for _, part := range core.Split(rel, pathSeparator()) {
if part == "" {
continue
}
current = core.JoinPath(current, part)
if err := rejectSymlink(current); err != nil {
return err
}
}
return nil
}
func rejectSymlink(path string) error {
info, err := os.Lstat(path)
if err != nil {
if core.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
if info.Mode()&fs.ModeSymlink != 0 {
return core.E("cache.validatePath", "path contains symlink", nil)
}
return nil
}
func hasPathDangerousBytes(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < 0x20 || s[i] == 0x7f {
return true
}
}
return false
}
func ensureSafeResponseBodyPath(path string) error {
if path == "" {
return core.E("cache.validateResponseBodyPath", "invalid empty body path", nil)
}
if len(path) > maxCacheKeyBytes {
return core.E("cache.validateResponseBodyPath", "invalid body path: too long", nil)
}
if core.PathIsAbs(path) {
return core.E("cache.validateResponseBodyPath", "invalid body path: absolute paths are not allowed", nil)
}
if core.Contains(path, "\\") || hasPathDangerousBytes(path) {
return core.E("cache.validateResponseBodyPath", "invalid body path: contains control bytes", nil)
}
normalized := normalizePath(path)
if !core.HasPrefix(normalized, "responses/") || !core.HasSuffix(normalized, ".bin") {
return core.E("cache.validateResponseBodyPath", "invalid body path: expected responses/<key>.bin", nil)
}
rel := core.TrimPrefix(normalized, "responses/")