diff --git a/internal/datasourcev2/helpers.go b/internal/datasourcev2/helpers.go index d7442420..cfdaaf64 100644 --- a/internal/datasourcev2/helpers.go +++ b/internal/datasourcev2/helpers.go @@ -32,8 +32,8 @@ func (e httpStatusError) Error() string { return e.Message } -// Tests whether an HTTP error status represents a condition that might resolve on its own if we retry, -// or at least should not make us permanently stop sending requests. +// Tests whether an HTTP error status represents a condition that might resolve on its own if we +// retry, or one that should stop this synchronizer until the data system restarts it. func isHTTPErrorRecoverable(statusCode int) bool { if statusCode >= 400 && statusCode < 500 { switch statusCode { @@ -67,7 +67,7 @@ func checkIfErrorIsRecoverableAndLog( recoverableMessage string, ) bool { if statusCode > 0 && !isHTTPErrorRecoverable(statusCode) { - loggers.Errorf("Error %s (giving up permanently): %s", errorContext, errorDesc) + loggers.Errorf("Error %s (will not retry until restarted): %s", errorContext, errorDesc) return false } loggers.Warnf("Error %s (%s): %s", errorContext, recoverableMessage, errorDesc) diff --git a/internal/datasourcev2/polling_data_source.go b/internal/datasourcev2/polling_data_source.go index 11488df4..ff62e4d1 100644 --- a/internal/datasourcev2/polling_data_source.go +++ b/internal/datasourcev2/polling_data_source.go @@ -16,6 +16,9 @@ import ( const ( pollingErrorContext = "on polling request" pollingWillRetryMessage = "will retry at next scheduled poll interval" + + // Consecutive successful polls required to report ResetThresholdMet. + pollResetThreshold = 2 ) // PollingRequester allows PollingProcessor to delegate fetching data to another component. @@ -112,6 +115,7 @@ func (pp *PollingProcessor) Sync(ds subsystems.DataSelector) <-chan subsystems.D return false } } + consecutiveSuccesses := 0 for { select { @@ -121,8 +125,17 @@ func (pp *PollingProcessor) Sync(ds subsystems.DataSelector) <-chan subsystems.D case <-ticker.C: result, err := pp.poll(ctx, ds) + if err == nil { + consecutiveSuccesses++ + if consecutiveSuccesses == pollResetThreshold { + result.ResetThresholdMet = true + } + } else { + consecutiveSuccesses = 0 + } + // When the server requested FDv1 fallback, dispatch the result as-is -- poll has - // already populated State (Valid on success, Off on error) and FallbackToFDv1=true. + // already populated State (Valid on success, Interrupted on error) and FallbackToFDv1=true. if result.FallbackToFDv1 { send(result) return @@ -135,8 +148,8 @@ func (pp *PollingProcessor) Sync(ds subsystems.DataSelector) <-chan subsystems.D continue } - // Non-fallback error: the caller may downgrade Off --> Interrupted when the error - // is recoverable. Log at the appropriate level. + // Non-fallback error: mark it an unexpected failure when it is not recoverable. + // Log at the appropriate level. if hse, ok := err.(httpStatusError); ok { if checkIfErrorIsRecoverableAndLog( pp.loggers, @@ -151,6 +164,7 @@ func (pp *PollingProcessor) Sync(ds subsystems.DataSelector) <-chan subsystems.D } continue } + result.UnexpectedFailure = true send(result) // poll set State=Off return } @@ -173,9 +187,9 @@ func (pp *PollingProcessor) Sync(ds subsystems.DataSelector) <-chan subsystems.D // the fallback signal. // // On success: result.State = Valid, result.ChangeSet populated, err = nil. -// On error: result.State = Off (the safer default), result.Error populated with Kind/Message/ -// StatusCode as appropriate, err returned so the caller can apply context-specific logic -// (e.g. downgrade Off --> Interrupted when the HTTP error is recoverable). +// On error: result.State = Interrupted, result.Error populated with Kind/Message/StatusCode as +// appropriate, err returned so the caller can apply context-specific logic (e.g. mark the result +// an unexpected failure when the HTTP error is not recoverable). // // The caller is responsible for publishing the result to its channel; poll does not touch any // resultChan so it can be unit-tested in isolation. @@ -194,7 +208,7 @@ func (pp *PollingProcessor) poll( return result, nil } - result.State = interfaces.DataSourceStateOff + result.State = interfaces.DataSourceStateInterrupted if hse, ok := err.(httpStatusError); ok { result.Error = interfaces.DataSourceErrorInfo{ Kind: interfaces.DataSourceErrorKindErrorResponse, diff --git a/internal/datasourcev2/polling_data_source_test.go b/internal/datasourcev2/polling_data_source_test.go index 18715889..4677b87a 100644 --- a/internal/datasourcev2/polling_data_source_test.go +++ b/internal/datasourcev2/polling_data_source_test.go @@ -217,6 +217,32 @@ func TestPollingProcessorSynchronizerCanMakeSuccessfulRequest(t *testing.T) { }) } +// The polling reset threshold is two consecutive successful polls, and any failure restarts it. +func TestPollingProcessorSynchronizerSignalsResetAfterTwoSuccessfulPolls(t *testing.T) { + ds := mocks.NewMockDataSelector(subsystems.NoSelector()) + data := ldservicesv2.NewServerSDKData().Flags(alwaysTrueFlag).ToInitializerPayload(subsystems.NoSelector()) + ok := ldservices.ServerSidePollingV2ServiceHandler(data) + + handler := httphelpers.SequentialHandler(ok, ok, httphelpers.HandlerWithStatus(500), ok, ok) + httphelpers.WithServer(handler, func(ts *httptest.Server) { + processor := NewPollingProcessor( + sharedtest.BasicClientContext(), + datasource.PollingConfig{ + BaseURI: ts.URL, + PollInterval: time.Millisecond * 10, + }, + ) + defer processor.Close() + + resultChan := processor.Sync(ds) + + for i, want := range []bool{false, true, false, false, true} { + result := <-resultChan + assert.Equal(t, want, result.ResetThresholdMet, "poll %d", i+1) + } + }) +} + func TestPollingProcessorSynchronizerHandlesInvalidJSON(t *testing.T) { ds := mocks.NewMockDataSelector(subsystems.NoSelector()) @@ -294,9 +320,10 @@ func TestPollingProcessorSynchronizerHandlesFallbackOnMalformedBody(t *testing.T resultChan := processor.Sync(ds) result := <-resultChan - assert.Equal(t, interfaces.DataSourceStateOff, result.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, result.State) assert.Equal(t, interfaces.DataSourceErrorKindInvalidData, result.Error.Kind) assert.True(t, result.FallbackToFDv1) + assert.False(t, result.UnexpectedFailure, "a malformed body is recoverable") }) } @@ -320,7 +347,7 @@ func TestPollingProcessorSynchronizerHandlesFallbackToFDv2(t *testing.T) { resultChan := processor.Sync(ds) result := <-resultChan - assert.Equal(t, result.State, interfaces.DataSourceStateOff) + assert.Equal(t, result.State, interfaces.DataSourceStateInterrupted) assert.Equal(t, result.Error.Kind, interfaces.DataSourceErrorKindErrorResponse) assert.True(t, result.FallbackToFDv1) }) @@ -461,7 +488,8 @@ func TestPollingProcessorSynchronizerHandlesUnrecoverableErrors(t *testing.T) { <-requestsCh result := <-resultChan - assert.Equal(t, interfaces.DataSourceStateOff, result.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, result.State) + assert.True(t, result.UnexpectedFailure) _ = func(errorInfo interfaces.DataSourceErrorInfo) { assert.Equal(t, interfaces.DataSourceErrorKindErrorResponse, errorInfo.Kind) assert.Equal(t, statusCode, errorInfo.StatusCode) diff --git a/internal/datasourcev2/streaming_data_source.go b/internal/datasourcev2/streaming_data_source.go index a448ad6d..45b237d3 100644 --- a/internal/datasourcev2/streaming_data_source.go +++ b/internal/datasourcev2/streaming_data_source.go @@ -52,10 +52,11 @@ const ( // 2b. If the data store doesn't support status notifications (which is normally only true of the in-memory store) // then we don't know the significance of the error, but we must assume that updates have been lost, so we'll // restart the stream. -// 3. If we receive an unrecoverable error like HTTP 401, we close the stream and don't retry, and set the state -// to OFF. Any other HTTP error or network error causes a retry with backoff, with a state of INTERRUPTED. +// 3. If we receive an unexpected error like HTTP 401, we close the stream and stop retrying, reporting +// INTERRUPTED with UnexpectedFailure set. Any other HTTP error or network error causes a retry with +// backoff, with a state of INTERRUPTED. // 4. We set the Future returned by start() to tell the client initialization logic that initialization has either -// succeeded (we got an initial payload and successfully stored it) or permanently failed (we got a 401, etc.). +// succeeded (we got an initial payload and successfully stored it) or stopped retrying (we got a 401, etc.). // Otherwise, the client initialization method may time out but we will still be retrying in the background, and // if we succeed then the client can detect that we're initialized now by calling our Initialized method. @@ -71,10 +72,12 @@ type StreamProcessor struct { diagnosticsManager *ldevents.DiagnosticsManager deserializeOptions datakinds.DeserializeOptions loggers ldlog.Loggers - connectionAttemptStartTime ldtime.UnixMillisecondTime + connectionAttemptStartTime ldtime.UnixMillisecondTime // guarded by connectionAttemptLock connectionAttemptLock sync.Mutex isClosed atomic.Bool halt chan struct{} + healthySince time.Time // guarded by connectionAttemptLock + resetInterval time.Duration } // NewStreamProcessor creates the internal implementation of the streaming data source. @@ -83,10 +86,11 @@ func NewStreamProcessor( cfg datasource.StreamConfig, ) *StreamProcessor { sp := &StreamProcessor{ - headers: context.GetHTTP().DefaultHeaders, - loggers: context.GetLogging().Loggers, - halt: make(chan struct{}), - cfg: cfg, + headers: context.GetHTTP().DefaultHeaders, + loggers: context.GetLogging().Loggers, + halt: make(chan struct{}), + cfg: cfg, + resetInterval: streamRetryResetInterval, } if cci, ok := context.(*internal.ClientContextImpl); ok { sp.diagnosticsManager = cci.DiagnosticsManager @@ -161,6 +165,7 @@ func (sp *StreamProcessor) reportMalformedEvent( } } +//nolint:gocyclo // TODO: refactor to make this function simpler. func (sp *StreamProcessor) consumeStream(stream *es.Stream, resultChan chan<- subsystems.DataSynchronizerResult) { // Consume remaining Events and Errors so we can garbage collect defer func() { @@ -179,6 +184,9 @@ func (sp *StreamProcessor) consumeStream(stream *es.Stream, resultChan chan<- su // can serve the server-provided data while FDv1 takes over. fallbackRequested := false + // Fires when healthy operation has lasted the reset interval. + var resetThreshold <-chan time.Time + for { select { case event, ok := <-stream.Events: @@ -208,6 +216,7 @@ func (sp *StreamProcessor) consumeStream(stream *es.Stream, resultChan chan<- su gotMalformedEvent := func(event es.Event, err error) { // The protocol should "forget" anything that happens upon receiving an error. changeSetBuilder = subsystems.NewChangeSetBuilder().WithDeserializeOptions(sp.deserializeOptions) + sp.noteUnhealthy() sp.reportMalformedEvent(event, err, environmentID, resultChan) shouldRestart = true // scenario 1 in error handling comments at top of file } @@ -234,6 +243,9 @@ func (sp *StreamProcessor) consumeStream(stream *es.Stream, resultChan chan<- su break } + if sp.noteHealthy() { + resetThreshold = time.After(sp.resetInterval) + } resultChan <- subsystems.DataSynchronizerResult{ State: interfaces.DataSourceStateValid, EnvironmentID: environmentID, @@ -301,6 +313,9 @@ func (sp *StreamProcessor) consumeStream(stream *es.Stream, resultChan chan<- su break } + if sp.noteHealthy() { + resetThreshold = time.After(sp.resetInterval) + } resultChan <- subsystems.DataSynchronizerResult{ ChangeSet: changeSet, State: interfaces.DataSourceStateValid, @@ -326,6 +341,15 @@ func (sp *StreamProcessor) consumeStream(stream *es.Stream, resultChan chan<- su return } + case <-resetThreshold: + if sp.healthyLongEnough() { + resultChan <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateValid, + EnvironmentID: environmentID, + ResetThresholdMet: true, + } + } + case <-sp.halt: stream.Close() return @@ -342,12 +366,13 @@ func (sp *StreamProcessor) subscribe(ds subsystems.DataSelector, resultChan chan reqErr, ) resultChan <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, + State: interfaces.DataSourceStateInterrupted, Error: interfaces.DataSourceErrorInfo{ Kind: interfaces.DataSourceErrorKindUnknown, Message: reqErr.Error(), Time: time.Now(), }, + UnexpectedFailure: true, } close(resultChan) sp.logConnectionResult(false) @@ -386,7 +411,7 @@ func (sp *StreamProcessor) subscribe(ds subsystems.DataSelector, resultChan chan if isFDv1FallbackRequested(se.Header) { resultChan <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, + State: interfaces.DataSourceStateInterrupted, Error: errorInfo, FallbackToFDv1: true, EnvironmentID: environmentID, @@ -411,9 +436,10 @@ func (sp *StreamProcessor) subscribe(ds subsystems.DataSelector, resultChan chan return es.StreamErrorHandlerResult{CloseNow: false} } resultChan <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, - Error: errorInfo, - EnvironmentID: environmentID, + State: interfaces.DataSourceStateInterrupted, + Error: errorInfo, + EnvironmentID: environmentID, + UnexpectedFailure: true, } return es.StreamErrorHandlerResult{CloseNow: true} } @@ -460,12 +486,13 @@ func (sp *StreamProcessor) subscribe(ds subsystems.DataSelector, resultChan chan sp.logConnectionResult(false) resultChan <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, + State: interfaces.DataSourceStateInterrupted, Error: interfaces.DataSourceErrorInfo{ Kind: interfaces.DataSourceErrorKindUnknown, Message: err.Error(), Time: time.Now(), }, + UnexpectedFailure: true, } close(resultChan) @@ -475,10 +502,36 @@ func (sp *StreamProcessor) subscribe(ds subsystems.DataSelector, resultChan chan sp.consumeStream(stream, resultChan) } +// noteHealthy records healthy operation, and reports whether this call began the period. +func (sp *StreamProcessor) noteHealthy() bool { + sp.connectionAttemptLock.Lock() + defer sp.connectionAttemptLock.Unlock() + if !sp.healthySince.IsZero() { + return false + } + sp.healthySince = time.Now() + return true +} + +// healthyLongEnough reports whether healthy operation has lasted the reset interval. +func (sp *StreamProcessor) healthyLongEnough() bool { + sp.connectionAttemptLock.Lock() + defer sp.connectionAttemptLock.Unlock() + return !sp.healthySince.IsZero() && time.Since(sp.healthySince) >= sp.resetInterval +} + +// noteUnhealthy ends the healthy period. +func (sp *StreamProcessor) noteUnhealthy() { + sp.connectionAttemptLock.Lock() + defer sp.connectionAttemptLock.Unlock() + sp.healthySince = time.Time{} +} + func (sp *StreamProcessor) logConnectionStarted() { sp.connectionAttemptLock.Lock() defer sp.connectionAttemptLock.Unlock() sp.connectionAttemptStartTime = ldtime.UnixMillisNow() + sp.healthySince = time.Time{} } func (sp *StreamProcessor) logConnectionResult(success bool) { diff --git a/internal/datasourcev2/streaming_data_source_test.go b/internal/datasourcev2/streaming_data_source_test.go index d9c0e41d..8633224c 100644 --- a/internal/datasourcev2/streaming_data_source_test.go +++ b/internal/datasourcev2/streaming_data_source_test.go @@ -27,6 +27,7 @@ import ( th "github.com/launchdarkly/go-test-helpers/v3" "github.com/launchdarkly/go-test-helpers/v3/httphelpers" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -81,7 +82,8 @@ func TestMalformedStreamBaseURI(t *testing.T) { resultChan := sp.Sync(ds) result := <-resultChan - assert.Equal(t, interfaces.DataSourceStateOff, result.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, result.State) + assert.True(t, result.UnexpectedFailure) assert.Equal(t, interfaces.DataSourceErrorKindUnknown, result.Error.Kind) } @@ -180,9 +182,10 @@ func TestStreamingProcessorHandlesFallbackToFDv1(t *testing.T) { resultChan := sp.Sync(ds) result := <-resultChan - assert.Equal(t, result.State, interfaces.DataSourceStateOff) + assert.Equal(t, result.State, interfaces.DataSourceStateInterrupted) assert.Equal(t, result.Error.Kind, interfaces.DataSourceErrorKindErrorResponse) assert.True(t, result.FallbackToFDv1) + assert.False(t, result.UnexpectedFailure, "a 500 is recoverable") }) } @@ -538,12 +541,80 @@ func testStreamProcessorUnrecoverableHTTPError(t *testing.T, statusCode int) { assert.Equal(t, 1, event.GetByKey("streamInits").Count()) assert.Equal(t, ldvalue.Bool(true), event.GetByKey("streamInits").GetByIndex(0).GetByKey("failed")) - assert.Equal(t, interfaces.DataSourceStateOff, result.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, result.State) + assert.True(t, result.UnexpectedFailure) assert.Equal(t, interfaces.DataSourceErrorKindErrorResponse, result.Error.Kind) assert.Equal(t, statusCode, result.Error.StatusCode) }) } +// A stream that goes quiet after its first Valid result still reports the reset when the +// threshold is reached, with no changeSet to carry. +func TestStreamingProcessorReportsResetOnAQuietStream(t *testing.T) { + protocol := ldservicesv2.NewStreamingProtocol(). + WithIntent(subsystems.ServerIntent{ + Payload: subsystems.Payload{ID: "up-to-date", Code: subsystems.IntentNone, Reason: "initial-state"}, + }) + + streamHandler, _ := ldservices.ServerSideStreamingV2ServiceProtocolHandler(protocol) + dd := mocks.NewMockDataDestination(datastore.NewInMemoryDataStore(sharedtest.NewTestLoggers())) + handler, _ := httphelpers.RecordingHandler(streamHandler) + + httphelpers.WithServer(handler, func(streamServer *httptest.Server) { + sp := NewStreamProcessor(sharedtest.BasicClientContext(), datasource.StreamConfig{URI: streamServer.URL}) + sp.resetInterval = 20 * time.Millisecond + defer sp.Close() + + resultChan := sp.Sync(dd) + + first := <-resultChan + require.Equal(t, interfaces.DataSourceStateValid, first.State) + require.False(t, first.ResetThresholdMet) + + second := <-resultChan + assert.True(t, second.ResetThresholdMet) + assert.Nil(t, second.ChangeSet) + }) +} + +// A malformed event ends the healthy period. The reset is not reported while the stream reconnects, and a new +// healthy period starts after the reconnect. +func TestStreamingProcessorRestartsHealthyPeriodAfterMalformedEvent(t *testing.T) { + upToDate := func() *ldservicesv2.StreamingProtocol { + return ldservicesv2.NewStreamingProtocol(). + WithIntent(subsystems.ServerIntent{ + Payload: subsystems.Payload{ID: "up-to-date", Code: subsystems.IntentNone, Reason: "initial-state"}, + }) + } + + // Each handler sends its intent on its first connection, so the reconnect also reports Valid. + streamHandler, stream := ldservices.ServerSideStreamingV2ServiceProtocolHandler(upToDate()) + reconnectHandler, _ := ldservices.ServerSideStreamingV2ServiceProtocolHandler(upToDate()) + dd := mocks.NewMockDataDestination(datastore.NewInMemoryDataStore(sharedtest.NewTestLoggers())) + + httphelpers.WithServer(httphelpers.SequentialHandler(streamHandler, reconnectHandler), func(ts *httptest.Server) { + // The reset interval is shorter than the default reconnect delay. + sp := NewStreamProcessor(sharedtest.BasicClientContext(), datasource.StreamConfig{URI: ts.URL}) + sp.resetInterval = 100 * time.Millisecond + defer sp.Close() + + resultChan := sp.Sync(dd) + require.Equal(t, interfaces.DataSourceStateValid, (<-resultChan).State) + + // Send a malformed event to make the stream restart. + stream.Send(httphelpers.SSEEvent{Event: putObjectEvent, Data: `{"data": }`}) + require.Equal(t, interfaces.DataSourceErrorKindInvalidData, (<-resultChan).Error.Kind) + + // The next result should be the reconnect, and then the reset for the new healthy period. + reconnected := th.RequireValue(t, resultChan, 5*time.Second, "expected a result after the reconnect") + assert.Equal(t, interfaces.DataSourceStateValid, reconnected.State) + assert.False(t, reconnected.ResetThresholdMet) + + reset := th.RequireValue(t, resultChan, time.Second, "expected a reset result") + assert.True(t, reset.ResetThresholdMet) + }) +} + func TestStreamingDataSourceHandlesUpToDateAndSubsequentChanges(t *testing.T) { protocol := ldservicesv2.NewStreamingProtocol(). WithIntent(subsystems.ServerIntent{ diff --git a/internal/datasystem/fdv2_datasystem.go b/internal/datasystem/fdv2_datasystem.go index 8e390a4b..13e5e19b 100644 --- a/internal/datasystem/fdv2_datasystem.go +++ b/internal/datasystem/fdv2_datasystem.go @@ -45,20 +45,19 @@ type FDv2 struct { initializers []subsystems.DataInitializer // Synchronizers, including the FDv1 fallback synchronizer if one is configured. A - // synchronizer that fails permanently is blocked. On a fallback to FDv1, the list switches - // to FDv1 mode, and only the FDv1 fallback synchronizer can run. + // synchronizer that reports an unexpected failure is parked. On a fallback to FDv1, every + // FDv2 synchronizer is excluded and the FDv1 fallback synchronizer becomes available. synchronizers *synchronizerList - // Receives a signal when the SDK key changes. The synchronizer loop then unblocks the - // blocked synchronizers. The buffer holds one signal, so a signal that arrives while the + // Receives a signal when the SDK key changes. The synchronizer loop then unparks the + // parked synchronizers. The buffer holds one signal, so a signal that arrives while the // loop is busy is not lost. sdkKeyChanged chan struct{} // Boolean used to track whether the datasystem was originally configured // with some sort of valid data source. // - // We cannot check this at run time because synchronizers may be blocked if - // they permanently fail. + // We cannot check this at run time because synchronizers may be parked or excluded. configuredWithDataSources bool // Whether the SDK should make use of persistent store/initializers/synchronizers or not. @@ -246,13 +245,13 @@ func (f *FDv2) run(ctx context.Context, closeWhenReady chan struct{}) { if fallback, errorInfo := f.runInitializers(ctx, closeWhenReady); fallback { if f.synchronizers.hasFDv1Fallback() { f.loggers.Warn("Falling back to FDv1 protocol") - // Switch to FDv1 mode, so only the FDv1 fallback synchronizer can run. - f.synchronizers.fdv1Fallback() + // Exclude every FDv2 synchronizer and make the FDv1 fallback synchronizer available. + f.synchronizers.fallBackToFDv1() } else { f.loggers.Warn("Initializer requested FDv1 fallback but none configured") - // Block every synchronizer so that none starts. - f.synchronizers.blockAll() - f.UpdateStatus(interfaces.DataSourceStateOff, errorInfo) + // Exclude every synchronizer so that none starts. + f.synchronizers.excludeAll() + f.UpdateStatus(interfaces.DataSourceStateInterrupted, errorInfo) } } @@ -376,7 +375,7 @@ func (f *FDv2) completeInitialization(closeWhenReady chan struct{}) { func (f *FDv2) runSynchronizers(ctx context.Context, closeWhenReady chan struct{}) { // If no synchronizers are available, close ready channel and return - if f.synchronizers.availableCount() == 0 { + if f.synchronizers.eligibleCount() == 0 { f.readyOnce.Do(func() { close(closeWhenReady) }) @@ -391,44 +390,45 @@ func (f *FDv2) runSynchronizers(ctx context.Context, closeWhenReady chan struct{ f.synchronizers.next() for { - // Check if we've run out of synchronizers - if f.synchronizers.availableCount() == 0 { - f.loggers.Warn("No more synchronizers available") - f.UpdateStatus(interfaces.DataSourceStateOff, f.getStatus().LastError) - f.readyOnce.Do(func() { - close(closeWhenReady) - }) - // Only an SDK key change can make the blocked synchronizers usable again. Only the - // Relay Proxy changes the key, with LDClient.LDRelayApplySDKKey, so for every other - // application the data system stays off. + // Nothing is eligible. Wait out the soonest unpark, then start the preferred slot. + if f.synchronizers.eligibleCount() == 0 { + unpark, parked := f.synchronizers.earliestUnpark() + if !parked { + f.loggers.Warn("No synchronizers eligible") + return + } + delay := time.Until(unpark) + f.loggers.Warnf("All synchronizers are backing off, the next attempt is in %s", delay) select { case <-ctx.Done(): return case <-f.sdkKeyChanged: - f.unblockSynchronizers() - // Like a recovery, return to the first available synchronizer, which is the - // most preferred one. - f.synchronizers.reset() - f.synchronizers.next() - // The data system is no longer off. Until the synchronizer reports, it is - // interrupted and keeps the error of the failure. The state change also - // restarts StateSince, so the fallback conditions do not count the time - // spent off. - f.UpdateStatus(interfaces.DataSourceStateInterrupted, f.getStatus().LastError) - continue + // An SDK key change can make the parked synchronizers usable again. Only the + // Relay Proxy changes the key, with LDClient.LDRelayApplySDKKey. + f.loggers.Info("SDK key changed, re-enabling synchronizers") + f.synchronizers.unparkAll() + case <-time.After(delay): } + f.synchronizers.reset() + f.synchronizers.next() + continue } // Build synchronizer sync, err := f.synchronizers.build() if err != nil { - f.loggers.Errorf("Failed to build synchronizer at index %d: %v", f.synchronizers.currentIndex(), err) - f.synchronizers.blockCurrent() + delay := f.synchronizers.parkCurrent() + f.loggers.Errorf("Failed to build synchronizer at index %d, backing off for %s: %v", + f.synchronizers.currentIndex(), delay, err) + if !f.waitFailoverDelay(ctx) { + return + } f.synchronizers.next() continue } f.loggers.Infof("Synchronizer at index %d (%s) is starting", f.synchronizers.currentIndex(), sync.Name()) + f.restartStatusClock() resultChan := sync.Sync(f.store) action, err := f.consumeSynchronizerResults(ctx, resultChan, closeWhenReady) @@ -445,26 +445,29 @@ func (f *FDv2) runSynchronizers(ctx context.Context, closeWhenReady chan struct{ case syncFDv1: if f.synchronizers.hasFDv1Fallback() { f.loggers.Warn("Falling back to FDv1 protocol") - // Switch to FDv1 mode, so only the FDv1 fallback synchronizer can run. - f.synchronizers.fdv1Fallback() + // Exclude every FDv2 synchronizer and make the FDv1 fallback synchronizer available. + f.synchronizers.fallBackToFDv1() f.synchronizers.next() continue } f.loggers.Warn("Synchronizer requested FDv1 fallback but none configured") - f.UpdateStatus(interfaces.DataSourceStateOff, f.getStatus().LastError) + f.UpdateStatus(interfaces.DataSourceStateInterrupted, f.getStatus().LastError) return - case syncBlock: - f.loggers.Warnf("Blocking synchronizer at index %d because it failed permanently", - f.synchronizers.currentIndex()) - f.synchronizers.blockCurrent() + case syncPark: + delay := f.synchronizers.parkCurrent() + f.loggers.Warnf("Synchronizer %s is backing off for %s after an unexpected error (%s)", + sync.Name(), delay, f.getStatus().LastError) + // Always wait a minimal amount after parking before starting anything else. + if !f.waitFailoverDelay(ctx) { + return + } f.synchronizers.next() continue case syncRestart: - // The synchronizer failed permanently after an SDK key change. It is not blocked, - // because the failure can come from a request that carried the old key. Like a - // recovery, return to the first available synchronizer, which uses the new key. - f.loggers.Infof("Synchronizer at index %d failed after the SDK key changed, returning to first synchronizer", - f.synchronizers.currentIndex()) + // The synchronizer failed after an SDK key change. Like a recovery, return to the + // first eligible synchronizer, which uses the new key. + f.loggers.Infof("Synchronizer %s failed after the SDK key changed, returning to first synchronizer", + sync.Name()) f.synchronizers.reset() f.synchronizers.next() case syncRecover: @@ -491,13 +494,38 @@ func (f *FDv2) runSynchronizers(ctx context.Context, closeWhenReady chan struct{ type syncAction int const ( - syncFallback syncAction = iota + syncNone syncAction = iota + syncFallback syncRecover - syncBlock + syncPark syncFDv1 syncRestart ) +// conditionAction returns the action the configured conditions call for, or syncNone. Recovery +// is checked first, so it takes precedence when both conditions hold. +func (f *FDv2) conditionAction(status interfaces.DataSourceStatus) syncAction { + if !f.synchronizers.isCurrentFirstEligible() && f.recoveryCond(status) { + f.loggers.Debugf("Recovery condition met") + return syncRecover + } + if f.fallbackCond(status) { + f.loggers.Debugf("Fallback condition met") + return syncFallback + } + return syncNone +} + +// waitFailoverDelay waits a short, jittered delay after a park. It returns false if ctx ends first. +func (f *FDv2) waitFailoverDelay(ctx context.Context) bool { + select { + case <-ctx.Done(): + return false + case <-time.After(f.synchronizers.failoverDelay()): + return true + } +} + func (f *FDv2) consumeSynchronizerResults( ctx context.Context, resultChan <-chan subsystems.DataSynchronizerResult, @@ -514,9 +542,10 @@ func (f *FDv2) consumeSynchronizerResults( case <-ctx.Done(): return syncFallback, ctx.Err() case <-f.sdkKeyChanged: - // The current synchronizer keeps running. The unblocked synchronizers become + // The current synchronizer keeps running. The unparked synchronizers become // available for fallback and recovery. - f.unblockSynchronizers() + f.loggers.Info("SDK key changed, re-enabling synchronizers") + f.synchronizers.unparkAll() keyChanged = true case result, ok := <-resultChan: // The status channel being closed means that we won't be receiving @@ -530,9 +559,14 @@ func (f *FDv2) consumeSynchronizerResults( f.environmentIDProvider.SetEnvironmentID(result.EnvironmentID) } + if result.ResetThresholdMet { + f.synchronizers.resetCurrentBackoff() + } + switch result.State { case interfaces.DataSourceStateValid: - if result.ChangeSet != nil && f.store.Apply(*result.ChangeSet, true) { + applied := result.ChangeSet != nil && f.store.Apply(*result.ChangeSet, true) + if applied { f.dataApplied.Set(true) } @@ -540,22 +574,13 @@ func (f *FDv2) consumeSynchronizerResults( // the signal must observe the updated status. f.UpdateStatus(result.State, result.Error) - f.readyOnce.Do(func() { - close(closeWhenReady) - }) + if applied && result.ChangeSet.IntentCode() == subsystems.IntentTransferFull { + f.readyOnce.Do(func() { + close(closeWhenReady) + }) + } case interfaces.DataSourceStateInterrupted: f.UpdateStatus(result.State, result.Error) - case interfaces.DataSourceStateOff: - f.UpdateStatus(interfaces.DataSourceStateInterrupted, result.Error) - if result.FallbackToFDv1 { - return syncFDv1, nil - } - if keyChanged { - // The failure can come from a request that carried the old key, so the - // synchronizer is not blocked. - return syncRestart, nil - } - return syncBlock, nil } // FallbackToFDv1 may ride along on a Valid or Interrupted result too -- e.g. a @@ -565,25 +590,26 @@ func (f *FDv2) consumeSynchronizerResults( if result.FallbackToFDv1 { return syncFDv1, nil } + + // An unexpected failure moves the data system on at once, without a fallback condition. + if result.UnexpectedFailure { + if keyChanged { + // The key changed after this synchronizer started, so return to the first one instead of parking. + return syncRestart, nil + } + return syncPark, nil + } case <-ticker.C: // If there's only one available synchronizer, don't check conditions - if f.synchronizers.availableCount() == 1 { + if f.synchronizers.eligibleCount() == 1 { continue } status := f.getStatus() f.loggers.Debugf("Data source status used to evaluate condition: %s", status.String()) - // Check fallback condition first (things are bad) - if f.fallbackCond(status) { - f.loggers.Debugf("Fallback condition met") - return syncFallback, nil - } - - // If not at the first available synchronizer, also check recovery condition (things are good) - if !f.synchronizers.isFirstAvailable() && f.recoveryCond(status) { - f.loggers.Debugf("Recovery condition met") - return syncRecover, nil + if action := f.conditionAction(status); action != syncNone { + return action, nil } f.loggers.Debugf("No condition met, continue with current synchronizer") @@ -593,22 +619,10 @@ func (f *FDv2) consumeSynchronizerResults( // SDKKeyChanged tells the data system that the SDK key has changed. // -// A permanent failure can depend on the key, for example a 401 response. The data system -// unblocks the synchronizers that failed permanently, so that they can run with the new key. -// -// If no synchronizer is running, the data system starts the first available synchronizer. A -// running synchronizer is not interrupted. The unblocked synchronizers become available for -// fallback and recovery. -// -// If every synchronizer failed permanently, the data source status is Off. The key change -// moves the status to Interrupted. Only the Relay Proxy changes the key, so for every other -// application Off stays permanent. -// -// The data system does not know the key, so it cannot tell whether the key is different. A -// call after LDClient.LDRelayApplySDKKey with the current key has the same effect as a call -// after a change to a new key. -// -// After an FDv1 fallback, the data system stays on FDv1. +// An unexpected failure, such as a 401 response, might be due to the SDK key. +// This method signals that the key changed, so that synchronizers in an extended backoff +// regime can unpark and be used again. If no synchronizer is running, the data system +// starts the first available synchronizer. A running synchronizer is not interrupted. // // SDKKeyChanged is safe to call from any goroutine. It does not block. func (f *FDv2) SDKKeyChanged() { @@ -619,24 +633,6 @@ func (f *FDv2) SDKKeyChanged() { } } -// unblockSynchronizers unblocks every synchronizer after an SDK key change. -// -// Every synchronizer that failed permanently is unblocked, not only the synchronizers whose -// failure depended on the key. The data system cannot reliably tell those failures apart. A -// custom synchronizer may report no status code, and a proxy may answer a bad key with another -// status. A synchronizer whose failure does not depend on the key fails again and is blocked -// again, which costs one more attempt for each key change. A synchronizer that stayed blocked -// after a failure that depended on the key would not run again until the application restarts. -// -// A server directive is not a block, so unblocking does not undo it. An FDv1 fallback is a -// mode of the synchronizer list, and unblocking does not change the mode. A fallback directive -// with no FDv1 fallback configured stops the synchronizer loop or keeps it from starting, so -// no loop receives the key change. -func (f *FDv2) unblockSynchronizers() { - f.loggers.Info("SDK key changed, re-enabling synchronizers") - f.synchronizers.unblockAll() -} - // Stop shuts down the data system. It will close any active synchronizers. If initialization is in progress, // it will cancel the process gracefully. func (f *FDv2) Stop() error { @@ -647,6 +643,7 @@ func (f *FDv2) Stop() error { f.cancel() } f.wg.Wait() + f.UpdateStatus(interfaces.DataSourceStateOff, interfaces.DataSourceErrorInfo{}) _ = f.store.Close() f.broadcasters.Close() @@ -739,6 +736,13 @@ func (f *FDv2) UpdateStatus(state interfaces.DataSourceState, err interfaces.Dat } } +// restartStatusClock sets the time the current status has been held since to now. +func (f *FDv2) restartStatusClock() { + f.mu.Lock() + defer f.mu.Unlock() + f.status.StateSince = time.Now() +} + func (f *FDv2) getStatus() interfaces.DataSourceStatus { f.mu.Lock() defer f.mu.Unlock() diff --git a/internal/datasystem/fdv2_datasystem_test.go b/internal/datasystem/fdv2_datasystem_test.go index a59eeeef..59a17c34 100644 --- a/internal/datasystem/fdv2_datasystem_test.go +++ b/internal/datasystem/fdv2_datasystem_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/launchdarkly/go-server-sdk/v7/interfaces" + "github.com/launchdarkly/go-server-sdk/v7/subsystems" ) func TestFDv2WaitForReturnsAfterTimeoutWhileStatusUpdatesAreQueued(t *testing.T) { @@ -49,3 +50,29 @@ func TestFDv2WaitForReturnsAfterTimeoutWhileStatusUpdatesAreQueued(t *testing.T) close(stop) flooders.Wait() } + +func TestFDv2SynchronizerSignalsReadinessOnlyForAFullPayload(t *testing.T) { + primary := newScriptedSynchronizer("primary") + system := makeSDKKeyTestFDv2(t, primary) + ready := make(chan struct{}) + system.Start(ready) + run := primary.requireRun(t) + + // An up-to-date result carries no data, so the data system is not ready. + run <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateValid, + ChangeSet: subsystems.NewChangeSetBuilder().NoChanges(), + } + select { + case <-ready: + assert.Fail(t, "ready after an up-to-date result") + case <-time.After(100 * time.Millisecond): + } + + // A full payload makes the data system ready. + run <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateValid, + ChangeSet: subsystems.NewChangeSetBuilder().Empty(subsystems.NewSelector("state", 1)), + } + requireReady(t, ready) +} diff --git a/internal/datasystem/fdv2_fallback_test.go b/internal/datasystem/fdv2_fallback_test.go index 1cef3b9e..f3f71f04 100644 --- a/internal/datasystem/fdv2_fallback_test.go +++ b/internal/datasystem/fdv2_fallback_test.go @@ -2,6 +2,7 @@ package datasystem import ( "context" + "errors" "sync" "testing" "time" @@ -159,10 +160,166 @@ func TestFDv2FallbackConditionDuringStartup(t *testing.T) { } } +// A synchronizer that reports a reset clears its park escalation. +func TestFDv2ResetSignalClearsParkEscalation(t *testing.T) { + only := newFakeSynchronizer("only") + system := makeFallbackTestFDv2(t, only) + + // Stand in for two earlier parks. + system.synchronizers.slots[0].parkAttempts = 2 + + only.results <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateValid, + ChangeSet: subsystems.NewChangeSetBuilder().Empty(subsystems.NewSelector("state", 1)), + ResetThresholdMet: true, + } + + ready := make(chan struct{}) + system.Start(ready) + select { + case <-ready: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the result to be consumed") + } + require.NoError(t, system.Stop()) + + assert.Equal(t, 0, system.synchronizers.slots[0].parkAttempts) +} + +// An explicit shutdown is the one condition that still reports Off, matching FDv1. Stop sets the +// status before returning, so no wait is needed here. +func TestFDv2ReportsOffAfterShutdown(t *testing.T) { + system := makeFallbackTestFDv2(t, newFakeSynchronizer("only")) + system.Start(make(chan struct{})) + + require.NoError(t, system.Stop()) + + assert.Equal(t, interfaces.DataSourceStateOff, system.getStatus().State) +} + +// One status can satisfy both the fallback and the recovery condition: Valid for longer than the +// recovery window, with no data ever applied. The data system must recover to the more-preferred +// synchronizer rather than fall back to the next one. +func TestFDv2RecoveryTakesPrecedenceOverFallback(t *testing.T) { + system := makeFallbackTestFDv2(t, newFakeSynchronizer("first"), newFakeSynchronizer("second")) + t.Cleanup(func() { _ = system.Stop() }) + + // Select the second synchronizer, so that a more-preferred one is eligible. + system.synchronizers.next() + system.synchronizers.next() + require.False(t, system.synchronizers.isCurrentFirstEligible()) + + status := interfaces.DataSourceStatus{ + State: interfaces.DataSourceStateValid, + StateSince: time.Now().Add(-6 * time.Minute), + } + + // Both conditions hold for this status, which is what makes the precedence observable. + require.True(t, system.fallbackCond(status)) + require.True(t, system.recoveryCond(status)) + + assert.Equal(t, syncRecover, system.conditionAction(status)) +} + +// After a park the data system waits a jittered second before starting the next synchronizer, so +// that a fleet-wide failure does not restart every instance at the same moment. +func TestFDv2WaitsFailoverDelayAfterParking(t *testing.T) { + failing := newFakeSynchronizer("failing") + next := newFakeSynchronizer("next") + + system := makeFallbackTestFDv2(t, failing, next) + t.Cleanup(func() { _ = system.Stop() }) + + failing.results <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateInterrupted, + UnexpectedFailure: true, + Error: interfaces.DataSourceErrorInfo{ + Kind: interfaces.DataSourceErrorKindErrorResponse, + StatusCode: 401, + }, + } + + system.Start(make(chan struct{})) + require.True(t, failing.wasStarted(5*time.Second), "first synchronizer should start") + + start := time.Now() + require.True(t, next.wasStarted(5*time.Second), "second synchronizer should start") + assert.Greater(t, time.Since(start), 400*time.Millisecond) +} + +// A synchronizer that fails to build is parked like any other unexpected failure, so the same +// failover delay follows. +func TestFDv2WaitsFailoverDelayAfterBuildFailure(t *testing.T) { + next := newFakeSynchronizer("next") + + system := makeFallbackTestFDv2(t, newFakeSynchronizer("unbuildable"), next) + t.Cleanup(func() { _ = system.Stop() }) + system.synchronizers.slots[0].build = func() (subsystems.DataSynchronizer, error) { + return nil, errors.New("build failed") + } + + start := time.Now() + system.Start(make(chan struct{})) + require.True(t, next.wasStarted(5*time.Second), "second synchronizer should start") + assert.Greater(t, time.Since(start), 400*time.Millisecond) +} + +// TestFDv2ParksSynchronizerOnUnexpectedFailure checks that an unexpected failure moves the +// data system on immediately. The startup fallback window is ten seconds, so a move inside +// two seconds can only have come from the failure itself. +func TestFDv2ParksSynchronizerOnUnexpectedFailure(t *testing.T) { + failing := newFakeSynchronizer("failing") + next := newFakeSynchronizer("next") + + system := makeFallbackTestFDv2(t, failing, next) + t.Cleanup(func() { _ = system.Stop() }) + + failing.results <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateInterrupted, + UnexpectedFailure: true, + Error: interfaces.DataSourceErrorInfo{ + Kind: interfaces.DataSourceErrorKindErrorResponse, + StatusCode: 401, + }, + } + + system.Start(make(chan struct{})) + + require.True(t, failing.wasStarted(5*time.Second), "first synchronizer should start") + assert.True(t, next.wasStarted(2*time.Second), + "an unexpected failure should move on without waiting for the fallback condition") +} + +// TestFDv2DoesNotReportOffWhileEverySynchronizerIsParked covers the single-synchronizer case, +// where a park leaves nothing running. The condition is transient, because the park expires, so +// the data system must not report a permanent state. +func TestFDv2DoesNotReportOffWhileEverySynchronizerIsParked(t *testing.T) { + only := newFakeSynchronizer("only") + + system := makeFallbackTestFDv2(t, only) + t.Cleanup(func() { _ = system.Stop() }) + + only.results <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateInterrupted, + UnexpectedFailure: true, + Error: interfaces.DataSourceErrorInfo{ + Kind: interfaces.DataSourceErrorKindErrorResponse, + StatusCode: 401, + }, + } + + system.Start(make(chan struct{})) + require.True(t, only.wasStarted(5*time.Second), "the only synchronizer should start") + + assert.Never(t, func() bool { + return system.DataSourceStatusProvider().GetStatus().State == interfaces.DataSourceStateOff + }, time.Second, 20*time.Millisecond) +} + // TestFDv2StartupFallsBackPastSilentSynchronizer exercises the whole synchronizer loop -// against the real fallback condition: the first synchronizer fails permanently and the -// second never reports anything, so reaching the third depends on the startup timer -// still being live after the permanent failure. +// against the real fallback condition: the first synchronizer reports an unexpected failure +// and the second never reports anything, so reaching the third depends on the startup timer +// still being live after the park. // // This runs for longer than most unit tests because it waits out the real ten-second // startup fallback window twice; the condition's timing is deliberately not stubbed so @@ -175,9 +332,10 @@ func TestFDv2StartupFallsBackPastSilentSynchronizer(t *testing.T) { system := makeFallbackTestFDv2(t, failing, silent, healthy) t.Cleanup(func() { _ = system.Stop() }) - // Report a permanent failure, which removes the first synchronizer from the list. + // Report an unexpected failure, which parks the first synchronizer. failing.results <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, + State: interfaces.DataSourceStateInterrupted, + UnexpectedFailure: true, Error: interfaces.DataSourceErrorInfo{ Kind: interfaces.DataSourceErrorKindErrorResponse, StatusCode: 401, diff --git a/internal/datasystem/fdv2_sdk_key_test.go b/internal/datasystem/fdv2_sdk_key_test.go index 1535c0bd..59264714 100644 --- a/internal/datasystem/fdv2_sdk_key_test.go +++ b/internal/datasystem/fdv2_sdk_key_test.go @@ -10,7 +10,6 @@ import ( "github.com/launchdarkly/go-server-sdk/v7/internal/sharedtest" "github.com/launchdarkly/go-server-sdk/v7/subsystems" - th "github.com/launchdarkly/go-test-helpers/v3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -68,8 +67,9 @@ func (s *scriptedSynchronizer) assertNoRun(t *testing.T) { var ( unauthorizedResult = subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, - Error: interfaces.DataSourceErrorInfo{Kind: interfaces.DataSourceErrorKindErrorResponse, StatusCode: 401}, + State: interfaces.DataSourceStateInterrupted, + Error: interfaces.DataSourceErrorInfo{Kind: interfaces.DataSourceErrorKindErrorResponse, StatusCode: 401}, + UnexpectedFailure: true, } validResult = subsystems.DataSynchronizerResult{State: interfaces.DataSourceStateValid} ) @@ -128,26 +128,21 @@ func requireKeyChangeTaken(t *testing.T, system *FDv2) { require.Eventually(t, func() bool { return len(system.sdkKeyChanged) == 0 }, time.Second, time.Millisecond) } -func TestFDv2TurnsOffWhenEverySynchronizerFailsPermanently(t *testing.T) { +func TestFDv2StaysInterruptedWhenEverySynchronizerIsParked(t *testing.T) { primary := newScriptedSynchronizer("primary") system := makeSDKKeyTestFDv2(t, primary) - ready := make(chan struct{}) - system.Start(ready) + system.Start(make(chan struct{})) - // The only synchronizer fails permanently, so no synchronizer is available. + // The only synchronizer fails, so the data system parks it. primary.requireRun(t) <- unauthorizedResult - requireReady(t, ready) - // The status is Off with the error of the failure. - status := system.DataSourceStatusProvider().GetStatus() - assert.Equal(t, interfaces.DataSourceStateOff, status.State) - assert.Equal(t, 401, status.LastError.StatusCode) + // The status is Interrupted with the error of the failure. + require.Eventually(t, func() bool { + return system.DataSourceStatusProvider().GetStatus().LastError.StatusCode == 401 + }, time.Second, time.Millisecond) + assert.Equal(t, interfaces.DataSourceStateInterrupted, system.DataSourceStatusProvider().GetStatus().State) - // Without a key change, Off is permanent. A wait for the valid state returns at once, and - // the synchronizer does not start again. - start := time.Now() - assert.False(t, system.DataSourceStatusProvider().WaitFor(interfaces.DataSourceStateValid, time.Second)) - assert.WithinDuration(t, time.Now(), start, 200*time.Millisecond) + // Without a key change, the synchronizer does not start again before its unpark time. primary.assertNoRun(t) } @@ -155,53 +150,32 @@ func TestFDv2KeyChangeRestartsFirstSynchronizerWhenEverySynchronizerFailed(t *te primary := newScriptedSynchronizer("primary") secondary := newScriptedSynchronizer("secondary") system := makeSDKKeyTestFDv2(t, primary, secondary) - ready := make(chan struct{}) - system.Start(ready) + system.Start(make(chan struct{})) - // Both synchronizers fail permanently, so the data system turns off. + // Both synchronizers fail, so the data system parks both. primary.requireRun(t) <- unauthorizedResult secondary.requireRun(t) <- unauthorizedResult - requireReady(t, ready) - off := system.DataSourceStatusProvider().GetStatus() - require.Equal(t, interfaces.DataSourceStateOff, off.State) - - // The clock can advance in coarse steps. On Windows, two calls to time.Now a few - // microseconds apart can return the same time. Wait until the clock has moved past the time - // of the off state, so that a restarted StateSince is later than it. - require.Eventually(t, func() bool { return time.Now().After(off.StateSince) }, time.Second, time.Millisecond) - - // After a key change, the data system leaves the off state. It is interrupted and keeps the - // error of the failure. StateSince restarts, so the fallback conditions do not count the time - // spent off. - statuses := system.DataSourceStatusProvider().AddStatusListener() - system.SDKKeyChanged() - status := th.RequireValue(t, statuses, time.Second) - assert.Equal(t, interfaces.DataSourceStateInterrupted, status.State) - assert.Equal(t, 401, status.LastError.StatusCode) - assert.True(t, status.StateSince.After(off.StateSince)) - // The primary synchronizer starts again and gets data. The secondary synchronizer does not - // start. + // After a key change, the primary synchronizer starts again and gets data. The secondary + // synchronizer does not start. + system.SDKKeyChanged() primary.requireRun(t) <- validResult assert.True(t, system.DataSourceStatusProvider().WaitFor(interfaces.DataSourceStateValid, time.Second)) secondary.assertNoRun(t) } -func TestFDv2KeyChangeRestartsFDv1FallbackSynchronizerAfterPermanentFailure(t *testing.T) { +func TestFDv2KeyChangeRestartsParkedFDv1FallbackSynchronizer(t *testing.T) { // The primary synchronizer directs a fallback to FDv1. Then the FDv1 fallback synchronizer - // fails permanently, so the data system turns off. + // fails, so the data system parks it. primary := newScriptedSynchronizer("primary") fdv1 := newScriptedSynchronizer("fdv1") system := makeSDKKeyTestFDv2WithFDv1Fallback(t, fdv1, primary) - ready := make(chan struct{}) - system.Start(ready) + system.Start(make(chan struct{})) primary.requireRun(t) <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, + State: interfaces.DataSourceStateInterrupted, FallbackToFDv1: true, } fdv1.requireRun(t) <- unauthorizedResult - requireReady(t, ready) - require.Equal(t, interfaces.DataSourceStateOff, system.DataSourceStatusProvider().GetStatus().State) // After a key change, the FDv1 fallback synchronizer starts again and gets data. The data // system stays on FDv1, so the primary synchronizer does not start. @@ -211,8 +185,8 @@ func TestFDv2KeyChangeRestartsFDv1FallbackSynchronizerAfterPermanentFailure(t *t primary.assertNoRun(t) } -func TestFDv2KeyChangeDuringRunReturnsToFirstSynchronizerAfterPermanentFailure(t *testing.T) { - // The first synchronizer fails permanently, so the second synchronizer runs. +func TestFDv2KeyChangeDuringRunReturnsToFirstSynchronizerAfterFailure(t *testing.T) { + // The first synchronizer fails and is parked, so the second synchronizer runs. first := newScriptedSynchronizer("first") second := newScriptedSynchronizer("second") third := newScriptedSynchronizer("third") @@ -225,9 +199,8 @@ func TestFDv2KeyChangeDuringRunReturnsToFirstSynchronizerAfterPermanentFailure(t system.SDKKeyChanged() requireKeyChangeTaken(t, system) - // The second synchronizer then fails permanently. The failure can come from a request that - // carried the old key, so the second synchronizer is not blocked. The data system returns to - // the first synchronizer, which the key change unblocked, rather than moving to the third. + // The second synchronizer then fails. The data system does not park it. It returns to the + // first synchronizer, which the key change unparked, rather than moving to the third. secondRun <- unauthorizedResult first.requireRun(t) third.assertNoRun(t) @@ -235,7 +208,7 @@ func TestFDv2KeyChangeDuringRunReturnsToFirstSynchronizerAfterPermanentFailure(t } func TestFDv2KeyChangeDoesNotInterruptRunningSynchronizer(t *testing.T) { - // The primary synchronizer fails permanently, so the secondary synchronizer runs and gets data. + // The primary synchronizer fails and is parked, so the secondary synchronizer runs and gets data. primary := newScriptedSynchronizer("primary") secondary := newScriptedSynchronizer("secondary") system := makeSDKKeyTestFDv2(t, primary, secondary) @@ -243,7 +216,7 @@ func TestFDv2KeyChangeDoesNotInterruptRunningSynchronizer(t *testing.T) { primary.requireRun(t) <- unauthorizedResult secondary.requireRun(t) <- validResult - // The key change unblocks the primary synchronizer, but the secondary synchronizer keeps + // The key change unparks the primary synchronizer, but the secondary synchronizer keeps // running. The recovery condition decides when to return to the primary synchronizer. system.SDKKeyChanged() requireKeyChangeTaken(t, system) @@ -252,25 +225,19 @@ func TestFDv2KeyChangeDoesNotInterruptRunningSynchronizer(t *testing.T) { } func TestFDv2KeyChangeDoesNotUndoFallbackDirectiveWithoutFDv1Fallback(t *testing.T) { - // No FDv1 fallback is configured, so a fallback directive turns the data system off for good. + // No FDv1 fallback is configured, so a fallback directive stops every synchronizer for good. primary := newScriptedSynchronizer("primary") system := makeSDKKeyTestFDv2(t, primary) ready := make(chan struct{}) system.Start(ready) primary.requireRun(t) <- subsystems.DataSynchronizerResult{ - State: interfaces.DataSourceStateOff, + State: interfaces.DataSourceStateInterrupted, FallbackToFDv1: true, } requireReady(t, ready) - require.Equal(t, interfaces.DataSourceStateOff, system.DataSourceStatusProvider().GetStatus().State) - // A key change does not start a synchronizer, and the data system stays off. + // A key change does not start a synchronizer, and the data system stays interrupted. system.SDKKeyChanged() primary.assertNoRun(t) - assert.Equal(t, interfaces.DataSourceStateOff, system.DataSourceStatusProvider().GetStatus().State) - - // Off is permanent, so a wait for the valid state returns at once. - start := time.Now() - assert.False(t, system.DataSourceStatusProvider().WaitFor(interfaces.DataSourceStateValid, time.Second)) - assert.WithinDuration(t, time.Now(), start, 200*time.Millisecond) + assert.Equal(t, interfaces.DataSourceStateInterrupted, system.DataSourceStatusProvider().GetStatus().State) } diff --git a/internal/datasystem/synchronizer_list.go b/internal/datasystem/synchronizer_list.go index f0d3c611..2e5c2ee5 100644 --- a/internal/datasystem/synchronizer_list.go +++ b/internal/datasystem/synchronizer_list.go @@ -2,12 +2,22 @@ package datasystem import ( "errors" + "math" + "math/rand" + "time" "github.com/launchdarkly/go-server-sdk/v7/subsystems" ) type synchronizerBuilder = func() (subsystems.DataSynchronizer, error) +// Bounds on the delay before a parked synchronizer may run again. +const ( + parkInitialDelay = 5 * time.Minute + parkMaxDelay = 1 * time.Hour + afterParkDelay = 1 * time.Second +) + var errNoCurrentSynchronizer = errors.New("no current synchronizer") // synchronizerSlot holds one synchronizer builder and its state. @@ -15,19 +25,34 @@ type synchronizerSlot struct { build synchronizerBuilder isFDv1Fallback bool - // True if the synchronizer failed permanently. A blocked slot is not eligible for use. - blocked bool + // excluded is true when the slot is not in the set the data system selects from: the FDv1 + // fallback slot before a directive, and the FDv2 slots while one is in effect. + excluded bool + + // parkedUntil is the unpark time of a parked slot. Zero means not parked. + parkedUntil time.Time + + // parkAttempts is the number of times the slot has been parked since its last reset. + parkAttempts int +} + +// park parks the slot and returns the delay until its unpark time. Each successive park +// doubles the delay, up to parkMaxDelay. +func (s *synchronizerSlot) park(rng *rand.Rand) time.Duration { + s.parkAttempts++ + t := time.Duration(math.Min( + float64(parkInitialDelay)*math.Pow(2, float64(s.parkAttempts-1)), + float64(parkMaxDelay), + )) + var jitter time.Duration + if halfT := int64(t / 2); halfT > 0 { + jitter = time.Duration(rng.Int63n(halfT)) + } + delay := t - jitter + s.parkedUntil = time.Now().Add(delay) + return delay } -// synchronizerList is the ordered list of synchronizers that the data system can use. A -// synchronizer that fails permanently stays in the list and is marked as blocked. The FDv1 -// fallback synchronizer, if configured, is the last slot. -// -// The list is either in FDv2 mode or in FDv1 mode. In FDv2 mode, only the FDv2 slots are -// eligible. In FDv1 mode, only the FDv1 fallback slot is eligible. The mode and the blocked -// state are independent. A slot is available if it is eligible in the current mode and it is -// not blocked. -// // The list is not safe for concurrent use. Only the goroutine that runs the synchronizers // uses it. type synchronizerList struct { @@ -36,11 +61,11 @@ type synchronizerList struct { // True if the last slot is the FDv1 fallback slot. hasFDv1 bool - // True after an FDv1 fallback. - onFDv1 bool - // Index of the current slot, or -1 if there is no current slot. current int + + // Source of jitter for park delays. + rng *rand.Rand } func newSynchronizerList(builders []synchronizerBuilder, fdv1Fallback synchronizerBuilder) *synchronizerList { @@ -49,24 +74,35 @@ func newSynchronizerList(builders []synchronizerBuilder, fdv1Fallback synchroniz slots = append(slots, synchronizerSlot{build: b}) } if fdv1Fallback != nil { - slots = append(slots, synchronizerSlot{build: fdv1Fallback, isFDv1Fallback: true}) + slots = append(slots, synchronizerSlot{build: fdv1Fallback, isFDv1Fallback: true, excluded: true}) } - return &synchronizerList{slots: slots, hasFDv1: fdv1Fallback != nil, current: -1} + return &synchronizerList{ + slots: slots, + hasFDv1: fdv1Fallback != nil, + current: -1, + //nolint:gosec // not a cryptographic use-case, weak RNG is acceptable for jitter + rng: rand.New(rand.NewSource(time.Now().UnixNano())), + } +} + +// isParked reports whether the slot's unpark time has not yet arrived. +func (l *synchronizerList) isParked(idx int) bool { + return time.Now().Before(l.slots[idx].parkedUntil) } -// isAvailable returns true if the slot is eligible in the current mode and is not blocked. -func (l *synchronizerList) isAvailable(slot synchronizerSlot) bool { - return !slot.blocked && slot.isFDv1Fallback == l.onFDv1 +// isEligible reports whether the slot can be selected. +func (l *synchronizerList) isEligible(idx int) bool { + return !l.slots[idx].excluded && !l.isParked(idx) } -// next makes the next available slot after the current slot the current slot. The search -// wraps around to the start of the list. If there is no current slot, the search starts at -// the start of the list. If the current slot is the only available slot, it stays current. -// If no slot is available, there is no current slot. +// next makes the first eligible slot after the current slot the current slot. The search wraps +// around, so it reaches the most-preferred eligible slot when none follows the current one. If +// there is no current slot, the search starts at the start of the list. If the current slot is +// the only eligible slot, it stays current. If no slot is eligible, there is no current slot. func (l *synchronizerList) next() { for i := 1; i <= len(l.slots); i++ { idx := (l.current + i) % len(l.slots) - if l.isAvailable(l.slots[idx]) { + if l.isEligible(idx) { l.current = idx return } @@ -74,7 +110,7 @@ func (l *synchronizerList) next() { l.current = -1 } -// reset clears the current slot. The next call to next selects the first available slot. +// reset clears the current slot. The next call to next selects the most-preferred eligible slot. func (l *synchronizerList) reset() { l.current = -1 } @@ -93,60 +129,88 @@ func (l *synchronizerList) build() (subsystems.DataSynchronizer, error) { return l.slots[l.current].build() } -// blockCurrent marks the current slot as blocked. -func (l *synchronizerList) blockCurrent() { +// parkCurrent parks the current slot and returns the delay until its unpark time. +func (l *synchronizerList) parkCurrent() time.Duration { + if l.current < 0 { + return 0 + } + return l.slots[l.current].park(l.rng) +} + +// unparkAll unparks every slot, including synchronizers that are currently excluded. +func (l *synchronizerList) unparkAll() { + for i := range l.slots { + l.slots[i].parkedUntil = time.Time{} + } +} + +// failoverDelay returns the delay to wait before starting another synchronizer after a park. +func (l *synchronizerList) failoverDelay() time.Duration { + return afterParkDelay - time.Duration(l.rng.Int63n(int64(afterParkDelay/2))) +} + +// resetCurrentBackoff clears the current slot's park escalation. +func (l *synchronizerList) resetCurrentBackoff() { if l.current >= 0 { - l.slots[l.current].blocked = true + l.slots[l.current].parkAttempts = 0 } } -// isFirstAvailable returns true if the current slot is the first available slot. -func (l *synchronizerList) isFirstAvailable() bool { - for i, slot := range l.slots { - if l.isAvailable(slot) { +// isCurrentFirstEligible returns true if the current slot is the most-preferred eligible slot. +func (l *synchronizerList) isCurrentFirstEligible() bool { + for i := range l.slots { + if l.isEligible(i) { return i == l.current } } return false } -// availableCount returns the number of available slots. -func (l *synchronizerList) availableCount() int { +// eligibleCount returns the number of slots that can be selected. +func (l *synchronizerList) eligibleCount() int { count := 0 - for _, slot := range l.slots { - if l.isAvailable(slot) { + for i := range l.slots { + if l.isEligible(i) { count++ } } return count } +// earliestUnpark returns the soonest unpark time among the parked slots, and whether there +// is one. Excluded slots are skipped. +func (l *synchronizerList) earliestUnpark() (time.Time, bool) { + var earliest time.Time + for i := range l.slots { + if l.slots[i].excluded || !l.isParked(i) { + continue + } + if earliest.IsZero() || l.slots[i].parkedUntil.Before(earliest) { + earliest = l.slots[i].parkedUntil + } + } + return earliest, !earliest.IsZero() +} + // hasFDv1Fallback returns true if the list contains an FDv1 fallback slot. func (l *synchronizerList) hasFDv1Fallback() bool { return l.hasFDv1 } -// blockAll blocks every slot and clears the current slot. -func (l *synchronizerList) blockAll() { +// excludeAll excludes every slot and clears the current slot. +func (l *synchronizerList) excludeAll() { for i := range l.slots { - l.slots[i].blocked = true + l.slots[i].excluded = true } l.current = -1 } -// fdv1Fallback puts the list in FDv1 mode, so only the FDv1 fallback slot is eligible. It -// also clears the current slot, so the next call to next selects the FDv1 fallback slot. The -// blocked state of the FDv2 slots does not change. -func (l *synchronizerList) fdv1Fallback() { - l.onFDv1 = true - l.current = -1 -} - -// unblockAll clears the blocked state of every slot, including FDv2 slots in FDv1 mode. The -// mode does not change, so after an FDv1 fallback only the FDv1 fallback slot is available. -// The current slot does not change. -func (l *synchronizerList) unblockAll() { +// fallBackToFDv1 excludes every FDv2 slot and includes the FDv1 fallback slot. It also clears +// the current slot, so the next call to next selects the FDv1 fallback slot. Any park on the +// FDv1 fallback slot stays in force. +func (l *synchronizerList) fallBackToFDv1() { for i := range l.slots { - l.slots[i].blocked = false + l.slots[i].excluded = !l.slots[i].isFDv1Fallback } + l.current = -1 } diff --git a/internal/datasystem/synchronizer_list_test.go b/internal/datasystem/synchronizer_list_test.go index cc8aa786..3334f5a9 100644 --- a/internal/datasystem/synchronizer_list_test.go +++ b/internal/datasystem/synchronizer_list_test.go @@ -2,6 +2,7 @@ package datasystem import ( "testing" + "time" "github.com/stretchr/testify/assert" @@ -12,130 +13,248 @@ func noopBuilder() (subsystems.DataSynchronizer, error) { return nil, nil } -func TestSynchronizerListNextSkipsBlockedSlotsAndWraps(t *testing.T) { +func TestSynchronizerListParkedSlotIsIneligibleUntilUnparkTime(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, nil) + now := time.Now() + list.next() + + // While the unpark time is in the future, only the other slot is eligible. + list.slots[0].parkedUntil = now.Add(5 * time.Minute) + assert.Equal(t, 1, list.eligibleCount()) + + // Once it has passed, the slot is eligible again. + list.slots[0].parkedUntil = now.Add(-time.Second) + assert.Equal(t, 2, list.eligibleCount()) +} + +func TestSynchronizerListParkDurationDoublesToTheCeiling(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder}, nil) + list.next() + + for _, want := range []time.Duration{ + 5 * time.Minute, 10 * time.Minute, 20 * time.Minute, 40 * time.Minute, time.Hour, time.Hour, + } { + delay := list.parkCurrent() + assert.Greater(t, delay, want/2) + assert.LessOrEqual(t, delay, want) + } +} + +func TestSynchronizerListResetReturnsParksToTheInitialDelay(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder}, nil) + list.next() + + first := list.parkCurrent() + list.parkCurrent() + list.resetCurrentBackoff() + afterReset := list.parkCurrent() + + for _, delay := range []time.Duration{first, afterReset} { + assert.Greater(t, delay, 150*time.Second) + assert.LessOrEqual(t, delay, 5*time.Minute) + } +} + +func TestSynchronizerListNextAfterParkPrefersTheSlotAfterTheParkedOne(t *testing.T) { list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder, noopBuilder}, nil) + now := time.Now() - // Select the first slot, then block the second slot. + // Fall back from the first slot to the second without parking the first. list.next() - assert.Equal(t, 0, list.currentIndex()) list.next() - list.blockCurrent() + assert.Equal(t, 1, list.currentIndex()) - // Moving on from the blocked slot reaches the third slot, then wraps past the blocked slot. + // Park the second slot. Selection continues after it rather than returning to the first, which + // a fallback condition demoted but did not park. + list.slots[1].parkedUntil = now.Add(5 * time.Minute) list.next() assert.Equal(t, 2, list.currentIndex()) +} + +func TestSynchronizerListNextWrapsToMostPreferredEligibleSlot(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, nil) + now := time.Now() + + // Move to the last slot, then park it. The search wraps to the first slot. + list.next() + list.next() + assert.Equal(t, 1, list.currentIndex()) + list.slots[1].parkedUntil = now.Add(5 * time.Minute) list.next() assert.Equal(t, 0, list.currentIndex()) - - // The blocked slot stays in the list but is not counted as available. - assert.Len(t, list.slots, 3) - assert.Equal(t, 2, list.availableCount()) } -func TestSynchronizerListNextKeepsOnlyAvailableSlot(t *testing.T) { +func TestSynchronizerListNextKeepsOnlyEligibleSlot(t *testing.T) { list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, nil) + now := time.Now() list.next() - list.blockCurrent() + list.slots[0].parkedUntil = now.Add(5 * time.Minute) - // Moving on from the blocked slot selects the only available slot. + // Moving on from the parked slot selects the only eligible slot, and moving on again keeps it. + // Stopping the only runnable slot would leave the SDK with no source of updates. list.next() - // Moving on again keeps the same slot. list.next() assert.Equal(t, 1, list.currentIndex()) } -func TestSynchronizerListNextLeavesNoCurrentSlotWhenAllSlotsBlocked(t *testing.T) { +func TestSynchronizerListNextLeavesNoCurrentSlotWhenEverySlotIsParked(t *testing.T) { list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, nil) - list.next() - list.blockCurrent() - list.next() - list.blockCurrent() + now := time.Now() + list.slots[0].parkedUntil = now.Add(5 * time.Minute) + list.slots[1].parkedUntil = now.Add(10 * time.Minute) - // No slot remains available. + // No slot is eligible, so nothing is selected and nothing starts. list.next() assert.Equal(t, -1, list.currentIndex()) - assert.Equal(t, 0, list.availableCount()) + assert.Equal(t, 0, list.eligibleCount()) +} + +func TestSynchronizerListEarliestUnparkReportsTheSoonestParkedSlot(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, nil) + now := time.Now() + + // With nothing parked there is no unpark time to wait for. + _, ok := list.earliestUnpark() + assert.False(t, ok) + + // Park both slots. The earliest of the two unpark times is reported. + list.slots[0].parkedUntil = now.Add(10 * time.Minute) + list.slots[1].parkedUntil = now.Add(5 * time.Minute) + + unpark, ok := list.earliestUnpark() + assert.True(t, ok) + assert.Equal(t, now.Add(5*time.Minute), unpark) +} + +func TestSynchronizerListEarliestUnparkIgnoresSlotsPastTheirUnparkTime(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, nil) + now := time.Now() + list.next() + list.slots[0].parkedUntil = now.Add(-time.Second) + + // A slot past its unpark time is eligible, so nothing is waiting. + _, ok := list.earliestUnpark() + assert.False(t, ok) } -func TestSynchronizerListEmptyHasNoAvailableSlot(t *testing.T) { +func TestSynchronizerListEmptyHasNoEligibleSlot(t *testing.T) { list := newSynchronizerList(nil, nil) // An empty list has nothing to select. list.next() assert.Equal(t, -1, list.currentIndex()) - assert.Equal(t, 0, list.availableCount()) + assert.Equal(t, 0, list.eligibleCount()) // Building with no current slot returns an error. _, err := list.build() assert.Error(t, err) } -func TestSynchronizerListResetReturnsToFirstAvailableSlot(t *testing.T) { +func TestSynchronizerListResetReturnsToMostPreferredEligibleSlot(t *testing.T) { list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder, noopBuilder}, nil) + now := time.Now() list.next() - list.blockCurrent() + list.slots[0].parkedUntil = now.Add(5 * time.Minute) list.next() list.next() assert.Equal(t, 2, list.currentIndex()) - assert.False(t, list.isFirstAvailable()) + assert.False(t, list.isCurrentFirstEligible()) - // Reset and select again. + // Recovery returns to the most-preferred eligible slot, which is the second while the first is parked. list.reset() list.next() - - // The first slot is blocked, so the second slot is the first available slot. assert.Equal(t, 1, list.currentIndex()) - assert.True(t, list.isFirstAvailable()) + assert.True(t, list.isCurrentFirstEligible()) + + // When the first slot re-enters, it becomes the most-preferred eligible slot. + list.slots[0].parkedUntil = now.Add(-time.Second) + assert.False(t, list.isCurrentFirstEligible()) + list.reset() + list.next() + assert.Equal(t, 0, list.currentIndex()) +} + +func TestSynchronizerListParkingSurvivesSelectionChanges(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder, noopBuilder}, nil) + now := time.Now() + list.next() + list.next() + + // Park the second slot, then move through the rest of the list and back. + list.slots[1].parkedUntil = now.Add(5 * time.Minute) + list.next() + list.next() + assert.Equal(t, 0, list.currentIndex()) + + // The park is still in force; selection never lands on the parked slot. + list.next() + assert.Equal(t, 2, list.currentIndex()) } -func TestSynchronizerListFDv1FallbackSlotIsUnusedUntilFallback(t *testing.T) { +func TestSynchronizerListFDv1FallbackSlotIsExcludedUntilFallback(t *testing.T) { list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, noopBuilder) assert.True(t, list.hasFDv1Fallback()) // Before a fallback, selection never reaches the FDv1 slot. - assert.Equal(t, 2, list.availableCount()) + assert.Equal(t, 2, list.eligibleCount()) list.next() list.next() list.next() assert.Equal(t, 0, list.currentIndex()) // Fall back to FDv1 and select again. - list.fdv1Fallback() + list.fallBackToFDv1() list.next() - // Only the FDv1 slot is available. + // Only the FDv1 slot is eligible, and every FDv2 slot is excluded. assert.Equal(t, 2, list.currentIndex()) assert.True(t, list.slots[list.currentIndex()].isFDv1Fallback) - assert.Equal(t, 1, list.availableCount()) + assert.Equal(t, 1, list.eligibleCount()) } -func TestSynchronizerListBlockAllLeavesNoSlotAvailable(t *testing.T) { +func TestSynchronizerListExcludedSlotIsNotEligibleWhenItsParkExpires(t *testing.T) { list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, noopBuilder) + now := time.Now() + + // Park the first slot past its unpark time, then engage a directed fallback to FDv1. list.next() + list.slots[0].parkedUntil = now.Add(-time.Second) + list.fallBackToFDv1() - // Block every slot, including the FDv1 fallback slot. - list.blockAll() + // The FDv2 slot is past its unpark time but excluded, so it still does not run. + assert.Equal(t, 1, list.eligibleCount()) + list.reset() + list.next() + assert.True(t, list.slots[list.currentIndex()].isFDv1Fallback) +} - // No slot remains available. +func TestSynchronizerListExcludeAllLeavesNoSlotEligible(t *testing.T) { + list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, noopBuilder) + list.next() + + // Exclude every slot, including the FDv1 fallback slot. + list.excludeAll() + + // No slot remains eligible. list.next() assert.Equal(t, -1, list.currentIndex()) + assert.Equal(t, 0, list.eligibleCount()) } -func TestSynchronizerListUnblockAllKeepsCurrentFDv2Slot(t *testing.T) { - // Streaming, polling, and FDv1 fallback slots. Streaming is blocked, and polling is current. +func TestSynchronizerListUnparkAllKeepsCurrentFDv2Slot(t *testing.T) { + // Streaming, polling, and FDv1 fallback slots. Streaming is parked, and polling is current. list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, noopBuilder) list.next() - list.blockCurrent() + list.parkCurrent() list.next() assert.Equal(t, 1, list.currentIndex()) - // Unblock the slots. - list.unblockAll() + list.unparkAll() - // Polling stays current, and streaming is available again as the first slot. + // Polling stays current, and streaming is eligible again as the first slot. assert.Equal(t, 1, list.currentIndex()) - assert.Equal(t, 2, list.availableCount()) - assert.False(t, list.isFirstAvailable()) + assert.Equal(t, 2, list.eligibleCount()) + assert.False(t, list.isCurrentFirstEligible()) // A recovery selects streaming. list.reset() @@ -143,27 +262,19 @@ func TestSynchronizerListUnblockAllKeepsCurrentFDv2Slot(t *testing.T) { assert.Equal(t, 0, list.currentIndex()) } -func TestSynchronizerListUnblockAllStaysOnFDv1AfterFallback(t *testing.T) { - // Streaming, polling, and FDv1 fallback slots. Streaming is blocked, then the list falls - // back to FDv1. +func TestSynchronizerListUnparkAllStaysOnFDv1AfterFallback(t *testing.T) { + // Streaming, polling, and FDv1 fallback slots. Streaming is parked, then the list falls back to FDv1. list := newSynchronizerList([]synchronizerBuilder{noopBuilder, noopBuilder}, noopBuilder) list.next() - list.blockCurrent() + list.parkCurrent() list.next() - list.fdv1Fallback() + list.fallBackToFDv1() list.next() assert.Equal(t, 2, list.currentIndex()) - // Unblock the slots. - list.unblockAll() + list.unparkAll() - // The FDv1 slot stays current and is the only available slot. + // The FDv1 slot stays current and is the only eligible slot. assert.Equal(t, 2, list.currentIndex()) - assert.Equal(t, 1, list.availableCount()) - - // On a return to FDv2 mode, streaming is selected before polling. - list.onFDv1 = false - list.reset() - list.next() - assert.Equal(t, 0, list.currentIndex()) + assert.Equal(t, 1, list.eligibleCount()) } diff --git a/ldclient.go b/ldclient.go index 9bdb7d5f..2d2605ad 100644 --- a/ldclient.go +++ b/ldclient.go @@ -705,17 +705,12 @@ func (client *LDClient) IsOffline() bool { // connection that is open. That connection continues until the service or the network ends it. Then // the client reconnects with the new key. // -// If the client uses the FDv2 data system, synchronizers that failed permanently can run again. -// If no synchronizer is running, the client starts one with the new key. If the client has fallen -// back to FDv1, it stays on FDv1. -// -// If every synchronizer failed permanently, the data source status is -// [interfaces.DataSourceStateOff]. This method then moves the status to -// [interfaces.DataSourceStateInterrupted], and the synchronizers that start again set it from then -// on. No other method makes the status leave [interfaces.DataSourceStateOff]. +// If the client uses the FDv2 data system, synchronizers that are backing off after a failure can +// run again at once. If no synchronizer is running, the client starts one with the new key. If the +// client has fallen back to FDv1, it stays on FDv1. // // The client does not compare sdkKey with the key it uses now. A call with the current key also -// starts the synchronizers that failed permanently again. The Relay Proxy uses this to try a key +// ends the backoff of every synchronizer. The Relay Proxy uses this to try a key // again after LaunchDarkly rejected it. // // SecureModeHash and diagnostic events also use the new key. Plugins keep the key that the client diff --git a/ldclient_end_to_end_fdv2_test.go b/ldclient_end_to_end_fdv2_test.go index df575321..f2f3290e 100644 --- a/ldclient_end_to_end_fdv2_test.go +++ b/ldclient_end_to_end_fdv2_test.go @@ -126,7 +126,7 @@ func TestFDV2CanFallBackToV1(t *testing.T) { // When an initializer requests FDv1 fallback but no FDv1 fallback is configured, the data source // status must transition to Off rather than staying stuck at Initializing. This mirrors the // synchronizer-triggered path when no FDv1 fallback is configured. -func TestFDV2InitializerFallbackWithoutFDv1FallbackTransitionsToOff(t *testing.T) { +func TestFDV2InitializerFallbackWithoutFDv1FallbackTransitionsToInterrupted(t *testing.T) { header := http.Header{ "X-LD-FD-Fallback": []string{"true"}, } @@ -157,9 +157,9 @@ func TestFDV2InitializerFallbackWithoutFDv1FallbackTransitionsToOff(t *testing.T // should end up Off, so assert that directly. status := client.GetDataSourceStatusProvider().GetStatus() assert.Equal(t, - interfaces.DataSourceStateOff, + interfaces.DataSourceStateInterrupted, status.State, - "status should transition to Off when initializer fallback requested but no FDv1 fallback configured") + "status should be Interrupted when initializer fallback requested but no FDv1 fallback configured") // The underlying initializer error must be preserved on the Off status so programmatic // monitors can see why the data source shut down, not just that it did. assert.NotEqual(t, interfaces.DataSourceErrorInfo{}, status.LastError, @@ -173,7 +173,7 @@ func TestFDV2InitializerFallbackWithoutFDv1FallbackTransitionsToOff(t *testing.T // When a synchronizer requests FDv1 fallback but no FDv1 fallback is configured, the data // source status must transition to Off. No other FDv2 synchronizer may start. -func TestFDV2SynchronizerFallbackWithoutFDv1FallbackTransitionsToOff(t *testing.T) { +func TestFDV2SynchronizerFallbackWithoutFDv1FallbackTransitionsToInterrupted(t *testing.T) { header := http.Header{ "X-LD-FD-Fallback": []string{"true"}, } @@ -201,7 +201,7 @@ func TestFDV2SynchronizerFallbackWithoutFDv1FallbackTransitionsToOff(t *testing. // The data system is off, and only the first synchronizer made a request. assert.Equal(t, initializationFailedErrorMessage, err.Error()) assert.Equal(t, - string(interfaces.DataSourceStateOff), + string(interfaces.DataSourceStateInterrupted), string(client.GetDataSourceStatusProvider().GetStatus().State)) <-requestsCh assertNoMoreRequests(t, requestsCh) @@ -362,7 +362,7 @@ func TestFDV2StreamingSynchronizer(t *testing.T) { }) } -func TestFDV2ShutdownDownIfBothSynchronizersFail(t *testing.T) { +func TestFDV2ParksBothSynchronizersOn401(t *testing.T) { handler, requestsCh := httphelpers.RecordingHandler(httphelpers.HandlerWithStatus(401)) httphelpers.WithServer(handler, func(server *httptest.Server) { logCapture := ldlogtest.NewMockLog() @@ -383,9 +383,11 @@ func TestFDV2ShutdownDownIfBothSynchronizersFail(t *testing.T) { require.NotNil(t, client) defer client.Close() - assert.Equal(t, initializationFailedErrorMessage, err.Error()) + assert.ErrorIs(t, err, ErrInitializationTimeout) - assert.Equal(t, string(interfaces.DataSourceStateOff), string(client.GetDataSourceStatusProvider().GetStatus().State)) + // Both synchronizers are parked, so nothing is running, but neither is retired. + assert.Equal(t, string(interfaces.DataSourceStateInterrupted), + string(client.GetDataSourceStatusProvider().GetStatus().State)) value, _ := client.BoolVariation(alwaysTrueFlag.Key, testUser, false) assert.False(t, value) @@ -401,15 +403,12 @@ func TestFDV2ShutdownDownIfBothSynchronizersFail(t *testing.T) { // Ensure no further requests assertNoMoreRequests(t, requestsCh) - expectedStreamError := "Error in stream connection (giving up permanently): HTTP error 401 (invalid SDK key)" - expectedPollError := "Error on polling request (giving up permanently): HTTP error 401 (invalid SDK key)" - assert.Equal(t, []string{expectedStreamError, expectedPollError}, logCapture.GetOutput(ldlog.Error)) - assert.Equal(t, []string{ - "Blocking synchronizer at index 0 because it failed permanently", - "Blocking synchronizer at index 1 because it failed permanently", - "No more synchronizers available", - initializationFailedErrorMessage, - }, logCapture.GetOutput(ldlog.Warn)) + // Each synchronizer reports its failure at error level, identifying the status code. + errorLogs := logCapture.GetOutput(ldlog.Error) + require.Len(t, errorLogs, 2) + for _, logged := range errorLogs { + assert.Contains(t, logged, "401") + } }) } @@ -477,9 +476,11 @@ func TestFDV2PollingSynchronizerFailsToStartWith401Error(t *testing.T) { require.NotNil(t, client) defer client.Close() - assert.Equal(t, initializationFailedErrorMessage, err.Error()) + assert.ErrorIs(t, err, ErrInitializationTimeout) - assert.Equal(t, string(interfaces.DataSourceStateOff), string(client.GetDataSourceStatusProvider().GetStatus().State)) + // A 401 is an unexpected failure, so the synchronizer is parked rather than retired. + assert.Equal(t, string(interfaces.DataSourceStateInterrupted), + string(client.GetDataSourceStatusProvider().GetStatus().State)) value, _ := client.BoolVariation(alwaysTrueFlag.Key, testUser, false) assert.False(t, value) @@ -488,13 +489,10 @@ func TestFDV2PollingSynchronizerFailsToStartWith401Error(t *testing.T) { assert.Equal(t, testSdkKey, r.Request.Header.Get("Authorization")) assertNoMoreRequests(t, requestsCh) - expectedError := "Error on polling request (giving up permanently): HTTP error 401 (invalid SDK key)" - assert.Equal(t, []string{expectedError}, logCapture.GetOutput(ldlog.Error)) - assert.Equal(t, []string{ - "Blocking synchronizer at index 0 because it failed permanently", - "No more synchronizers available", - initializationFailedErrorMessage, - }, logCapture.GetOutput(ldlog.Warn)) + // The failure is reported at error level and identifies the status code. + errorLogs := logCapture.GetOutput(ldlog.Error) + require.Len(t, errorLogs, 1) + assert.Contains(t, errorLogs[0], "401") }) } @@ -703,7 +701,7 @@ func TestFDV2PopulatedPersistentStoreDoesNotSatisfyInitSuccess(t *testing.T) { require.Error(t, err) require.NotNil(t, client) defer client.Close() - assert.Equal(t, initializationFailedErrorMessage, err.Error()) + assert.ErrorIs(t, err, ErrInitializationTimeout) // The persisted data is still available: the client reports Initialized and evaluates // with the stored flag. diff --git a/ldclient_listeners_fdv2_test.go b/ldclient_listeners_fdv2_test.go index 5037e332..eccb4b4a 100644 --- a/ldclient_listeners_fdv2_test.go +++ b/ldclient_listeners_fdv2_test.go @@ -181,7 +181,8 @@ func TestDataSourceStatusProviderV2(t *testing.T) { return default: status := p.client.GetDataSourceStatusProvider().GetStatus() - if status.State == interfaces.DataSourceStateOff { + if status.State == interfaces.DataSourceStateInterrupted && + status.LastError.StatusCode == 401 { return } } @@ -213,11 +214,9 @@ func TestDataSourceStatusProviderV2(t *testing.T) { assert.Equal(t, interfaces.DataSourceErrorKindErrorResponse, status.LastError.Kind) assert.Equal(t, 401, status.LastError.StatusCode) - status = <-ch - assert.Equal(t, interfaces.DataSourceStateOff, status.State) - + // The 401 parks the synchronizer, so the status stays Interrupted. status = p.client.GetDataSourceStatusProvider().GetStatus() - assert.Equal(t, interfaces.DataSourceStateOff, status.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, status.State) }, httphelpers.HandlerWithStatus(401)) }) @@ -237,15 +236,13 @@ func TestDataSourceStatusProviderV2(t *testing.T) { foundIt = p.client.GetDataSourceStatusProvider().WaitFor(interfaces.DataSourceStateInterrupted, time.Second) assert.False(t, foundIt) - // Shut it down and make sure it's stopped. + // Closing the stream leads to a 401, which parks the synchronizer. p.control.Close() - foundIt = p.client.GetDataSourceStatusProvider().WaitFor(interfaces.DataSourceStateOff, time.Second) + foundIt = p.client.GetDataSourceStatusProvider().WaitFor(interfaces.DataSourceStateInterrupted, time.Second) assert.True(t, foundIt) - // Ensure that an off status doesn't require the use of a timer. - start = time.Now() - foundIt = p.client.GetDataSourceStatusProvider().WaitFor(interfaces.DataSourceStateValid, time.Hour*100) - assert.WithinDuration(t, time.Now(), start, time.Millisecond*30) + // A parked synchronizer never becomes valid, so the wait expires. + foundIt = p.client.GetDataSourceStatusProvider().WaitFor(interfaces.DataSourceStateValid, time.Millisecond*100) assert.False(t, foundIt) }, httphelpers.HandlerWithStatus(401)) }) diff --git a/ldclient_sdk_key_test.go b/ldclient_sdk_key_test.go index 82d87b92..67e9ebc5 100644 --- a/ldclient_sdk_key_test.go +++ b/ldclient_sdk_key_test.go @@ -171,7 +171,7 @@ func rejectKeyHandler(rejectedKey string, next http.Handler) http.Handler { }) } -func TestLDRelayApplySDKKeyRestartsFDv2SynchronizersAfterPermanentFailure(t *testing.T) { +func TestLDRelayApplySDKKeyRestartsParkedFDv2Synchronizers(t *testing.T) { data := ldservicesv2.NewServerSDKData().Flags(alwaysTrueFlag) protocol := ldservicesv2.NewStreamingProtocol(). WithIntent(subsystems.ServerIntent{Payload: subsystems.Payload{ @@ -191,17 +191,17 @@ func TestLDRelayApplySDKKeyRestartsFDv2SynchronizersAfterPermanentFailure(t *tes Logging: ldcomponents.Logging().Loggers(sharedtest.NewTestLoggers()), } - // Both synchronizers reject the original key, so the data system turns off. - client, err := MakeCustomClient(testSdkKey, config, time.Second*5) + // Both synchronizers reject the original key, so the data system parks both. + client, err := MakeCustomClient(testSdkKey, config, time.Second) require.Error(t, err) defer client.Close() th.RequireValue(t, requestsCh, time.Second, "timed out waiting for stream request") th.RequireValue(t, requestsCh, time.Second, "timed out waiting for poll request") status := client.GetDataSourceStatusProvider().GetStatus() - require.Equal(t, interfaces.DataSourceStateOff, status.State) + require.Equal(t, interfaces.DataSourceStateInterrupted, status.State) require.Equal(t, 401, status.LastError.StatusCode) - // Change the key. The data system leaves the off state. + // Change the key. require.NoError(t, client.LDRelayApplySDKKey(newTestSdkKey)) // The primary synchronizer starts again with the new key and gets data. @@ -213,7 +213,7 @@ func TestLDRelayApplySDKKeyRestartsFDv2SynchronizersAfterPermanentFailure(t *tes }) } -func TestLDRelayApplySDKKeyWithTheCurrentKeyRestartsFDv2SynchronizersAfterPermanentFailure(t *testing.T) { +func TestLDRelayApplySDKKeyWithTheCurrentKeyRestartsParkedFDv2Synchronizers(t *testing.T) { data := ldservicesv2.NewServerSDKData().Flags(alwaysTrueFlag) protocol := ldservicesv2.NewStreamingProtocol(). WithIntent(subsystems.ServerIntent{Payload: subsystems.Payload{ @@ -241,13 +241,13 @@ func TestLDRelayApplySDKKeyWithTheCurrentKeyRestartsFDv2SynchronizersAfterPerman Logging: ldcomponents.Logging().Loggers(sharedtest.NewTestLoggers()), } - // LaunchDarkly rejects the key, so both synchronizers fail and the data system turns off. - client, err := MakeCustomClient(testSdkKey, config, time.Second*5) + // LaunchDarkly rejects the key, so both synchronizers fail and the data system parks both. + client, err := MakeCustomClient(testSdkKey, config, time.Second) require.Error(t, err) defer client.Close() th.RequireValue(t, requestsCh, time.Second, "timed out waiting for stream request") th.RequireValue(t, requestsCh, time.Second, "timed out waiting for poll request") - require.Equal(t, interfaces.DataSourceStateOff, client.GetDataSourceStatusProvider().GetStatus().State) + require.Equal(t, interfaces.DataSourceStateInterrupted, client.GetDataSourceStatusProvider().GetStatus().State) // LaunchDarkly accepts the key again. A call with the same key starts the synchronizers again. rejecting.Store(false) diff --git a/ldfiledatav2/file_data_source_impl.go b/ldfiledatav2/file_data_source_impl.go index 772ec8e9..aa8828e3 100644 --- a/ldfiledatav2/file_data_source_impl.go +++ b/ldfiledatav2/file_data_source_impl.go @@ -95,7 +95,10 @@ func (fs *fileDataSource) Sync(ds subsystems.DataSelector) <-chan subsystems.Dat // unread rejection cannot block. if fs.closed.Load() || !fs.syncStarted.CompareAndSwap(false, true) { rejected := make(chan subsystems.DataSynchronizerResult, 1) - rejected <- subsystems.DataSynchronizerResult{State: interfaces.DataSourceStateOff} + rejected <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateInterrupted, + UnexpectedFailure: true, + } close(rejected) return rejected } @@ -123,7 +126,15 @@ func (fs *fileDataSource) Sync(ds subsystems.DataSelector) <-chan subsystems.Dat fs.changeSetBroadcaster.RemoveListener(changeSetChan) fs.statusBroadcaster.RemoveListener(statusChan) rejected := make(chan subsystems.DataSynchronizerResult, 1) - rejected <- subsystems.DataSynchronizerResult{State: interfaces.DataSourceStateOff} + rejected <- subsystems.DataSynchronizerResult{ + State: interfaces.DataSourceStateInterrupted, + Error: interfaces.DataSourceErrorInfo{ + Kind: interfaces.DataSourceErrorKindUnknown, + Message: err.Error(), + Time: time.Now(), + }, + UnexpectedFailure: true, + } close(rejected) return rejected } diff --git a/ldfiledatav2/file_data_source_test.go b/ldfiledatav2/file_data_source_test.go index e7355015..35407d8b 100644 --- a/ldfiledatav2/file_data_source_test.go +++ b/ldfiledatav2/file_data_source_test.go @@ -384,7 +384,7 @@ func TestInitializerBuildAndFetchLeaksNoGoroutines(t *testing.T) { }) } -func TestSyncReturnsOffWhenReloaderFactoryFails(t *testing.T) { +func TestSyncReportsUnexpectedFailureWhenReloaderFactoryFails(t *testing.T) { th.WithTempFileData([]byte(`{"flags": {"my-flag": {"on": true}}}`), func(filename string) { f := func(paths []string, loggers ldlog.Loggers, reload func(), closeCh <-chan struct{}) error { return errors.New("no watches available") @@ -395,7 +395,7 @@ func TestSyncReturnsOffWhenReloaderFactoryFails(t *testing.T) { assert.NoError(t, err) defer sync.Close() - // The failure must surface as an Off result rather than a hang. + // The failure must surface as an unexpected failure rather than a hang. results := make(chan subsystems.DataSynchronizerResult, 1) go func() { resultChan := sync.Sync(mocks.NewMockDataSelector(subsystems.NoSelector())) @@ -405,7 +405,8 @@ func TestSyncReturnsOffWhenReloaderFactoryFails(t *testing.T) { }() select { case result := <-results: - assert.Equal(t, interfaces.DataSourceStateOff, result.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, result.State) + assert.True(t, result.UnexpectedFailure) case <-time.After(5 * time.Second): require.FailNow(t, "Sync hung after the reloader factory failed") } @@ -428,7 +429,8 @@ func TestSecondSyncIsRejected(t *testing.T) { secondChan := sync.Sync(mocks.NewMockDataSelector(subsystems.NoSelector())) select { case second := <-secondChan: - assert.Equal(t, interfaces.DataSourceStateOff, second.State) + assert.Equal(t, interfaces.DataSourceStateInterrupted, second.State) + assert.True(t, second.UnexpectedFailure) case <-time.After(5 * time.Second): require.FailNow(t, "second Sync produced no result") } diff --git a/subsystems/data_source.go b/subsystems/data_source.go index e6bcc102..a29b0d34 100644 --- a/subsystems/data_source.go +++ b/subsystems/data_source.go @@ -60,6 +60,12 @@ type DataSynchronizerResult struct { Error interfaces.DataSourceErrorInfo FallbackToFDv1 bool EnvironmentID ldvalue.OptionalString + + // UnexpectedFailure is true when the reported failure will not resolve on retry, such as an HTTP 401. + UnexpectedFailure bool + + // ResetThresholdMet is true when the synchronizer has met its reset threshold. + ResetThresholdMet bool } // DataSynchronizer represents a component capable of obtaining a Basis and subsequent delta updates asynchronously.