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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions internal/datasourcev2/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
28 changes: 21 additions & 7 deletions internal/datasourcev2/polling_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -112,6 +115,7 @@ func (pp *PollingProcessor) Sync(ds subsystems.DataSelector) <-chan subsystems.D
return false
}
}
consecutiveSuccesses := 0

for {
select {
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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
}
Expand All @@ -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.
Expand All @@ -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,
Expand Down
34 changes: 31 additions & 3 deletions internal/datasourcev2/polling_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down Expand Up @@ -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")
})
}

Expand All @@ -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)
})
Expand Down Expand Up @@ -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)
Expand Down
81 changes: 67 additions & 14 deletions internal/datasourcev2/streaming_data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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() {
Expand All @@ -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:
Expand Down Expand Up @@ -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
}
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

case <-sp.halt:
stream.Close()
return
Expand All @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -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}
}
Expand Down Expand Up @@ -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)

Expand All @@ -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) {
Expand Down
Loading
Loading