Repository navigation
[go, js, rust] Fix context canceled problem in start when stopping #1577
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
190 changes: 190 additions & 0 deletions
190
internal/maintenance/periodic_job_enqueuer_shutdown_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| package maintenance | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "log/slog" | ||
| "os" | ||
| "testing" | ||
| "testing/synctest" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/riverqueue/river/riverdriver" | ||
| "github.com/riverqueue/river/rivershared/riverpilot" | ||
| "github.com/riverqueue/river/rivershared/riversharedtest" | ||
| "github.com/riverqueue/river/rivershared/testsignal" | ||
| "github.com/riverqueue/river/rivertype" | ||
| ) | ||
|
|
||
| type periodicShutdownExecutor struct { | ||
| riverdriver.Executor | ||
|
|
||
| beginFunc func(context.Context) error | ||
| tx *periodicShutdownTx | ||
| } | ||
|
|
||
| func (e *periodicShutdownExecutor) Begin(ctx context.Context) (riverdriver.ExecutorTx, error) { | ||
| if err := e.beginFunc(ctx); err != nil { | ||
| return nil, err | ||
| } | ||
| return e.tx, nil | ||
| } | ||
|
|
||
| type periodicShutdownTx struct { | ||
| riverdriver.ExecutorTx | ||
|
|
||
| commitFunc func(context.Context) error | ||
| rollbackFunc func(context.Context) error | ||
| } | ||
|
|
||
| func (tx *periodicShutdownTx) Commit(ctx context.Context) error { return tx.commitFunc(ctx) } | ||
|
|
||
| func (tx *periodicShutdownTx) Rollback(ctx context.Context) error { return tx.rollbackFunc(ctx) } | ||
|
|
||
| func TestPeriodicJobEnqueuer_ShutdownDuringStagger(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| for _, stopService := range []bool{false, true} { | ||
| t.Run(fmt.Sprintf("StopService=%t", stopService), func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| synctest.Test(t, func(t *testing.T) { | ||
| var logOutput bytes.Buffer | ||
| archetype := riversharedtest.BaseServiceArchetype(t) | ||
| archetype.Logger = slog.New(slog.NewTextHandler(&logOutput, &slog.HandlerOptions{Level: slog.LevelError})) | ||
| var beginCalls, constructorCalls, getAllCalls int | ||
| pilot := NewPilotPeriodicJobMock() | ||
| pilot.PeriodicJobGetAllMock = func(context.Context, riverdriver.Executor, *riverpilot.PeriodicJobGetAllParams) ([]*riverpilot.PeriodicJob, error) { | ||
| getAllCalls++ | ||
| return nil, nil | ||
| } | ||
| svc, err := NewPeriodicJobEnqueuer(archetype, &PeriodicJobEnqueuerConfig{ | ||
| PeriodicJobs: []*PeriodicJob{{ | ||
| ConstructorFunc: func() (*rivertype.JobInsertParams, error) { | ||
| constructorCalls++ | ||
| return &rivertype.JobInsertParams{}, nil | ||
| }, | ||
| RunOnStart: true, | ||
| ScheduleFunc: func(now time.Time) time.Time { return now.Add(time.Hour) }, | ||
| }}, | ||
| Pilot: pilot, | ||
| }, &periodicShutdownExecutor{beginFunc: func(ctx context.Context) error { | ||
| beginCalls++ | ||
| return ctx.Err() | ||
| }}) | ||
| require.NoError(t, err) | ||
|
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| defer cancel() | ||
| var startResult testsignal.TestSignal[error] | ||
| startResult.Init(t) | ||
| go func() { startResult.Signal(svc.Start(ctx)) }() | ||
| // Wait until Start is sleeping in the real stagger, without | ||
| // depending on its randomly selected duration. | ||
| synctest.Wait() | ||
| if stopService { | ||
| svc.Stop() | ||
| } else { | ||
| cancel() | ||
| } | ||
| err = startResult.WaitOrTimeout() | ||
| svc.Stop() | ||
| require.Empty(t, logOutput.String()) | ||
| require.NoError(t, err) | ||
| require.Zero(t, beginCalls) | ||
| require.Zero(t, constructorCalls) | ||
| require.Zero(t, getAllCalls) | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestPeriodicJobEnqueuer_TransactionErrorLogging(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| for _, operation := range []string{"Begin", "Commit", "Insert", "Upsert"} { | ||
| t.Run(operation, func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| for _, outcome := range []string{"Canceled", "DatabaseError", "DriverErrorOnCancellation", "LocalTimeout", "ParentDeadline"} { | ||
| t.Run(outcome, func(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| synctest.Test(t, func(t *testing.T) { | ||
| var logOutput bytes.Buffer | ||
| archetype := riversharedtest.BaseServiceArchetype(t) | ||
| archetype.Logger = slog.New(slog.NewTextHandler(&logOutput, &slog.HandlerOptions{Level: slog.LevelError})) | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| defer cancel() | ||
| if outcome == "ParentDeadline" { | ||
| var cancelDeadline context.CancelFunc | ||
| ctx, cancelDeadline = context.WithTimeout(ctx, time.Second) | ||
| defer cancelDeadline() | ||
| } | ||
| dbErr := errors.New("database failed") | ||
| operationFunc := func(queryCtx context.Context, name string) error { | ||
| if name != operation { | ||
| return nil | ||
| } | ||
| switch outcome { | ||
| case "Canceled": | ||
| cancel() | ||
| return fmt.Errorf("query interrupted: %w", queryCtx.Err()) | ||
| case "DriverErrorOnCancellation": | ||
| cancel() | ||
| return fmt.Errorf("write failed: %w", os.ErrDeadlineExceeded) | ||
| case "LocalTimeout", "ParentDeadline": | ||
| <-queryCtx.Done() | ||
| return queryCtx.Err() | ||
| default: | ||
| return dbErr | ||
| } | ||
| } | ||
| rolledBack := false | ||
| exec := &periodicShutdownExecutor{ | ||
| beginFunc: func(ctx context.Context) error { return operationFunc(ctx, "Begin") }, | ||
| tx: &periodicShutdownTx{ | ||
| commitFunc: func(ctx context.Context) error { return operationFunc(ctx, "Commit") }, | ||
| rollbackFunc: func(ctx context.Context) error { | ||
| rolledBack = true | ||
| require.NoError(t, ctx.Err(), "rollback must survive query cancellation") | ||
| return nil | ||
| }, | ||
| }, | ||
| } | ||
| pilot := NewPilotPeriodicJobMock() | ||
| pilot.PeriodicJobUpsertManyMock = func(ctx context.Context, _ riverdriver.Executor, _ *riverpilot.PeriodicJobUpsertManyParams) ([]*riverpilot.PeriodicJob, error) { | ||
| return nil, operationFunc(ctx, "Upsert") | ||
| } | ||
| svc, err := NewPeriodicJobEnqueuer(archetype, &PeriodicJobEnqueuerConfig{ | ||
| Insert: func(ctx context.Context, _ riverdriver.ExecutorTx, _ []*rivertype.JobInsertParams) ([]*rivertype.JobInsertResult, error) { | ||
| return nil, operationFunc(ctx, "Insert") | ||
| }, | ||
| Pilot: pilot, | ||
| }, exec) | ||
| require.NoError(t, err) | ||
| svc.TestSignals.Init(t) | ||
| svc.insertBatch(ctx, []*rivertype.JobInsertParams{{}}, &riverpilot.PeriodicJobUpsertManyParams{ | ||
| Jobs: []*riverpilot.PeriodicJobUpsertParams{{ID: "periodic"}}, | ||
| }, nil) | ||
| switch outcome { | ||
| case "DatabaseError": | ||
| require.Contains(t, logOutput.String(), dbErr.Error()) | ||
| case "LocalTimeout": | ||
| require.Contains(t, logOutput.String(), context.DeadlineExceeded.Error()) | ||
| default: | ||
| require.Empty(t, logOutput.String()) | ||
| } | ||
| require.Equal(t, operation != "Begin", rolledBack) | ||
| svc.TestSignals.InsertedJobs.RequireEmpty() | ||
| svc.TestSignals.PeriodicJobUpserted.RequireEmpty() | ||
| }) | ||
| }) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖 nit: the four
if serviceCtx.Err() == nil { log }guards are the same decision made four times. The other services make it once by havingrunOncereturn an error and logging in the loop. Optional, butinsertBatchcould do the same, which also removes theserviceCtxaliasing:Both call sites (inside
validateInsertRunOnStartAndScheduleNewlyAddedand in the timer branch of the run loop) then use the same shape as the other services:The
ctx.Err()check at the top ofvalidateInsertRunOnStartAndScheduleNewlyAddedshould stay since it also skips calling user constructors.TestPeriodicJobEnqueuer_TransactionErrorLoggingwould need its log assertions adjusted to the single message plus the wrapped cause.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤖 Leaving this optional refactor out of this PR to keep the change focused. The existing transaction error tests cover cancellation, local timeouts, and database failures at each failure point.