@@ -8,16 +8,26 @@ import (
88 "time"
99
1010 "github.com/jellydator/ttlcache/v3"
11+ "go.opentelemetry.io/otel"
12+ "go.opentelemetry.io/otel/metric"
1113 "go.uber.org/zap"
1214 "golang.org/x/sys/unix"
1315
1416 "github.com/e2b-dev/infra/packages/orchestrator/pkg/cfg"
1517 "github.com/e2b-dev/infra/packages/orchestrator/pkg/units"
1618 "github.com/e2b-dev/infra/packages/shared/pkg/featureflags"
1719 "github.com/e2b-dev/infra/packages/shared/pkg/logger"
20+ "github.com/e2b-dev/infra/packages/shared/pkg/utils"
1821)
1922
20- var fallbackDiffSize = units .MBToBytes (100 )
23+ var (
24+ fallbackDiffSize = units .MBToBytes (100 )
25+
26+ meter = otel .Meter ("github.com/e2b-dev/infra/packages/orchestrator/pkg/sandbox/build" )
27+ residenceDurationMetric = utils .Must (meter .Int64Histogram ("orchestrator.build.cache.residence_duration" ,
28+ metric .WithDescription ("How long a diff was kept in the local build cache before eviction" ),
29+ metric .WithUnit ("s" )))
30+ )
2131
2232type deleteDiff struct {
2333 size int64
@@ -37,6 +47,8 @@ type DiffStore struct {
3747 pdSizes map [DiffStoreKey ]* deleteDiff
3848 pdMu sync.RWMutex
3949 pdDelay time.Duration
50+
51+ insertionTimes sync.Map // map[DiffStoreKey]time.Time — tracks when each diff was cached
4052}
4153
4254func NewDiffStore (
@@ -65,7 +77,13 @@ func NewDiffStore(
6577 }
6678
6779 cache .OnEviction (func (ctx context.Context , _ ttlcache.EvictionReason , item * ttlcache.Item [DiffStoreKey , Diff ]) {
80+ if insertedAt , ok := ds .insertionTimes .LoadAndDelete (item .Key ()); ok {
81+ duration := time .Since (insertedAt .(time.Time ))
82+ residenceDurationMetric .Record (ctx , int64 (duration .Seconds ()))
83+ }
84+
6885 buildData := item .Value ()
86+
6987 // buildData will be deleted by calling buildData.Close()
7088 defer ds .resetDelete (item .Key ())
7189
@@ -110,6 +128,8 @@ func (s *DiffStore) Get(ctx context.Context, diff Diff) (Diff, error) {
110128 }
111129
112130 if ! found {
131+ s .insertionTimes .Store (diff .CacheKey (), time .Now ())
132+
113133 err := diff .Init (ctx )
114134 if err != nil {
115135 return nil , fmt .Errorf ("failed to init source: %w" , err )
@@ -122,6 +142,7 @@ func (s *DiffStore) Get(ctx context.Context, diff Diff) (Diff, error) {
122142func (s * DiffStore ) Add (d Diff ) {
123143 s .resetDelete (d .CacheKey ())
124144 s .cache .Set (d .CacheKey (), d , ttlcache .DefaultTTL )
145+ s .insertionTimes .LoadOrStore (d .CacheKey (), time .Now ())
125146}
126147
127148func (s * DiffStore ) Has (d Diff ) bool {
0 commit comments