github.com/status-im/status-go@v1.1.0/services/ext/context.go (about) 1 package ext 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/status-im/status-go/db" 8 ) 9 10 // ContextKey is a type used for keys in ext Context. 11 type ContextKey struct { 12 Name string 13 } 14 15 // NewContextKey returns new ContextKey instance. 16 func NewContextKey(name string) ContextKey { 17 return ContextKey{Name: name} 18 } 19 20 var ( 21 historyDBKey = NewContextKey("history_db") 22 requestRegistryKey = NewContextKey("request_registry") 23 timeKey = NewContextKey("time") 24 ) 25 26 // NewContext creates Context with all required fields. 27 func NewContext(ctx context.Context, source TimeSource, registry *RequestsRegistry, storage db.Storage) Context { 28 ctx = context.WithValue(ctx, historyDBKey, db.NewHistoryStore(storage)) 29 ctx = context.WithValue(ctx, timeKey, source) 30 ctx = context.WithValue(ctx, requestRegistryKey, registry) 31 return Context{ctx} 32 } 33 34 // TimeSource is a type used for current time. 35 type TimeSource func() time.Time 36 37 // Context provides access to request-scoped values. 38 type Context struct { 39 context.Context 40 } 41 42 // HistoryStore returns db.HistoryStore instance associated with this request. 43 func (c Context) HistoryStore() db.HistoryStore { 44 return c.Value(historyDBKey).(db.HistoryStore) 45 } 46 47 // Time returns current time using time function associated with this request. 48 func (c Context) Time() time.Time { 49 return c.Value(timeKey).(TimeSource)() 50 } 51 52 // RequestRegistry returns RequestRegistry that tracks each request life-span. 53 func (c Context) RequestRegistry() *RequestsRegistry { 54 return c.Value(requestRegistryKey).(*RequestsRegistry) 55 }