Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/service_spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,19 @@ A test hook must:
* `stage` (string, optional): If executing a stage, for example `beforeEvaluation`, this should be the stage.
- Return data from the stages as specified via the `data` configuration. For instance the return value from the `beforeEvaluation` hook should be `data['beforeEvaluation']` merged with the input data for the stage.

#### Capability `"hook-environment-id"`

This means that the SDK propagates the environment ID reported by LaunchDarkly, in the `X-LD-EnvID` response
header of streaming or polling responses, into the hook series contexts.

If this capability is set, the test harness will send an `X-LD-EnvID` header in its streaming and polling
responses, and the test hook must include the environment ID of the `EvaluationSeriesContext` as the
`environmentId` property of the `evaluationSeriesContext` payload object (and of the `trackSeriesContext`
payload object if the `track-hooks` capability is also supported).

The environment ID is only asserted on the `afterEvaluation` stage, since SDKs which fetch flag data during
evaluation rather than during initialization cannot know it before the evaluation has happened.

#### Capability `"flag-change-listeners"`

This means that the SDK has support for general flag change listeners — listeners that are notified when any flag's configuration changes. When a flag changes, the SDK test service should POST notification data to the callback URI provided during listener registration.
Expand Down
67 changes: 65 additions & 2 deletions sdktests/common_tests_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func doEvaluationSeriesTests(t *ldtest.T) {
executesAfterEvaluationHooksInReverseRegistrationOrder)

t.Run("data propagates from before to after", beforeEvaluationDataPropagatesToAfter)
t.Run("provides the environment ID", evaluationSeriesContextIncludesEnvironmentID)
t.RequireCapability(servicedef.CapabilityMigrations)
t.Run("data propagates from before to after for migrations", beforeEvaluationDataPropagatesToAfterMigration)
}
Expand Down Expand Up @@ -598,6 +599,61 @@ func executesAfterEvaluationHooksInReverseRegistrationOrder(t *ldtest.T) {
"afterEvaluation hooks must execute in the reverse of the order of hook registration")
}

