From 5017de454ae678940d5130c4bb58e77469e54a5c Mon Sep 17 00:00:00 2001 From: Mariem Baccari Date: Fri, 28 Aug 2026 13:09:19 +0200 Subject: [PATCH] [raftstore] Rename context methods --- cmds/core-service/main.go | 4 +-- pkg/aux_/pool_participants.go | 2 +- pkg/aux_/store/memstore/dss.go | 2 +- pkg/aux_/store/memstore/dss_test.go | 8 +++--- pkg/aux_/store/memstore/snapshot_test.go | 4 +-- pkg/aux_/store/memstore/store_test.go | 4 +-- pkg/locality/locality.go | 20 +++++++------- pkg/raftstore/consensus/proposal.go | 2 +- pkg/raftstore/store.go | 4 +-- .../memstore/identification_service_area.go | 4 +-- .../identification_service_area_test.go | 16 ++++++------ pkg/rid/store/memstore/snapshot_test.go | 4 +-- pkg/rid/store/memstore/store_test.go | 6 ++--- pkg/rid/store/memstore/subscriptions.go | 10 +++---- pkg/rid/store/memstore/subscriptions_test.go | 24 ++++++++--------- pkg/scd/constraints_handler.go | 2 +- pkg/scd/operational_intents_handler.go | 4 +-- pkg/scd/operations/constraint.go | 2 +- pkg/scd/operations/operational_intents.go | 2 +- pkg/scd/operations/subscription.go | 4 +-- pkg/scd/store/memstore/availability.go | 2 +- pkg/scd/store/memstore/constraints.go | 2 +- pkg/scd/store/memstore/operational_intents.go | 2 +- pkg/scd/store/memstore/store_test.go | 2 +- pkg/scd/store/memstore/subscriptions.go | 2 +- pkg/timestamp/timestamp.go | 26 +++++++++---------- 26 files changed, 82 insertions(+), 82 deletions(-) diff --git a/cmds/core-service/main.go b/cmds/core-service/main.go index 6b4026fda..91ee224b1 100644 --- a/cmds/core-service/main.go +++ b/cmds/core-service/main.go @@ -368,9 +368,9 @@ func RunHTTPServer(ctx context.Context, ctxCanceler func(), address, locality st handler = authorizer.TokenMiddleware(handler) handler = http.TimeoutHandler(handler, *timeout, "request timeout") handler = logging.HTTPMiddleware(logger, *dumpRequests, handler) - handler = timestamp.RequestTimestampMiddleware(handler) + handler = timestamp.Middleware(handler) handler = random.Middleware(handler) - handler = requestlocality.LocalityMiddleware(locality)(handler) + handler = requestlocality.Middleware(locality)(handler) if *enableMetrics || *enableTracing { // We use the default settings; the APIRouter handler will override the span value accordingly, as it has more information. diff --git a/pkg/aux_/pool_participants.go b/pkg/aux_/pool_participants.go index 8a00c9f1f..dae417936 100644 --- a/pkg/aux_/pool_participants.go +++ b/pkg/aux_/pool_participants.go @@ -96,7 +96,7 @@ func (a *Server) PutDSSInstancesHeartbeat(ctx context.Context, req *restapi.PutD } heartbeat.Timestamp = &ts } else { - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) heartbeat.Timestamp = &now } diff --git a/pkg/aux_/store/memstore/dss.go b/pkg/aux_/store/memstore/dss.go index ef90996f3..359beec9e 100644 --- a/pkg/aux_/store/memstore/dss.go +++ b/pkg/aux_/store/memstore/dss.go @@ -11,7 +11,7 @@ import ( ) func (r *repo) SaveOwnMetadata(ctx context.Context, loc string, publicEndpoint string) error { - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) r.state.Participants[locality(loc)] = &participant{ PublicEndpoint: publicEndpoint, diff --git a/pkg/aux_/store/memstore/dss_test.go b/pkg/aux_/store/memstore/dss_test.go index f39bcb248..4c9a730a4 100644 --- a/pkg/aux_/store/memstore/dss_test.go +++ b/pkg/aux_/store/memstore/dss_test.go @@ -15,7 +15,7 @@ var fakeClock = clockwork.NewFakeClock() func TestSaveOwnMetadataRoundTrip(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) r := newRepo() require.NoError(t, r.SaveOwnMetadata(ctx, "dss-1", "https://example.com")) @@ -35,7 +35,7 @@ func TestSaveOwnMetadataRoundTrip(t *testing.T) { func TestSaveOwnMetadataUpsert(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) r := newRepo() require.NoError(t, r.SaveOwnMetadata(ctx, "dss-1", "https://old.example.com")) @@ -50,7 +50,7 @@ func TestSaveOwnMetadataUpsert(t *testing.T) { func TestGetDSSMetadataPicksLatestHeartbeat(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) r := newRepo() require.NoError(t, r.SaveOwnMetadata(ctx, "dss-1", "https://example.com")) @@ -71,7 +71,7 @@ func TestGetDSSMetadataPicksLatestHeartbeat(t *testing.T) { func TestGetDSSMetadataUpdatesHeartbeatPerSource(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) r := newRepo() require.NoError(t, r.SaveOwnMetadata(ctx, "dss-1", "https://example.com")) diff --git a/pkg/aux_/store/memstore/snapshot_test.go b/pkg/aux_/store/memstore/snapshot_test.go index cd2f03a9f..1ff9015b4 100644 --- a/pkg/aux_/store/memstore/snapshot_test.go +++ b/pkg/aux_/store/memstore/snapshot_test.go @@ -17,7 +17,7 @@ import ( func TestSnapshotRoundTrip(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) src := newRepo() require.NoError(t, src.SaveOwnMetadata(ctx, "dss-1", "https://example.com")) ts := time.Now().UTC() @@ -40,7 +40,7 @@ func TestSnapshotRoundTrip(t *testing.T) { func TestRestoreFromSnapshotReplacesState(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) src := newRepo() require.NoError(t, src.SaveOwnMetadata(ctx, "dss-1", "https://example.com")) data, err := src.GetSnapshot() diff --git a/pkg/aux_/store/memstore/store_test.go b/pkg/aux_/store/memstore/store_test.go index 1526efb04..70376edb3 100644 --- a/pkg/aux_/store/memstore/store_test.go +++ b/pkg/aux_/store/memstore/store_test.go @@ -10,7 +10,7 @@ import ( func TestCheckpointRestore(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) r := newRepo() @@ -34,7 +34,7 @@ func TestCheckpointRestore(t *testing.T) { func TestCheckpointIsolatesUpsert(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) r := newRepo() require.NoError(t, r.SaveOwnMetadata(ctx, "dss-1", "https://old.example.com")) diff --git a/pkg/locality/locality.go b/pkg/locality/locality.go index 8ea51faa8..6e1454c85 100644 --- a/pkg/locality/locality.go +++ b/pkg/locality/locality.go @@ -7,12 +7,12 @@ import ( "github.com/interuss/stacktrace" ) -type localityKey struct{} +type key struct{} -// MustGetRequestLocality returns the request locality from the context and panics if it is not +// MustFromContext returns the request locality from the context and panics if it is not // present, which is a programming error. -func MustGetRequestLocality(ctx context.Context) string { - locality, ok := ctx.Value(localityKey{}).(string) +func MustFromContext(ctx context.Context) string { + locality, ok := ctx.Value(key{}).(string) if !ok { panic(stacktrace.NewError("request locality not present in context")) } @@ -20,17 +20,17 @@ func MustGetRequestLocality(ctx context.Context) string { return locality } -// WithRequestLocality returns a new context with the given locality. -func WithRequestLocality(ctx context.Context, locality string) context.Context { - return context.WithValue(ctx, localityKey{}, locality) +// NewContext returns a new context with the given locality. +func NewContext(ctx context.Context, locality string) context.Context { + return context.WithValue(ctx, key{}, locality) } -// LocalityMiddleware is an HTTP middleware that stamps each incoming request with this +// Middleware is an HTTP middleware that stamps each incoming request with this // DSS instance's locality so that locality-dependent operations execute deterministically across nodes. -func LocalityMiddleware(locality string) func(http.Handler) http.Handler { +func Middleware(locality string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - next.ServeHTTP(w, r.WithContext(WithRequestLocality(r.Context(), locality))) + next.ServeHTTP(w, r.WithContext(NewContext(r.Context(), locality))) }) } } diff --git a/pkg/raftstore/consensus/proposal.go b/pkg/raftstore/consensus/proposal.go index bb63fda74..332a842e8 100644 --- a/pkg/raftstore/consensus/proposal.go +++ b/pkg/raftstore/consensus/proposal.go @@ -35,7 +35,7 @@ type Proposal struct { } func (c *Consensus) newProposal(ctx context.Context, requestType RequestType, value []byte, readOnly bool) Proposal { - timestamp := timestamp.MustGetRequestTimestamp(ctx) + timestamp := timestamp.MustFromContext(ctx) seed := random.MustFromContext(ctx) return Proposal{ diff --git a/pkg/raftstore/store.go b/pkg/raftstore/store.go index a17c00827..b3c6919aa 100644 --- a/pkg/raftstore/store.go +++ b/pkg/raftstore/store.go @@ -116,8 +116,8 @@ func (s *Store[R]) processCommits(ctx context.Context, commitCh <-chan consensus continue } - proposalCtx := timestamp.WithRequestTimestamp(ctx, commit.Prop.Timestamp) - proposalCtx = locality.WithRequestLocality(proposalCtx, commit.Prop.Locality) + proposalCtx := timestamp.NewContext(ctx, commit.Prop.Timestamp) + proposalCtx = locality.NewContext(proposalCtx, commit.Prop.Locality) proposalCtx = random.NewContext(proposalCtx, commit.Prop.Seed) result, err := s.raftRepo.Apply(proposalCtx, commit.Prop) commit.Done <- consensus.ProposalResult{Result: result, Error: err} diff --git a/pkg/rid/store/memstore/identification_service_area.go b/pkg/rid/store/memstore/identification_service_area.go index bf7bb042b..02976cc69 100644 --- a/pkg/rid/store/memstore/identification_service_area.go +++ b/pkg/rid/store/memstore/identification_service_area.go @@ -61,7 +61,7 @@ func (r *repo) InsertISA(ctx context.Context, isa *ridmodels.IdentificationServi return nil, stacktrace.NewError("ISA with id %s already exists", isa.ID) } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := isaRecordFromModel(isa, now) r.state.ISAs[isa.ID] = rec @@ -77,7 +77,7 @@ func (r *repo) UpdateISA(ctx context.Context, isa *ridmodels.IdentificationServi return nil, nil } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := isaRecordFromModel(isa, now) rec.Owner = prev.Owner // It's not possible to update the owner of an ISA, this ensure it's to changed to a new value. diff --git a/pkg/rid/store/memstore/identification_service_area_test.go b/pkg/rid/store/memstore/identification_service_area_test.go index f6baa8dbf..a9bb4b34f 100644 --- a/pkg/rid/store/memstore/identification_service_area_test.go +++ b/pkg/rid/store/memstore/identification_service_area_test.go @@ -34,7 +34,7 @@ var ( func TestStoreSearchISAs(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) cells := s2.CellUnion{ s2.CellID(17106221850767130624), s2.CellID(17106221885126868992), @@ -137,7 +137,7 @@ func TestStoreSearchISAs(t *testing.T) { func TestBadVersion(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) saOut1, err := repo.InsertISA(ctx, serviceArea) @@ -159,7 +159,7 @@ func TestBadVersion(t *testing.T) { func TestStoreExpiredISA(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) saOut, err := repo.InsertISA(ctx, serviceArea) @@ -194,7 +194,7 @@ func TestStoreExpiredISA(t *testing.T) { func TestStoreDeleteISAs(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) // Insert the ISA. @@ -215,7 +215,7 @@ func TestStoreDeleteISAs(t *testing.T) { func TestStoreISAWithNoGeoData(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) endTime := fakeClock.Now().Add(24 * time.Hour) @@ -230,7 +230,7 @@ func TestStoreISAWithNoGeoData(t *testing.T) { func TestListExpiredISAs(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) // Insert ISA with endtime 1 day from now @@ -261,7 +261,7 @@ func TestListExpiredISAs(t *testing.T) { func TestListExpiredISAsWithEmptyWriter(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) // Insert ISA with endtime 1 day from now @@ -294,7 +294,7 @@ func TestListExpiredISAsWithEmptyWriter(t *testing.T) { func TestStoreCountISAs(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) // Insert the ISA. diff --git a/pkg/rid/store/memstore/snapshot_test.go b/pkg/rid/store/memstore/snapshot_test.go index a795d5f5f..50fc5423d 100644 --- a/pkg/rid/store/memstore/snapshot_test.go +++ b/pkg/rid/store/memstore/snapshot_test.go @@ -15,7 +15,7 @@ import ( func TestSnapshotRoundTrip(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) src := setUpStore(t) _, err := src.InsertISA(ctx, serviceArea) require.NoError(t, err) @@ -49,7 +49,7 @@ func TestSnapshotRoundTrip(t *testing.T) { func TestRestoreFromSnapshotReplacesState(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) src := setUpStore(t) _, err := src.InsertISA(ctx, serviceArea) require.NoError(t, err) diff --git a/pkg/rid/store/memstore/store_test.go b/pkg/rid/store/memstore/store_test.go index 62752a537..55d13081f 100644 --- a/pkg/rid/store/memstore/store_test.go +++ b/pkg/rid/store/memstore/store_test.go @@ -30,7 +30,7 @@ func setUpStore(t *testing.T) *repo { func TestDatabaseEnsuresBeginsBeforeExpires(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) var ( @@ -50,7 +50,7 @@ func TestDatabaseEnsuresBeginsBeforeExpires(t *testing.T) { func TestCheckpointRestoreISA(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) _, err := repo.InsertISA(ctx, serviceArea) @@ -76,7 +76,7 @@ func TestCheckpointRestoreISA(t *testing.T) { func TestCheckpointIsolatesNotificationIndex(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) sub, err := repo.InsertSubscription(ctx, subscriptionsPool[0].input) diff --git a/pkg/rid/store/memstore/subscriptions.go b/pkg/rid/store/memstore/subscriptions.go index 63cb22c09..f5a7bffdb 100644 --- a/pkg/rid/store/memstore/subscriptions.go +++ b/pkg/rid/store/memstore/subscriptions.go @@ -67,7 +67,7 @@ func (r *repo) InsertSubscription(ctx context.Context, s *ridmodels.Subscription return nil, stacktrace.NewError("Subscription with id %s already exists", s.ID) } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := subRecordFromModel(s, now) r.state.Subscriptions[s.ID] = rec @@ -83,7 +83,7 @@ func (r *repo) UpdateSubscription(ctx context.Context, s *ridmodels.Subscription return nil, nil } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := subRecordFromModel(s, now) rec.Owner = prev.Owner // It's not possible to update the owner of a subscription, this ensure it's to changed to a new value. @@ -137,7 +137,7 @@ func (r *repo) searchSubscriptions(ctx context.Context, cells s2.CellUnion, owne return nil, stacktrace.NewErrorWithCode(dsserr.BadRequest, "no location provided") } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) var out []*ridmodels.Subscription for rec := range r.liveSubscriptionsInCells(now, cells, owner) { @@ -154,7 +154,7 @@ func (r *repo) searchSubscriptions(ctx context.Context, cells s2.CellUnion, owne // subscription in the given cells. func (r *repo) UpdateNotificationIdxsInCells(ctx context.Context, cells s2.CellUnion) ([]*ridmodels.Subscription, error) { - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) var out []*ridmodels.Subscription for rec := range r.liveSubscriptionsInCells(now, cells, nil) { @@ -166,7 +166,7 @@ func (r *repo) UpdateNotificationIdxsInCells(ctx context.Context, cells s2.CellU func (r *repo) MaxSubscriptionCountInCellsByOwner(ctx context.Context, cells s2.CellUnion, owner dssmodels.Owner) (int, error) { - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) want := cellSet(cells) counts := make(map[s2.CellID]int, len(cells)) diff --git a/pkg/rid/store/memstore/subscriptions_test.go b/pkg/rid/store/memstore/subscriptions_test.go index 1d61cf707..993aaeff8 100644 --- a/pkg/rid/store/memstore/subscriptions_test.go +++ b/pkg/rid/store/memstore/subscriptions_test.go @@ -70,7 +70,7 @@ var ( func TestStoreGetSubscription(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) for _, r := range subscriptionsPool { @@ -90,7 +90,7 @@ func TestStoreGetSubscription(t *testing.T) { func TestStoreInsertSubscription(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) for _, r := range subscriptionsPool { @@ -134,7 +134,7 @@ func TestStoreInsertSubscription(t *testing.T) { func TestStoreDeleteSubscription(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) for _, r := range subscriptionsPool { @@ -162,7 +162,7 @@ func TestStoreDeleteSubscription(t *testing.T) { func TestStoreSearchSubscription(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now().UTC()) + ctx = timestamp.NewContext(ctx, fakeClock.Now().UTC()) repo := setUpStore(t) var ( @@ -207,7 +207,7 @@ func TestStoreSearchSubscription(t *testing.T) { func TestStoreExpiredSubscription(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) endTime := fakeClock.Now().Add(24 * time.Hour) @@ -221,7 +221,7 @@ func TestStoreExpiredSubscription(t *testing.T) { require.NoError(t, err) // The subscription's endTime is 24 hours from now. - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now().Add(23*time.Hour)) + ctx = timestamp.NewContext(ctx, fakeClock.Now().Add(23*time.Hour)) // We should still be able to find the subscription by searching and by ID. subs, err := repo.SearchSubscriptionsByOwner(ctx, sub.Cells, "original owner") @@ -233,7 +233,7 @@ func TestStoreExpiredSubscription(t *testing.T) { require.NotNil(t, &ret) // But now the subscription has expired. - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now().Add(25*time.Hour)) + ctx = timestamp.NewContext(ctx, fakeClock.Now().Add(25*time.Hour)) subs, err = repo.SearchSubscriptionsByOwner(ctx, sub.Cells, "original owner") require.NoError(t, err) @@ -246,7 +246,7 @@ func TestStoreExpiredSubscription(t *testing.T) { func TestStoreSubscriptionWithNoGeoData(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) endTime := fakeClock.Now().Add(24 * time.Hour) @@ -261,7 +261,7 @@ func TestStoreSubscriptionWithNoGeoData(t *testing.T) { func TestMaxSubscriptionCountInCellsByOwner(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) for _, s := range subscriptionsPool { @@ -276,7 +276,7 @@ func TestMaxSubscriptionCountInCellsByOwner(t *testing.T) { func TestListExpiredSubscriptions(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) fakeClock := clockwork.NewFakeClockAt(time.Now()) @@ -309,7 +309,7 @@ func TestListExpiredSubscriptions(t *testing.T) { func TestListExpiredSubscriptionsWithEmptyWriter(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) // Insert Subscription with endtime 1 day from now @@ -342,7 +342,7 @@ func TestListExpiredSubscriptionsWithEmptyWriter(t *testing.T) { func TestStoreCountSubscription(t *testing.T) { ctx := context.Background() - ctx = timestamp.WithRequestTimestamp(ctx, fakeClock.Now()) + ctx = timestamp.NewContext(ctx, fakeClock.Now()) repo := setUpStore(t) for _, r := range subscriptionsPool { diff --git a/pkg/scd/constraints_handler.go b/pkg/scd/constraints_handler.go index 4151855fa..692a5405c 100644 --- a/pkg/scd/constraints_handler.go +++ b/pkg/scd/constraints_handler.go @@ -168,7 +168,7 @@ func (a *Server) UpdateConstraintReference(ctx context.Context, req *restapi.Upd // validateConstraintUpsertRequest performs the request validation that can be done ahead of the transaction. // Note that this does NOT check for anything related to access controls: any error returned should be labeled as a dsserr.BadRequest. func validateConstraintUpsertRequest(ctx context.Context, entityid restapi.EntityID, params *restapi.PutConstraintReferenceParameters, allowHTTPBaseUrls bool) error { - _, err := operations.ValidateAndReturnConstraintUpsertParams(timestamp.MustGetRequestTimestamp(ctx), entityid, params) + _, err := operations.ValidateAndReturnConstraintUpsertParams(timestamp.MustFromContext(ctx), entityid, params) if err != nil { return err } diff --git a/pkg/scd/operational_intents_handler.go b/pkg/scd/operational_intents_handler.go index eba9ff596..8e00f28f9 100644 --- a/pkg/scd/operational_intents_handler.go +++ b/pkg/scd/operational_intents_handler.go @@ -138,7 +138,7 @@ func (a *Server) CreateOperationalIntentReference(ctx context.Context, req *rest return restapi.CreateOperationalIntentReferenceResponseSet{Response400: &restapi.ErrorResponse{ Message: dsserr.Handle(ctx, stacktrace.PropagateWithCode(req.BodyParseError, dsserr.BadRequest, "Malformed params"))}} } - validParams, err := operations.ValidateAndReturnOIRUpsertParams(timestamp.MustGetRequestTimestamp(ctx), req.Entityid, "", req.Body, a.AllowHTTPBaseUrls) + validParams, err := operations.ValidateAndReturnOIRUpsertParams(timestamp.MustFromContext(ctx), req.Entityid, "", req.Body, a.AllowHTTPBaseUrls) if err != nil { return restapi.CreateOperationalIntentReferenceResponseSet{Response400: &restapi.ErrorResponse{ Message: dsserr.Handle(ctx, stacktrace.PropagateWithCode(err, dsserr.BadRequest, "Failed to validate Operational Intent Reference upsert parameters"))}} @@ -181,7 +181,7 @@ func (a *Server) UpdateOperationalIntentReference(ctx context.Context, req *rest return restapi.UpdateOperationalIntentReferenceResponseSet{Response400: &restapi.ErrorResponse{ Message: dsserr.Handle(ctx, stacktrace.PropagateWithCode(req.BodyParseError, dsserr.BadRequest, "Malformed params"))}} } - validParams, err := operations.ValidateAndReturnOIRUpsertParams(timestamp.MustGetRequestTimestamp(ctx), req.Entityid, req.Ovn, req.Body, a.AllowHTTPBaseUrls) + validParams, err := operations.ValidateAndReturnOIRUpsertParams(timestamp.MustFromContext(ctx), req.Entityid, req.Ovn, req.Body, a.AllowHTTPBaseUrls) if err != nil { return restapi.UpdateOperationalIntentReferenceResponseSet{Response400: &restapi.ErrorResponse{ Message: dsserr.Handle(ctx, stacktrace.PropagateWithCode(err, dsserr.BadRequest, "Failed to validate Operational Intent Reference upsert parameters"))}} diff --git a/pkg/scd/operations/constraint.go b/pkg/scd/operations/constraint.go index e1c2202ac..7b32dd7f5 100644 --- a/pkg/scd/operations/constraint.go +++ b/pkg/scd/operations/constraint.go @@ -94,7 +94,7 @@ func executePutConstraint(ctx context.Context, repo repos.Repository, request ds return nil, stacktrace.NewError("unexpected request type %T for operation %q", request, restapi.CreateConstraintReferenceOperationID) } - validParams, err := ValidateAndReturnConstraintUpsertParams(timestamp.MustGetRequestTimestamp(ctx), entityid, params) + validParams, err := ValidateAndReturnConstraintUpsertParams(timestamp.MustFromContext(ctx), entityid, params) if err != nil { return nil, stacktrace.PropagateWithCode(err, dsserr.BadRequest, "Failed to validate Constraint upsert parameters") } diff --git a/pkg/scd/operations/operational_intents.go b/pkg/scd/operations/operational_intents.go index f655b4868..76216c814 100644 --- a/pkg/scd/operations/operational_intents.go +++ b/pkg/scd/operations/operational_intents.go @@ -663,7 +663,7 @@ func executePutOperationalIntentReference(ctx context.Context, repo repos.Reposi return nil, stacktrace.NewError("unexpected request type %T for operation %q", request, restapi.CreateOperationalIntentReferenceOperationID) } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) // Base URL scheme validation is a pre-flight, request-only check performed by the handler // before this action is proposed for consensus; skip it here (allowHTTPBaseUrls: true). diff --git a/pkg/scd/operations/subscription.go b/pkg/scd/operations/subscription.go index 01585719a..a4cb4c989 100644 --- a/pkg/scd/operations/subscription.go +++ b/pkg/scd/operations/subscription.go @@ -119,7 +119,7 @@ func executePutSubscription(ctx context.Context, repo repos.Repository, request } // Validate and perhaps correct StartTime and EndTime. - if err := subreq.AdjustTimeRange(timestamp.MustGetRequestTimestamp(ctx), old); err != nil { + if err := subreq.AdjustTimeRange(timestamp.MustFromContext(ctx), old); err != nil { return nil, stacktrace.Propagate(err, "Error adjusting time range of Subscription") } @@ -373,7 +373,7 @@ func executeQuerySubscriptions(ctx context.Context, repo repos.Repository, reque return nil, stacktrace.Propagate(err, "Error searching Subscriptions in repo") } - nowMarker := timestamp.MustGetRequestTimestamp(ctx) + nowMarker := timestamp.MustFromContext(ctx) // Return response to client response := &restapi.QuerySubscriptionsResponse{ diff --git a/pkg/scd/store/memstore/availability.go b/pkg/scd/store/memstore/availability.go index bb750996a..8fe0dc839 100644 --- a/pkg/scd/store/memstore/availability.go +++ b/pkg/scd/store/memstore/availability.go @@ -26,7 +26,7 @@ func (r *repo) GetUssAvailability(_ context.Context, id dssmodels.Manager) (*scd } func (r *repo) UpsertUssAvailability(ctx context.Context, s *scdmodels.UssAvailabilityStatus) (*scdmodels.UssAvailabilityStatus, error) { - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := &availabilityRecord{ Uss: s.Uss, diff --git a/pkg/scd/store/memstore/constraints.go b/pkg/scd/store/memstore/constraints.go index 6fb54f143..33c9a0b6a 100644 --- a/pkg/scd/store/memstore/constraints.go +++ b/pkg/scd/store/memstore/constraints.go @@ -67,7 +67,7 @@ func (r *repo) UpsertConstraint(ctx context.Context, s *scdmodels.Constraint) (* return nil, stacktrace.Propagate(err, "Failed to convert array to jackc/pgtype") } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := &constraintRecord{ ID: s.ID, diff --git a/pkg/scd/store/memstore/operational_intents.go b/pkg/scd/store/memstore/operational_intents.go index fad0deec2..0abbab93f 100644 --- a/pkg/scd/store/memstore/operational_intents.go +++ b/pkg/scd/store/memstore/operational_intents.go @@ -98,7 +98,7 @@ func (r *repo) UpsertOperationalIntent(ctx context.Context, operation *scdmodels ussRequestedOVN = operation.OVN.String() } - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := &operationalIntentRecord{ ID: operation.ID, diff --git a/pkg/scd/store/memstore/store_test.go b/pkg/scd/store/memstore/store_test.go index 7f43bdf8c..caecd5bc6 100644 --- a/pkg/scd/store/memstore/store_test.go +++ b/pkg/scd/store/memstore/store_test.go @@ -40,7 +40,7 @@ func setUpStore(t *testing.T) *repo { // writeCtx returns a context carrying a deterministic write timestamp so that // updated_at is controlled in tests. func writeCtx() context.Context { - return timestamp.WithRequestTimestamp(context.Background(), writeTime) + return timestamp.NewContext(context.Background(), writeTime) } func sampleConstraint() *scdmodels.Constraint { diff --git a/pkg/scd/store/memstore/subscriptions.go b/pkg/scd/store/memstore/subscriptions.go index 02f233698..850d06125 100644 --- a/pkg/scd/store/memstore/subscriptions.go +++ b/pkg/scd/store/memstore/subscriptions.go @@ -78,7 +78,7 @@ func (r *repo) GetSubscription(_ context.Context, id dssmodels.ID) (*scdmodels.S } func (r *repo) UpsertSubscription(ctx context.Context, s *scdmodels.Subscription) (*scdmodels.Subscription, error) { - now := timestamp.MustGetRequestTimestamp(ctx) + now := timestamp.MustFromContext(ctx) rec := &subscriptionRecord{ ID: s.ID, diff --git a/pkg/timestamp/timestamp.go b/pkg/timestamp/timestamp.go index 28dbe9451..fe1329d46 100644 --- a/pkg/timestamp/timestamp.go +++ b/pkg/timestamp/timestamp.go @@ -8,13 +8,13 @@ import ( "github.com/interuss/stacktrace" ) -type timestampKey struct{} +type key struct{} -// requestTimestampFromContext returns the request timestamp from the context, or an error if the value is not present or if it is zero. +// fromContext returns the request timestamp from the context, or an error if the value is not present or if it is zero. // The timestamp is set by the Middleware when a query is received then (on the receiver side) by the Raftstore when the query is applied. // It is then used for deterministic execution of time-dependent queries. -func requestTimestampFromContext(ctx context.Context) (time.Time, error) { - timestamp, ok := ctx.Value(timestampKey{}).(time.Time) +func fromContext(ctx context.Context) (time.Time, error) { + timestamp, ok := ctx.Value(key{}).(time.Time) if !ok { return time.Time{}, stacktrace.NewError("timestamp not found in context") } @@ -26,10 +26,10 @@ func requestTimestampFromContext(ctx context.Context) (time.Time, error) { return timestamp, nil } -// MustGetRequestTimestamp returns the request timestamp from the context and panics if it is not +// MustFromContext returns the request timestamp from the context and panics if it is not // present or invalid, which is a programming error. -func MustGetRequestTimestamp(ctx context.Context) time.Time { - timestamp, err := requestTimestampFromContext(ctx) +func MustFromContext(ctx context.Context) time.Time { + timestamp, err := fromContext(ctx) if err != nil { panic(err) } @@ -37,18 +37,18 @@ func MustGetRequestTimestamp(ctx context.Context) time.Time { return timestamp } -// WithRequestTimestamp returns a new context with the given timestamp. -func WithRequestTimestamp(ctx context.Context, timestamp time.Time) context.Context { - return context.WithValue(ctx, timestampKey{}, timestamp) +// NewContext returns a new context with the given timestamp. +func NewContext(ctx context.Context, timestamp time.Time) context.Context { + return context.WithValue(ctx, key{}, timestamp) } -// RequestTimestampMiddleware is an HTTP middleware that stamps each incoming +// Middleware is an HTTP middleware that stamps each incoming // request with its received time. This timestamp is later used as the // timestamp of the Raft proposal, so that time-dependent queries // execute deterministically across nodes and contexts (catchup / restart etc.). -func RequestTimestampMiddleware(next http.Handler) http.Handler { +func Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := WithRequestTimestamp(r.Context(), time.Now()) + ctx := NewContext(r.Context(), time.Now()) next.ServeHTTP(w, r.WithContext(ctx)) }) }