func evaluationSeriesContextIncludesEnvironmentID(t *ldtest.T) {
t.RequireCapability(servicedef.CapabilityHookEnvironmentID)

runTest := func(t *ldtest.T, dataSystemOptions ...SDKDataSystemOption) {
hookName := "evaluationSeriesContextIncludesEnvironmentID"
environmentID := "env-12345"

context := ldcontext.New("user-key")
flagContext := o.Some(context)
configurers := []SDKConfigurer{}

if t.Capabilities().Has(servicedef.CapabilityClientSide) {
configurers = append(configurers, WithClientSideInitialContext(context))
flagContext = o.None[ldcontext.Context]()
}

client, hooks := createClientForHooksWithDataSystemOptions(t, []string{hookName}, nil, nil,
append([]SDKDataSystemOption{DataSystemOptionEnvironmentID(environmentID)}, dataSystemOptions...),
configurers...)
defer hooks.Close()

client.EvaluateFlag(t, servicedef.EvaluateFlagParams{
FlagKey: "bool-flag",
Context: flagContext,
ValueType: servicedef.ValueTypeBool,
DefaultValue: ldvalue.Bool(false),
})

hooks.ExpectCall(t, hookName, func(payload servicedef.HookExecutionPayload) bool {
if payload.Stage.Value() != servicedef.AfterEvaluation {
return false
}
assert.Equal(t, o.Some(environmentID), payload.EvaluationSeriesContext.Value().EnvironmentID)
return true
})
}

t.Run("default data source", func(t *ldtest.T) {
runTest(t)
})

if t.Capabilities().Has(servicedef.CapabilityClientSide) {
// Client-side SDKs use connection modes, so a top-level polling option would be ignored.
t.Run("polling", func(t *ldtest.T) {
runTest(t,
DataSystemOptionConnectionMode("polling", DataSystemOptionPolling()),
DataSystemOptionInitialConnectionMode("polling"))
})
} else if t.Capabilities().Has(servicedef.CapabilityServerSidePolling) {
t.Run("polling", func(t *ldtest.T) {
runTest(t, DataSystemOptionPolling())
})
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

func createClientForHooks(t *ldtest.T, instances []string,
hookData map[servicedef.HookStage]servicedef.SDKConfigEvaluationHookData,
configurers ...SDKConfigurer) (*SDKClient, *Hooks) {
Expand All @@ -607,6 +663,13 @@ func createClientForHooks(t *ldtest.T, instances []string,
func createClientForHooksWithErrors(t *ldtest.T, instances []string,
hookData map[servicedef.HookStage]servicedef.SDKConfigEvaluationHookData,
hookErrors map[servicedef.HookStage]o.Maybe[string], configurers ...SDKConfigurer) (*SDKClient, *Hooks) {
return createClientForHooksWithDataSystemOptions(t, instances, hookData, hookErrors, nil, configurers...)
}

func createClientForHooksWithDataSystemOptions(t *ldtest.T, instances []string,
hookData map[servicedef.HookStage]servicedef.SDKConfigEvaluationHookData,
hookErrors map[servicedef.HookStage]o.Maybe[string], dataSystemOptions []SDKDataSystemOption,
configurers ...SDKConfigurer) (*SDKClient, *Hooks) {
boolFlag := ldbuilders.NewFlagBuilder("bool-flag").
Variations(ldvalue.Bool(false), ldvalue.Bool(true)).
FallthroughVariation(1).On(true).Build()
Expand Down Expand Up @@ -643,11 +706,11 @@ func createClientForHooksWithErrors(t *ldtest.T, instances []string,
for _, flag := range flags {
dataBuilder.Flag(flag.Key, mockld.ClientSDKFlag{Value: flag.Variations[1]})
}
dataSystem = NewSDKDataSystem(t, dataBuilder.Build())
dataSystem = NewSDKDataSystem(t, dataBuilder.Build(), dataSystemOptions...)
} else {
dataBuilder := mockld.NewServerSDKDataBuilder()
dataBuilder.Flag(flags...)
dataSystem = NewSDKDataSystem(t, dataBuilder.Build())
dataSystem = NewSDKDataSystem(t, dataBuilder.Build(), dataSystemOptions...)
}

hooks := NewHooks(requireContext(t).harness, t.DebugLogger(), instances, hookData, hookErrors)
Expand Down
2 changes: 2 additions & 0 deletions sdktests/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ const (
allAllowedTagChars = "._-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
tagNameAppID = "application-id"
tagNameAppVersion = "application-version"

environmentIDHeader = "X-LD-EnvID"
)
43 changes: 37 additions & 6 deletions sdktests/testapi_sdk_data_system.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type sdkDataSystemConfig struct {
pollingSynchronizerOpts []DataSynchronizerOption
connectionModes []connectionModeEntry
initialConnectionMode string
environmentID o.Maybe[string]
}

// SDKDataSystemOption is the interface for options to NewSDKDataSystem.
Expand Down Expand Up @@ -64,6 +65,16 @@ func DataSystemOptionPollInterval(interval time.Duration) SDKDataSystemOption {
})
}

// DataSystemOptionEnvironmentID makes every mock service of the data system report an environment
// ID in the X-LD-EnvID response header, as LaunchDarkly does. It must be specified at the top level;
// it applies to all connection modes.
func DataSystemOptionEnvironmentID(environmentID string) SDKDataSystemOption {
return helpers.ConfigOptionFunc[sdkDataSystemConfig](func(c *sdkDataSystemConfig) error {
c.environmentID = o.Some(environmentID)
return nil
})
}

// DataSystemOptionConnectionMode defines a named connection mode with its own set of
// initializers and synchronizers. The inner options (e.g. DataSystemOptionPolling,
// DataSystemOptionStreaming) control what mock services the mode contains. If no inner
Expand Down Expand Up @@ -98,6 +109,7 @@ type SDKDataSystem struct {
Synchronizers []DataSynchronizer
connectionModes map[string]*dataSystemMode
initialConnectionMode string
environmentID o.Maybe[string]
}

// ConnectionMode returns the named connection mode, or nil if it doesn't exist.
Expand Down Expand Up @@ -350,10 +362,10 @@ func NewSDKDataSystemCustom(
func (s *SDKDataSystem) CreateEndpoints() {
if len(s.connectionModes) > 0 {
for _, mode := range s.connectionModes {
createEndpoints(s.t, mode.initializers, mode.synchronizers)
createEndpoints(s.t, mode.initializers, mode.synchronizers, s.environmentID)
}
} else {
createEndpoints(s.t, s.Initializers, s.Synchronizers)
createEndpoints(s.t, s.Initializers, s.Synchronizers, s.environmentID)
}
}

Expand Down Expand Up @@ -408,7 +420,7 @@ func buildDataSystem(t *ldtest.T, data mockld.SDKData, options []SDKDataSystemOp
var config sdkDataSystemConfig
_ = helpers.ApplyOptions(&config, options...)

d := &SDKDataSystem{t: t}
d := &SDKDataSystem{t: t, environmentID: config.environmentID}

if len(config.connectionModes) > 0 {
d.connectionModes = make(map[string]*dataSystemMode)
Expand Down Expand Up @@ -452,14 +464,20 @@ func buildDataSystem(t *ldtest.T, data mockld.SDKData, options []SDKDataSystemOp
return d
}

func createEndpoints(t *ldtest.T, initializers []DataInitializer, synchronizers []DataSynchronizer) {
func createEndpoints(
t *ldtest.T,
initializers []DataInitializer,
synchronizers []DataSynchronizer,
environmentID o.Maybe[string],
) {
for i := range initializers {
init := &initializers[i]
if init.pollingService == nil {
continue
}
init.endpoint =
requireContext(t).harness.NewMockEndpoint(init.pollingService, t.DebugLogger(),
requireContext(t).harness.NewMockEndpoint(
withEnvironmentIDHeader(init.pollingService, environmentID), t.DebugLogger(),
harness.MockEndpointDescription("polling initializer"))
t.Defer(init.endpoint.Close)
}
Expand All @@ -468,12 +486,25 @@ func createEndpoints(t *ldtest.T, initializers []DataInitializer, synchronizers
sync := &synchronizers[i]
isPolling := sync.polling != nil
handler := helpers.IfElse[http.Handler](isPolling, sync.polling, sync.streaming)
sync.endpoint = requireContext(t).harness.NewMockEndpoint(handler, t.DebugLogger(),
sync.endpoint = requireContext(t).harness.NewMockEndpoint(
withEnvironmentIDHeader(handler, environmentID), t.DebugLogger(),
harness.MockEndpointDescription("synchronizer service"))
t.Defer(sync.endpoint.Close)
}
}

// withEnvironmentIDHeader wraps a handler so that its responses carry the X-LD-EnvID header.
// If no environment ID is defined, the handler is returned unchanged.
func withEnvironmentIDHeader(handler http.Handler, environmentID o.Maybe[string]) http.Handler {
if !environmentID.IsDefined() {
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(environmentIDHeader, environmentID.Value())
handler.ServeHTTP(w, r)
})
}

func setDataOnServices(initializers []DataInitializer, synchronizers []DataSynchronizer, data mockld.SDKData) {
for _, init := range initializers {
if init.pollingService != nil {
Expand Down
1 change: 1 addition & 0 deletions servicedef/service_params.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const (
CapabilityFlagChangeListeners = "flag-change-listeners"
CapabilityFlagValueChangeListeners = "flag-value-change-listeners"
CapabilityTrackHooks = "track-hooks"
CapabilityHookEnvironmentID = "hook-environment-id"
CapabilityClientPrereqEvents = "client-prereq-events"
CapabilityPersistentDataStoreRedis = "persistent-data-store-redis"
CapabilityPersistentDataStoreConsul = "persistent-data-store-consul"
Expand Down
Loading