repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
insights-bot
github_2023
go
2
nekomeowww
nekomeowww
@@ -53,3 +57,27 @@ func ContainsCJKChar(s string) bool { return false } + +// ReplaceMarkdownTitlesToBoldTexts +func ReplaceMarkdownTitlesToBoldTexts(text string) (string, error) { + exp, err := regexp.Compile(`(?m)^(#){1,6} (.)*(\n)?`) + if err != nil { + return "", err + }
`if` 块下面的逻辑和 `if` 无关了,可以空行
insights-bot
github_2023
go
2
nekomeowww
nekomeowww
@@ -53,3 +57,27 @@ func ContainsCJKChar(s string) bool { return false } + +// ReplaceMarkdownTitlesToBoldTexts +func ReplaceMarkdownTitlesToBoldTexts(text string) (string, error) { + exp, err := regexp.Compile(`(?m)^(#){1,6} (.)*(\n)?`) + if err != nil { + return "", err + } + return exp.ReplaceAllStringFunc(text...
这里为什么要 `println` 呢?
insights-bot
github_2023
go
2
nekomeowww
nekomeowww
@@ -53,3 +57,27 @@ func ContainsCJKChar(s string) bool { return false } + +// ReplaceMarkdownTitlesToBoldTexts +func ReplaceMarkdownTitlesToBoldTexts(text string) (string, error) { + exp, err := regexp.Compile(`(?m)^(#){1,6} (.)*(\n)?`) + if err != nil { + return "", err + } + return exp.ReplaceAllStringFunc(text...
这个写法有点奇怪,能用 `strings.Replace(...)` 吗?
insights-bot
github_2023
go
2
nekomeowww
nekomeowww
@@ -53,3 +57,27 @@ func ContainsCJKChar(s string) bool { return false } + +// ReplaceMarkdownTitlesToBoldTexts +func ReplaceMarkdownTitlesToBoldTexts(text string) (string, error) { + exp, err := regexp.Compile(`(?m)^(#){1,6} (.)*(\n)?`) + if err != nil { + return "", err + } + return exp.ReplaceAllStringFunc(text...
这个写法也有点奇怪,能换成 `strings.TrimPrefix(...)` 吗?
river
github_2023
go
818
riverqueue
bgentry
@@ -360,6 +362,8 @@ type HookWorkBegin interface { // List of middleware interfaces that may be implemented: // - JobInsertMiddleware // - WorkerMiddleware +// +// More operation-specific interfaces may be added in future versions.
Wild bug. We could put the revert of this in its own branch and send it over as a reproduction if we know which repo to open it on?
river
github_2023
others
818
riverqueue
bgentry
@@ -21,82 +12,108 @@ linters: - testpackage # requires tests in test packages like `river_test` # disabled because they're annoying/bad + - cyclop # screams into the void at "cyclomatic complexity" + - funlen # screams when functions are more than 60 lines long; what are we even doing here guys -...
🤣
river
github_2023
others
818
riverqueue
bgentry
@@ -21,82 +12,108 @@ linters: - testpackage # requires tests in test packages like `river_test` # disabled because they're annoying/bad + - cyclop # screams into the void at "cyclomatic complexity" + - funlen # screams when functions are more than 60 lines long; what are we even doing here guys
These are popular in Ruby and Elixir. It makes a bit more sense in Ruby with DSLs and the low cost of extracting tons of little methods, but less so in Go IMO.
river
github_2023
others
818
riverqueue
bgentry
@@ -21,82 +12,108 @@ linters: - testpackage # requires tests in test packages like `river_test` # disabled because they're annoying/bad + - cyclop # screams into the void at "cyclomatic complexity" + - funlen # screams when functions are more than 60 lines long; what are we even doing here guys -...
intentional non-alphabetical resorts of attr ordering in here? There's a whole bunch of them.
river
github_2023
go
818
riverqueue
bgentry
@@ -99,10 +99,12 @@ func JobList(ctx context.Context, exec riverdriver.Executor, params *JobListPara for i, orderBy := range params.OrderBy { orderByBuilder.WriteString(orderBy.Expr) - if orderBy.Order == SortOrderAsc { + switch orderBy.Order { + case SortOrderAsc: orderByBuilder.WriteString(" ASC") - } ...
Maybe this should actually be an error 🤔
river
github_2023
go
814
riverqueue
bgentry
@@ -27,6 +32,47 @@ func BaseServiceArchetype(tb testing.TB) *baseservice.Archetype { } } +// A pool and mutex to protect it, lazily initialized by TestTx. Once open, this +// pool is never explicitly closed, instead closing implicitly as the package +// tests finish. +var ( + dbPool *pgxpool.Pool //nolint:gochec...
I wonder if this should take an arg for DB URL rather than assuming a particular env? It makes it slightly more verbose to use but also much more flexible if other projects want to use their own schemas and DBs instead of sharing those used by the main River test suite. It could even `require.NotEmpty` on the URL so...
river
github_2023
go
814
riverqueue
bgentry
@@ -48,6 +94,69 @@ func LoggerWarn(tb testing.TB) *slog.Logger { return slogtest.NewLogger(tb, &slog.HandlerOptions{Level: slog.LevelWarn}) } +// TestTx starts a test transaction that's rolled back automatically as the test +// case is cleaning itself up. +// +// This variant uses the default database pool from DB...
This of course means this rollback could hang ~indefinitely since it no longer inherits cancellation from `tb.Context()`, but that's probably fine within a test suite. Worst case you could re-apply a moderate timeout here.
river
github_2023
go
815
riverqueue
bgentry
@@ -6,6 +6,9 @@ import ( "github.com/riverqueue/river/rivertype" ) +// MiddlewareDefaults should be embedded on any middleware implementation. It +// helps identify a struct as middleware, and guarantee forward compatibility in
Might be slightly more readable as "guarantees": ```suggestion // helps identify a struct as middleware, and guarantees forward compatibility in ```
river
github_2023
go
808
riverqueue
bgentry
@@ -26,6 +27,10 @@ func main() { } func run() error { + // Allows secondary River repositories to make use of this command by + // specifying their own prefix. + packagePrefix := cmp.Or(os.Getenv("PACKAGE_PREFIX"), "github.com/riverqueue/river")
Could just make this a required input and skip having a default value? Your call.
river
github_2023
others
807
riverqueue
bgentry
@@ -1,16 +1,17 @@ module github.com/riverqueue/river/cmd/river go 1.22.0
should we think about bumping this next release, or not until really needed?
river
github_2023
go
804
riverqueue
bgentry
@@ -368,6 +412,9 @@ func (c *Config) validate() error { if c.MaxAttempts < 0 { return errors.New("MaxAttempts cannot be less than zero") } + if len(c.Middleware) > 0 && (len(c.JobInsertMiddleware) > 0 || len(c.WorkerMiddleware) > 0) { + return errors.New("only set one of JobInsertMiddleware/WorkerMiddleware or ...
feels like there's some missing words here like "is allowed" or "may be provided", or even just an initial prefix of "can"
river
github_2023
go
804
riverqueue
bgentry
@@ -13,6 +14,19 @@ import ( // helpers aren't included in Godoc and keep each example more succinct. // +type NoOpArgs struct{} + +func (NoOpArgs) Kind() string { return "no_op" } + +type NoOpWorker struct { + river.WorkerDefaults[NoOpArgs] +} + +func (w *NoOpWorker) Work(ctx context.Context, job *river.Job[NoOpArg...
At one point (during the extraction of the `internal/jobexecutor` package) I had an internal package of `testworker` which might be a useful home for these if they can be leveraged elsewhere. Of course you can't use them from `package river` tests because of the circular dependency due to the `river.Job` argument and `...
river
github_2023
go
789
riverqueue
bgentry
@@ -1510,6 +1523,28 @@ func (c *Client[TTx]) insertManyShared( execute func(context.Context, []*riverdriver.JobInsertFastParams) ([]*rivertype.JobInsertResult, error), ) ([]*rivertype.JobInsertResult, error) { doInner := func(ctx context.Context) ([]*rivertype.JobInsertResult, error) { + for _, params := range in...
I did something similar with unique jobs for extracting `river:"unique"` struct field tags: https://github.com/riverqueue/river/blob/2b277cb050d5fb7c890fcf13bd48ec2358577c6c/internal/dbunique/unique_fields.go#L92-L117 Obviously since these are things that aren't supposed to change at runtime you can do this once per...
river
github_2023
go
789
riverqueue
bgentry
@@ -270,6 +270,55 @@ type JobInsertParams struct { UniqueStates byte } +// Hook is an arbitrary interface for a plugin "hook" which will execute some +// arbitrary code at a predefined step in the job lifecycle. +// +// This interface is left purposely non-specific. Hook structs should embed +// river.HookDefaults...
I'm not really vibing with the naming here. I assume the intention is to keep them sortable by event type (insert vs work) but the names feel unintuitive and not as descriptive as I'd hope. For example `BeforeInsert` feels obvious as to its timing (right before an insert), where as `InsertBegin` is not as obvious to me...
river
github_2023
go
789
riverqueue
bgentry
@@ -1510,6 +1521,24 @@ func (c *Client[TTx]) insertManyShared( execute func(context.Context, []*riverdriver.JobInsertFastParams) ([]*rivertype.JobInsertResult, error), ) ([]*rivertype.JobInsertResult, error) { doInner := func(ctx context.Context) ([]*rivertype.JobInsertResult, error) { + for _, params := range in...
Maybe this isn't worth being the one thing that pushes us to fully drop 1.22 support, but we're well within our "2 most recent Go versions" policy to support only 1.23+.
river
github_2023
go
789
riverqueue
bgentry
@@ -24,6 +24,19 @@ type JobArgs interface { Kind() string } +type JobArgsWithHooks interface { + // Hooks returns specific hooks to run for this job type. These will run + // after the global hooks configured on the client. + // + // Warning: Hooks returned should be based on the job type only and be + // invarian...
```suggestion // invariant of the specific contents of a job. Hooks are extracted by ```
river
github_2023
others
795
riverqueue
bgentry
@@ -7,14 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Changed - ⚠️ Version 0.19.0 has minor breaking changes for the `Worker.Middleware`, introduced fairly recently in 0.17.0. We tried not to make this change, but found the existing middleware inte...
Not even sure this needs to be in here as there's no user-facing impact, but if you keep it: ```suggestion - `JobList` has been reimplemented to use sqlc. [PR #795](https://github.com/riverqueue/river/pull/795). ```
river
github_2023
go
799
riverqueue
bgentry
@@ -110,9 +110,19 @@ func (r *Replacer) Run(ctx context.Context, sql string, args []any) (string, []a // RunSafely is the same as Run, but returns an error in case of missing or // extra templates. func (r *Replacer) RunSafely(ctx context.Context, sql string, args []any) (string, []any, error) { - // If nothing pres...
Switch statements are executed top-to-bottom, so maybe you want this fast path short circuit to go first?
river
github_2023
go
794
riverqueue
bgentry
@@ -0,0 +1,239 @@ +// Package sqlctemplate provides a way of making arbitrary text replacement in +// sqlc queries which normally only allow parameters which are in places valid +// in a prepared statement. For example, it can be used to insert a schema name +// as a prefix to tables referenced in sqlc, which is otherw...
Is this actually true @brandur? I have some comments in another branch that I would actually love to be stripped out of the final query, but they're not, regardless of whether they're on a `--` or `/* */` comment line all by themselves.
river
github_2023
go
783
riverqueue
bgentry
@@ -183,16 +184,31 @@ func (e *JobExecutor) execute(ctx context.Context) (res *jobExecutorResult) { return &jobExecutorResult{Err: &rivertype.UnknownJobKindError{Kind: e.JobRow.Kind}, MetadataUpdates: metadataUpdates} } + // Unmarshal jobs early so that they can be used in places like allowing a + // custom args...
I'm trying to think about the potential downsides of this. Obviously calling unmarshal twice isn't great, though this shouldn't have a high cost. And if we want to continue to allow args-driven timeouts, then you'd have to do any pre-processing of args _before_ calling the job timeout. I think this means that encrypted...
river
github_2023
go
783
riverqueue
bgentry
@@ -183,16 +184,31 @@ func (e *JobExecutor) execute(ctx context.Context) (res *jobExecutorResult) { return &jobExecutorResult{Err: &rivertype.UnknownJobKindError{Kind: e.JobRow.Kind}, MetadataUpdates: metadataUpdates} } + // Unmarshal jobs early so that they can be used in places like allowing a + // custom args...
Huh, I think I fixed #752 as part of 0132e537ab49246431f4b021f4287ab53ee75f48 / #753 without explicitly calling it out. Looks like it's now applying the timeout to the entire chain.
river
github_2023
go
783
riverqueue
bgentry
@@ -183,16 +183,21 @@ func (e *JobExecutor) execute(ctx context.Context) (res *jobExecutorResult) { return &jobExecutorResult{Err: &rivertype.UnknownJobKindError{Kind: e.JobRow.Kind}, MetadataUpdates: metadataUpdates} } - if err := e.WorkUnit.UnmarshalJob(); err != nil { - return &jobExecutorResult{Err: err, Me...
A notable and maybe unintentional change here: the context passed to middleware is no longer being cancelled at any point, because you're only canceling the innermost context given to the worker's `Work()`. Maybe this should be resolved by adding a `context.WithCancel()` and `defer cancel()` up at the top of `execute()...
river
github_2023
go
758
riverqueue
brandur
@@ -1 +1,266 @@ package riverdriver + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/riverqueue/river/rivertype" +) + +func TestJobSetStateCancelled(t *testing.T) { + t.Parallel() + + t.Run("EmptyMetadata", func(t *testing.T) { + t.Parallel() + id := int64(1) + finalizedAt ...
```suggestion t.Run("EmptyMetadata", func(t *testing.T) { ```
river
github_2023
others
758
riverqueue
brandur
@@ -487,24 +489,35 @@ updated_job AS ( finalized_at = CASE WHEN job_to_update.should_cancel THEN now() WHEN job_to_update.finalized_at_do_update THEN job_to_update.finalized_at ELSE river_job.finalized_at END, - metadata = CASE WHEN job_to_up...
```suggestion AND river_job.id NOT IN (SELECT id FROM updated_running) AND river_job.state != 'running' AND job_to_update.metadata_do_merge ```
river
github_2023
go
758
riverqueue
brandur
@@ -136,6 +140,14 @@ type JobRow struct { UniqueStates []JobState } +// Output returns the previously recorded output for the job, if any. +func (j *JobRow) Output() []byte { + if !gjson.GetBytes(j.Metadata, MetadataKeyOutput).Exists() { + return nil + } + return []byte(gjson.GetBytes(j.Metadata, MetadataKeyOutpu...
You're repeating the same work here twice by invoking into `GetBytes()`.
river
github_2023
go
758
riverqueue
brandur
@@ -0,0 +1,24 @@ +package river + +import ( + "context" + "encoding/json" + "errors" + + "github.com/riverqueue/river/rivertype" +) + +func RecordOutput(ctx context.Context, output any) error {
I don't think I'm quite wrapping my head around this API — is the expectation is that users keep some sort of persistent object around that they continue to append to as the job goes, then call `RecordOutput` at the end of each of their job functions? If so, a couple things: * Isn't that pretty inconvenient? You'...
river
github_2023
go
758
riverqueue
brandur
@@ -312,54 +312,111 @@ type JobScheduleResult struct { // running job. Use one of the constructors below to ensure a correct // combination of parameters. type JobSetStateIfRunningParams struct { - ID int64 - Attempt *int - ErrData []byte - FinalizedAt *time.Time - ScheduledA...
Any way we can inline these with the struct initialization below instead of setting a local variable everywhere? I'm sure the compiler will optimize it out anyway, but just makes the code more unsightly/harder to read IMO. (Also applies to the other six functions below.)
river
github_2023
go
758
riverqueue
brandur
@@ -7,8 +7,12 @@ import ( "context" "errors" "time" + + "github.com/tidwall/gjson" ) +const MetadataKeyOutput = "output"
Let's maybe put a token docstring on this just given it's a public API export.
river
github_2023
go
774
riverqueue
brandur
@@ -131,7 +131,7 @@ func (e *JobExecutor) execute(ctx context.Context) (res *jobExecutorResult) { ) res = &jobExecutorResult{ - PanicTrace: string(debug.Stack()), + PanicTrace: captureStackTraceSkipFrames(4),
Oof, it's good there's a test for this because it'd be pretty shaky otherwise. The raw number "4" probably merits a comment.
river
github_2023
go
774
riverqueue
brandur
@@ -325,3 +325,25 @@ func (e *JobExecutor) reportError(ctx context.Context, res *jobExecutorResult) { e.Logger.ErrorContext(ctx, e.Name+": Failed to report error for job", logAttrs...) } } + +// captureStackTrace returns a formatted stack trace string starting after +// skipping the specified number of frames. Th...
I assume the formatting comes from what `debug.Stack()` would be doing? A little unfortunate that we have to format it manually here.
river
github_2023
go
775
riverqueue
brandur
@@ -22,6 +22,40 @@ type testArgs struct { func (testArgs) Kind() string { return "rivertest_work_test" } +func TestWorker_NewWorker(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + type testBundle struct { + config *river.Config + driver *riverpgxv5.Driver + tx pgx.Tx + } + + setup := func...
Nit, but found the casing a bit awkward to read. Really doesn't need the "A" anyway: ```suggestion t.Run("HandlesNilRiverConfig", func(t *testing.T) { ```
river
github_2023
go
766
riverqueue
brandur
@@ -70,86 +74,129 @@ func NewWorker[T river.JobArgs, TTx any](tb testing.TB, driver riverdriver.Drive } } +func (w *Worker[T, TTx]) insertJob(ctx context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) *rivertype.JobRow { + tb.Helper() + + result, err := w.client.InsertTx(ctx, tx, args, opts) + if ...
This job completer is technically started, so I wonder if we should just skip stopping it too to save the cleanup hook.
river
github_2023
go
766
riverqueue
brandur
@@ -70,86 +74,129 @@ func NewWorker[T river.JobArgs, TTx any](tb testing.TB, driver riverdriver.Drive } } +func (w *Worker[T, TTx]) insertJob(ctx context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) *rivertype.JobRow { + tb.Helper() + + result, err := w.client.InsertTx(ctx, tx, args, opts) + if ...
Would be a very minor saving, but I wonder if we should let this tolerate a `nil` subscribe channel so we can skip the allocation and the frontmatter code.
river
github_2023
go
766
riverqueue
brandur
@@ -58,48 +80,43 @@ func TestWorker_Work(t *testing.T) { return nil }) - tw := NewWorker(t, driver, config, worker) - require.NoError(t, tw.Work(context.Background(), t, testArgs{Value: "test"}, nil)) + tw := NewWorker(t, bundle.driver, bundle.config, worker) + res, err := tw.Work(context.Background(), t, ...
Maybe replace this `context.Background()` with `ctx` since it's broadly defined now, and it cleans up a lot of visual noise.
river
github_2023
go
765
riverqueue
bgentry
@@ -77,12 +78,62 @@ func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, args T, opts * return w.WorkJob(ctx, tb, job) } +// WorkTx allocates a synthetic job with the provided arguments and optional +// insert options, then works it in the given transaction. +func (w *Worker[T, TTx]) WorkTx(ctx contex...
Trying to think of what else should get updated here to be realistic. I guess it's all of these, and not just the state? https://github.com/riverqueue/river/blob/0a8ee30d2e521f8083f2f061a1a3546980e2e99a/riverdriver/riverpgxv5/internal/dbsqlc/river_job.sql#L151-L154 So we should consider both setting those when up...
river
github_2023
go
765
riverqueue
bgentry
@@ -77,12 +78,62 @@ func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, args T, opts * return w.WorkJob(ctx, tb, job) } +// WorkTx allocates a synthetic job with the provided arguments and optional +// insert options, then works it in the given transaction. +func (w *Worker[T, TTx]) WorkTx(ctx contex...
The docs at the top of the file about not touching the database are no longer accurate. On a bigger note though, I'm wondering if we're thinking about this the right way. The original vision here was to not hit the DB which is why we're synthetically creating fake jobs instead of inserting and then working them. If ...
river
github_2023
go
765
riverqueue
bgentry
@@ -163,24 +166,224 @@ func TestWorker_Work(t *testing.T) { }) } +func TestWorker_WorkTx(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + type testBundle struct { + client *river.Client[pgx.Tx] + driver *riverpgxv5.Driver + tx pgx.Tx + workFunc func(ctx context.Context, job *river.J...
> This is a little unfortunate — you still won't be able to use `JobCompleteTx` for the `Work`/`WorkTx` variants because there's no way to inject the ID of the job which should be updated. Can you explain a little more what you mean here? Even if it's a synthetic job, `JobCompleteTx` would still get called—it's just...
river
github_2023
others
762
riverqueue
brandur
@@ -57,6 +57,14 @@ define test-target endef $(foreach mod,$(submodules),$(eval $(call test-target,$(mod)))) +.PHONY: test/race +test/race:: ## Run test suite for all submodules with race detector +define test-race-target + test/race:: ; cd $1 && go test ./... -p 1 -race +endef
What's going on here?
river
github_2023
go
760
riverqueue
bgentry
@@ -18,7 +18,7 @@ func TestNeverSchedule(t *testing.T) { t.Parallel() schedule := NeverSchedule() - require.Equal(t, time.Unix(1<<63-1, 0), schedule.Next(time.Now())) + require.Equal(t, time.Unix(1<<63-62135596801, 999999999), schedule.Next(time.Now()))
Maybe we should add one more test here to verify that it’s more than 1000 years in the future or something like that?
river
github_2023
others
760
riverqueue
bgentry
@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `riverdatabasesql` driver: properly handle `nil` values in `bytea[]` inputs. This fixes the driver's handling of empty unique keys on insert for non-unique jobs with the newer unique jobs implementation. [PR #739](ht...
```suggestion - - `NeverSchedule.Next` now returns the correct maximum time value, ensuring that the periodic job truly never runs. This fixes an issue where an incorrect maximum timestamp was previously used. Thanks Hubert Krauze ([@krhubert](https://github.com/krhubert))! [PR #760](https://github.com/riverqueue/rive...
river
github_2023
go
753
riverqueue
brandur
@@ -0,0 +1,166 @@ +package rivertest + +import ( + "context" + "encoding/json" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/riverqueue/river" + "github.com/riverqueue/river/riverdriver" + "github.com/riverqueue/river/rivershared/util/ptrutil" + "github.com/riverqueue/ri...
Would definitely be nice to be able to share all this with the main package a little better. I could see it being an easy mistake to make to add something in one place and then forget to do the other.
river
github_2023
go
753
riverqueue
brandur
@@ -0,0 +1,218 @@ +package rivertest + +import ( + "context" + "encoding/json" + "sync/atomic" + "testing" + "time" + + "github.com/riverqueue/river" + "github.com/riverqueue/river/internal/dbunique" + "github.com/riverqueue/river/internal/execution" + "github.com/riverqueue/river/riverdriver" + "github.com/riverqueue/...
> I opted to make a separate helper method for working a job with custom insert opts because (1) I expect the vast majority of use cases won't need to care about this and will only care about worker + args, and (2) the much more common use case will benefit from not needing to specify `, nil` at the end of every call. ...
river
github_2023
go
753
riverqueue
brandur
@@ -0,0 +1,218 @@ +package rivertest + +import ( + "context" + "encoding/json" + "sync/atomic" + "testing" + "time" + + "github.com/riverqueue/river" + "github.com/riverqueue/river/internal/dbunique" + "github.com/riverqueue/river/internal/execution" + "github.com/riverqueue/river/riverdriver" + "github.com/riverqueue/...
Discussed a bit on Slack. Option (2) seems to be the most plausible, although stubbing out real functionality that'd otherwise hit a DB or do so something else in the real world is always a little icky. Hopefully though this is a special case where `river.JobCompleteTx` is already tested so well that it's not as necess...
river
github_2023
go
753
riverqueue
brandur
@@ -0,0 +1,223 @@ +package rivertest + +import ( + "context" + "encoding/json" + "sync/atomic" + "testing" + "time" + + "github.com/riverqueue/river" + "github.com/riverqueue/river/internal/dbunique" + "github.com/riverqueue/river/internal/execution" + "github.com/riverqueue/river/riverdriver" + "github.com/riverqueue/...
We can probably punt on this, but it'd probably make sense to have a test or something that'd make sure users have a sane way to do this. `JobCompleteTx` will probably refuse to complete the job unless it's `running`, and there might not be that easy of a way to manipulate a job from `available` to `running` right n...
river
github_2023
go
754
riverqueue
brandur
@@ -0,0 +1,33 @@ +package rivertype + +import "time" + +// TimeGenerator generates a current time in UTC. In test environments it's +// implemented by riverinternaltest.timeStub which lets the current time be +// stubbed. Otherwise, it's implemented as UnStubbableTimeGenerator which +// doesn't allow stubbing. +type Ti...
I don't think users will ever need to access `UnStubbableTimeGenerator` since it's set by default and they'll only want to ever set a mock right? Maybe move this back to `rivershared`.
river
github_2023
go
754
riverqueue
brandur
@@ -0,0 +1,33 @@ +package rivertype + +import "time" + +// TimeGenerator generates a current time in UTC. In test environments it's +// implemented by riverinternaltest.timeStub which lets the current time be +// stubbed. Otherwise, it's implemented as UnStubbableTimeGenerator which +// doesn't allow stubbing. +type Ti...
It feels a little off to require this as part of the interface — it's basically there so we can do shortcuts in tests like this: ``` go archetype := riversharedtest.BaseServiceArchetype(t) archetype.Time.StubNowUTC(time.Now().UTC()) ``` But unlike our test code, users won't be able to do that anyway becaus...
river
github_2023
go
754
riverqueue
brandur
@@ -0,0 +1,48 @@ +package rivertest + +import ( + "sync" + "time" +) + +// TimeStub implements rivertype.TimeGenerator to allow time to be stubbed in +// tests. It is implemented in a thread-safe manner with a mutex, allowing the +// current time to be stubbed at any time with StubNowUTC. +type TimeStub struct { + mu ...
Hm, unless we're going to rename the other two functions, I'd probably leave it. Just seems more consistent.
river
github_2023
go
755
riverqueue
brandur
@@ -148,7 +148,7 @@ func TestBaseCommandSetIntegration(t *testing.T) { buildInfo, _ := debug.ReadBuildInfo() require.Equal(t, strings.TrimSpace(fmt.Sprintf(` -River version (unknown) +River version (devel)
Oh weird. Yeah not sure — it might also just be a minor breaking change I suppose. They released a change to `go vet` (which runs with other Go commands) that bans use of variable strings in printf-like format directives that initially broke our build at work when I upgraded. It wasn't too hard to fix, but I was surpri...
river
github_2023
go
718
riverqueue
brandur
@@ -191,6 +191,11 @@ type Config struct { // than working them. If it's specified, then Workers must also be given. Queues map[string]QueueConfig + // ReindexerIndexes is a list of indexes to reindex on each run of the + // reindexer. If empty, defaults to only the args and metadata GIN indexes + // (river_job_ar...
Especially given that no one's asking for this, IMO better to leave internal for now. Just improves future flexibility and I can't think of a good reason to have a non-default.
river
github_2023
others
718
riverqueue
brandur
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- The reindexer has been enabled. By default, it will reindex only the `river_job_args_index` and `river_jobs_metadata_index` `GIN` indexes, which are more prone to bloat. It will also ...
```suggestion - The reindexer has been enabled. By default, it will reindex only the `river_job_args_index` and `river_jobs_metadata_index` `GIN` indexes, which are more prone to bloat. It will also run daily at midnight UTC by default. Each of these settings can be customized on the `river.Config` type via `Reindexer...
river
github_2023
go
718
riverqueue
brandur
@@ -3656,6 +3656,17 @@ func Test_Client_Maintenance(t *testing.T) { }) } +type runOnceScheduler struct {
Maybe call this a "schedule" instead of a "scheduler" given the existing naming of types like `PeriodicSchedule` and `DefaultReindexerSchedule`.
river
github_2023
go
718
riverqueue
brandur
@@ -3656,6 +3656,17 @@ func Test_Client_Maintenance(t *testing.T) { }) } +type runOnceScheduler struct { + ran atomic.Bool +} + +func (s *runOnceScheduler) Next(time.Time) time.Time { + if !s.ran.Swap(true) { + return time.Now() + } + // Return the maximum future time so that the scheduler doesn't run again. + re...
Fix spacing here (no newline after this function).
river
github_2023
go
718
riverqueue
brandur
@@ -87,6 +87,18 @@ func (s *periodicIntervalSchedule) Next(t time.Time) time.Time { return t.Add(s.interval) } +type neverSchedule struct{} + +func (s *neverSchedule) Next(t time.Time) time.Time { + // Return the maximum future time so that the schedule never runs. + return time.Unix(1<<63-1, 0) +} + +// ScheduleN...
Hrmm, I'm a little mixed on this one. Given that `PeriodicSchedule` is already an external naming scheme, it may be that `NeverSchedule` fits better into that, don't you think? "Never schedule" also flows off the tongue a bit easier.
river
github_2023
go
733
riverqueue
brandur
@@ -905,12 +905,12 @@ func Exercise[TTx any](ctx context.Context, t *testing.T, require.Nil(t, job.AttemptedAt) require.Empty(t, job.AttemptedBy) require.WithinDuration(t, now, job.CreatedAt, 2*time.Second) - require.Equal(t, []byte(`{"encoded": "args"}`), job.EncodedArgs) + require.JSONEq(t, `{"en...
I can already tell it's going to drive me crazy that they didn't called this `JSONEqual` to match all the other existing `Equal` helpers.
river
github_2023
go
731
riverqueue
bgentry
@@ -90,6 +90,17 @@ type Config struct { // Defaults to 7 days. DiscardedJobRetentionPeriod time.Duration + // SkipUnknownJobCheck is a flag to control whether the client should skip + // checking to see if a registered worker exists in the client's worker bundle + // for a job arg prior to insertion. + // + // Th...
We tend to keep struct fields sorted alphabetically unless there's a compelling reason not to. Could you put this down above `TestOnly`?
river
github_2023
go
730
riverqueue
brandur
@@ -377,20 +377,22 @@ func (c *BatchCompleter) handleBatch(ctx context.Context) error { // it's done this way to allocate as few new slices as necessary. mapBatch := func(setStateBatch map[int64]*batchCompleterSetState) *riverdriver.JobSetStateIfRunningManyParams { params := &riverdriver.JobSetStateIfRunningMany...
I found the naming of this one a little odd to read. I see what you did here by making "snooze" come first, but it mightttt be better as the more natural "increment snooze" or maybe "do snooze increment" so there's some kind of verb on the front.
river
github_2023
go
702
riverqueue
bgentry
@@ -164,3 +175,9 @@ func openPgxV5DBPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, er return dbPool, nil } + +func pgEnvConfigured() bool { + // Consider these two vars the bare minimum for an env-based configuration. + // return os.Getenv("PGHOST") != "" && os.Getenv("PGDATABASE") != "" + return os...
Some commented code in here and a comment which only lines up with the commented variant (not the active one)
river
github_2023
go
691
riverqueue
bgentry
@@ -2,31 +2,14 @@ package randutil import ( cryptorand "crypto/rand" - "encoding/binary" "encoding/hex" - mathrand "math/rand" - "sync" + "math/rand/v2" "time" ) -// NewCryptoSeededConcurrentSafeSource generates a new pseudo-random source -// that's been created with a cryptographically secure seed to ensur...
riverpro will need a bump to correspond with these internal API changes
river
github_2023
go
664
riverqueue
gaffneyc
@@ -472,6 +493,11 @@ func (p *producer) innerFetchLoop(workCtx context.Context, fetchResultCh chan pr p.Logger.ErrorContext(workCtx, p.Name+": Error fetching jobs", slog.String("err", result.err.Error())) } else if len(result.jobs) > 0 { p.startNewExecutors(workCtx, result.jobs) + + // Fetch returned t...
It's not clear to me how this is triggered only when a full batch has been returned. Should it only be set to true when `len(results.jobs) == limit`?
river
github_2023
go
584
riverqueue
bgentry
@@ -0,0 +1,47 @@ +package river + +import ( + "context" + + "github.com/riverqueue/river/rivertype" +) + +// JobMiddlewareDefaults is an embeddable struct that provides default +// implementations for the rivertype.JobMiddleware. Use of this struct is +// recommended in case rivertype.JobMiddleware is expanded in the f...
I think for this to be the most useful it would need to be customizable on a per-job basis. I'm wondering what that looks like in practice with this design. Like what if I wanted to add a middleware that uses some aspect of the worker or args to dynamically determine what to do? (maybe some optional interface gets fulf...
river
github_2023
go
584
riverqueue
bgentry
@@ -218,6 +219,128 @@ type AttemptError struct { Trace string `json:"trace"` } +type JobInsertParams struct { + CreatedAt *time.Time + EncodedArgs []byte + Kind string + MaxAttempts int + Metadata []byte + Priority int + Queue string + ScheduledAt *time.Time + State JobState + Tags ...
Makes sense, I think this is probably the cleaner & more flexible option.
river
github_2023
go
584
riverqueue
bgentry
@@ -1405,32 +1424,50 @@ func (c *Client[TTx]) InsertManyTx(ctx context.Context, tx TTx, params []InsertM return c.insertFastMany(ctx, exec, insertParams) } -func (c *Client[TTx]) insertFastMany(ctx context.Context, tx riverdriver.ExecutorTx, insertParams []*riverdriver.JobInsertFastParams) (int, error) { - inserte...
I worry a bit about the number of places where we have to do this kind of struct pointer casting and the potential danger of it. A lot of those are in tests and presumably any issues would be caught by tests, but I still felt like I should point out that it makes me feel a little uneasy.
river
github_2023
go
584
riverqueue
bgentry
@@ -1150,7 +1155,7 @@ func (c *Client[TTx]) ID() string { return c.config.ID } -func insertParamsFromConfigArgsAndOptions(archetype *baseservice.Archetype, config *Config, args JobArgs, insertOpts *InsertOpts) (*riverdriver.JobInsertFastParams, *dbunique.UniqueOpts, error) {
What do you think about pulling arg encoding out of this helper and passing the middleware functions a type that includes raw unencoded `JobArgs`? My thought is that this unlocks more dynamic behavior, because middleware then have the ability to do type assertions against `JobArgs` including to assert interface impleme...
river
github_2023
others
599
riverqueue
bgentry
@@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fixed a panic that'd occur if `StopAndCancel` was invoked before a client was started. [PR #557](https://github.com/riverqueue/river/pull/557). - A `PeriodicJobConstructor` should be able to return `nil` `JobArgs` i...
```suggestion - Fixed a nil pointer exception if `Client.Subscribe` was called when the client had no configured workers (it still, panics with a more instructive error message now). [PR #599](https://github.com/riverqueue/river/pull/599). ```
river
github_2023
go
599
riverqueue
bgentry
@@ -906,6 +906,10 @@ type SubscribeConfig struct { // Special internal variant that lets us inject an overridden size. func (c *Client[TTx]) SubscribeConfig(config *SubscribeConfig) (<-chan *Event, func()) { + if c.subscriptionManager == nil { + panic("created a subscription on a client that will never work jobs (...
```suggestion panic("created a subscription on a client that will never work jobs (Workers not configured)") ```
river
github_2023
go
599
riverqueue
bgentry
@@ -3893,6 +3893,19 @@ func Test_Client_Subscribe(t *testing.T) { require.Empty(t, client.subscriptionManager.subscriptions) }) + + // Just make sure this doesn't fail on a nil pointer exception. + t.Run("SubscribeOnClientWithoutWorkers", func(t *testing.T) { + t.Parallel() + + dbPool := riverinternaltest.Test...
```suggestion require.PanicsWithValue(t, "created a subscription on a client that will never work jobs (Workers not configured)", func() { ```
river
github_2023
go
589
riverqueue
brandur
@@ -286,6 +286,54 @@ func (e *Executor) JobInsertFull(ctx context.Context, params *riverdriver.JobIns return jobRowFromInternal(job) } +func (e *Executor) JobInsertManyReturning(ctx context.Context, params []*riverdriver.JobInsertFastParams) ([]*rivertype.JobRow, error) { + insertJobsParams := &dbsqlc.JobInsertMan...
Should maybe pull this trick into the other `JobInsertMany` in here too.
river
github_2023
go
589
riverqueue
brandur
@@ -118,6 +118,7 @@ type Executor interface { JobInsertFast(ctx context.Context, params *JobInsertFastParams) (*rivertype.JobRow, error) JobInsertFastMany(ctx context.Context, params []*JobInsertFastParams) (int, error) JobInsertFull(ctx context.Context, params *JobInsertFullParams) (*rivertype.JobRow, error) + J...
This one's still kind of a "job insert fast" variant, so that should probably still be in there. I wonder too if we should try to match up which one gets the suffix between the client and driver a little bit more. In the client, the "fast" version gets a suffix, but in the driver here the "returning" variant gets th...
river
github_2023
go
532
riverqueue
brandur
@@ -94,7 +94,7 @@ Provides command line facilities for the River job queue. } addDatabaseURLFlag := func(cmd *cobra.Command, databaseURL *string) { - cmd.Flags().StringVar(databaseURL, "database-url", "", "URL of the database to benchmark (should look like `postgres://...`") + cmd.Flags().StringVar(databaseURL,...
```suggestion cmd.Flags().StringVar(databaseURL, "database-url", "", "URL of the database to benchmark (should look like `postgres://...`") ``` Maybe revert his line ... `postgres://` implies that the `postgresql://` is also supported, and generally it's better if these help lines are terser so they don't line w...
river
github_2023
go
532
riverqueue
brandur
@@ -17,6 +16,16 @@ import ( "github.com/riverqueue/river/rivermigrate" ) +const ( + // Referencing the offical PostgreSQL documentation, it appears that + // `postgresql://` is the default/preferred URI scheme, with `postgres://` + // as the fallback. River accepts both. + // + // See https://www.postgresql.org/do...
Thank you for the comment (usually I think these are quite a good idea), but maybe drop this one. It feels oddly unsure of itself ("it appears that"), and also the naming of the constants make it so obvious what's going on here that I don't think it's really needed.
river
github_2023
go
526
riverqueue
bgentry
@@ -16,6 +16,8 @@ const ( QueueDefault = "default" ) +type ContextKeyClient struct{}
Thoughts on exposing a function here for setting the client on the context, rather than exposing the key itself? That would still make it impossible for that key to be utilized in any way other than by calling the function. And it feels more inline with the common pattern recommended in [the docs](https://pkg.go.dev/co...
river
github_2023
go
526
riverqueue
bgentry
@@ -535,3 +536,12 @@ func failure(t testingT, format string, a ...any) { func failureString(format string, a ...any) string { return "\n River assertion failure:\n " + fmt.Sprintf(format, a...) + "\n" } + +// WorkContext returns a realistic context that can be used to test JobArgs.Work +// implementations. +/...
Do you think this should also attempt to apply timeouts to the context or no? For example there's a default client-level job timeout, as well as the possibility of it being overridden by the worker's `Timeout(job)` method. I did that with my internal job testing helper in the API, but since it's worker-specific mayb...
river
github_2023
others
558
riverqueue
bgentry
@@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Agniva De Sarker
Trying to confirm if this is the correct copyright holder for this bit, where did this name come from?
river
github_2023
go
557
riverqueue
ccoVeille
@@ -491,6 +491,7 @@ func NewClient[TTx any](driver riverdriver.Driver[TTx], config *Config) (*Client uniqueInserter: baseservice.Init(archetype, &dbunique.UniqueInserter{ AdvisoryLockPrefix: config.AdvisoryLockPrefix, }), + workCancel: func(cause error) {}, // replaced on start, but here in case StopAndCance...
for such usecase I would define a `defautWorkCanceler := func(error) {}` Then use it here, it helps to document separately, and using ```suggestion workCancel: defautWorkCanceler // replaced on start ```
river
github_2023
go
537
riverqueue
ccoVeille
@@ -124,7 +125,7 @@ func RunCommand[TOpts CommandOpts](ctx context.Context, bundle *RunCommandBundle ok, err := procureAndRun() if err != nil { - fmt.Fprintf(os.Stderr, "failed: %s\n", err) + fmt.Fprintf(os.Stdout, "failed: %s\n", err)
I'm surprised by this change. If you had used command.StdOut, I might have understand, but here reporting errors to stdout seems strange. Maybe I simply missed something about your PR If it's OK to use stdout here for error reporting, adding an inline comment could help
river
github_2023
go
537
riverqueue
ccoVeille
@@ -69,20 +76,102 @@ var ( testMigrationAll = []rivermigrate.Migration{testMigration01, testMigration02, testMigration03} //nolint:gochecknoglobals ) +type TestDriverProcurer struct{} + +func (p *TestDriverProcurer) ProcurePgxV5(pool *pgxpool.Pool) riverdriver.Driver[pgx.Tx] { + return riverpgxv5.New(pool) +} + +/...
I would have used require.Contains to do not link the test and the templating ```suggestion require.Contains(t, bundle.out.String(), "River version (unknown)") require.Contains(t, bundle.out.String(), "Built with " + buildInfo.GoVersion) ```
river
github_2023
go
529
riverqueue
brandur
@@ -535,16 +535,25 @@ func (p *producer) dispatchWork(workCtx context.Context, count int, fetchResultC func (p *producer) heartbeatLogLoop(ctx context.Context) { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() + type state struct {
I think the naming on this is just a little too generic. Maybe `jobStatistics`?
river
github_2023
go
529
riverqueue
brandur
@@ -535,16 +535,25 @@ func (p *producer) dispatchWork(workCtx context.Context, count int, fetchResultC func (p *producer) heartbeatLogLoop(ctx context.Context) { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() + type state struct { + jobsRan uint64 + jobsActive int + } + prev := state{}
And similarly here too. Maybe: * `cur` -> `curStats` * `prev` -> `prevStats`
river
github_2023
go
529
riverqueue
brandur
@@ -535,16 +535,25 @@ func (p *producer) dispatchWork(workCtx context.Context, count int, fetchResultC func (p *producer) heartbeatLogLoop(ctx context.Context) { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() + type state struct { + jobsRan uint64 + jobsActive int + } + prev := state{} for { ...
Removing the guaranteed tick means this isn't really a heartbeat anymore. Maybe rephrase to? ```suggestion p.Logger.InfoContext(ctx, p.Name+": Producer job stats", ```
river
github_2023
go
529
riverqueue
brandur
@@ -535,16 +535,25 @@ func (p *producer) dispatchWork(workCtx context.Context, count int, fetchResultC func (p *producer) heartbeatLogLoop(ctx context.Context) { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() + type jobCount struct { + ran uint64 + active int + } + var prevCount jobCount for ...
Small, but can you change back to capitalizing the start of sentence? We're pretty consistent on this throughout the rest of the code. ```suggestion p.Logger.InfoContext(ctx, p.Name+": Producer job count changed", ```
river
github_2023
go
529
riverqueue
brandur
@@ -535,16 +535,25 @@ func (p *producer) dispatchWork(workCtx context.Context, count int, fetchResultC func (p *producer) heartbeatLogLoop(ctx context.Context) { ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() + type jobCount struct { + ran uint64 + active int + } + var prevCount jobCount for ...
Can we just make this "counts"? Saying "changed" seems to suggest the log was fired by something changing, which isn't really the case since it's just periodic output. ```suggestion p.Logger.InfoContext(ctx, p.Name+": Producer job counts", ```
river
github_2023
go
528
riverqueue
bgentry
@@ -0,0 +1,124 @@ +// Package main provides a command to help bump the `go/`toolchain` directives
The recommended convention on `main` packages is to name this first word after the program name, rather than `main`: https://tip.golang.org/doc/comment#cmd
river
github_2023
others
522
riverqueue
bgentry
@@ -1,23 +1,23 @@ module github.com/riverqueue/river/cmd/river -go 1.22.5 +go 1.21.13 -// replace github.com/riverqueue/river => ../.. +toolchain go1.22.5 -// replace github.com/riverqueue/river/riverdriver => ../../riverdriver +replace github.com/riverqueue/river => ../.. -// replace github.com/riverqueue/riv...
Is this why setup-go is still upgrading us to 1.22? ``` Setup go version spec 1.21 Found in cache @ /opt/hostedtoolcache/go/1.21.[12](https://github.com/riverqueue/river/actions/runs/10312078359/job/28546717441#step:4:13)/x64 Added go to the path Successfully set up Go version 1.21 go: downloading go1.22.5 (lin...
river
github_2023
go
505
riverqueue
bgentry
@@ -192,6 +192,26 @@ func Exercise[TTx any](ctx context.Context, t *testing.T, exists, err = exec.ColumnExists(ctx, "river_job", "does_not_exist") require.NoError(t, err) require.False(t, exists) + + exists, err = exec.ColumnExists(ctx, "does_not_exist", "id") + require.NoError(t, err) + require.False(t, ex...
Does this pollute the search path for this connection for future tests? Or does the conn pool get thrown away entirely after each test before the test DB goes back into the DB pool?
river
github_2023
others
493
riverqueue
brandur
@@ -242,56 +259,3 @@ jobs: run: | echo "Make sure that all sqlc changes are checked in" make verify/sqlc - - producer_sample:
Just to make sure: you took this out on purpose?
river
github_2023
others
483
riverqueue
brandur
@@ -96,88 +96,94 @@ jobs: run: go test -race ./... -timeout 2m cli: - runs-on: ubuntu-latest - timeout-minutes: 3 + strategy: + matrix: + os: [ubuntu-latest, windows-latest] - services: - postgres: - image: postgres - env: - POSTGRES_PASSWORD: postgres...
Dang, so just TBC, it looks like this will be by far the slowest job now right? (Last run took 4 min, which is 33% slower than the 3 min the test suite takes.) River core's CI is still within reasonable bounds time-wise, although it's pretty slow already. We can see how bad it could get by looking at River UI though...
river
github_2023
others
481
riverqueue
bgentry
@@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Include `pending` state in `JobListParams` by default so pending jobs are included in `JobList` / `JobListTx` results. +- Include `pending` state in `JobListParams` by default so pending jobs are included ...
d'oh, thanks for adding this, forgot to after I opened the PR
river
github_2023
others
481
riverqueue
bgentry
@@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Include `pending` state in `JobListParams` by default so pending jobs are included in `JobList` / `JobListTx` results. +- Include `pending` state in `JobListParams` by default so pending jobs are included ...
```suggestion - Quote strings when using `Client.JobList` functions with the `database/sql` driver. [PR #481](https://github.com/riverqueue/river/pull/481). ```
river
github_2023
go
481
riverqueue
bgentry
@@ -1206,47 +1206,67 @@ func Exercise[TTx any](ctx context.Context, t *testing.T, t.Run("JobList", func(t *testing.T) { t.Parallel() - exec, _ := setup(ctx, t) + t.Run("ListsJobs", func(t *testing.T) { + exec, _ := setup(ctx, t) - now := time.Now().UTC() + now := time.Now().UTC() - job := testfactory...
```suggestion t.Run("QuotesStrings", func(t *testing.T) { ```
river
github_2023
go
481
riverqueue
bgentry
@@ -40,3 +40,33 @@ func TestInterpretError(t *testing.T) { require.ErrorIs(t, interpretError(sql.ErrNoRows), rivertype.ErrNotFound) require.NoError(t, interpretError(nil)) } + +func TestReplacedNamed(t *testing.T) {
```suggestion func TestReplaceNamed(t *testing.T) { ```
river
github_2023
go
481
riverqueue
uniquefine
@@ -364,6 +358,36 @@ func (e *Executor) JobList(ctx context.Context, query string, namedArgs map[stri return mapSliceError(items, jobRowFromInternal) } +// `database/sql` has an `sql.Named` system that should theoretically work for +// named parameters, but neither Pgx or lib/pq implement it, so just use dumb +// ...
I think a case for `[]string` is still missing.
river
github_2023
others
451
riverqueue
bgentry
@@ -14,6 +14,20 @@ go install github.com/riverqueue/river/cmd/river@latest river migrate-up --database-url "$DATABASE_URL" ``` +The migration **includes a new index**. Users with a very large job table may want to consider raising the index separately using `CONCURRENTLY` (which must be run outside of a transaction...
I'm inclined to say this should be a separate migration just so we can add the index concurrently. I don't love that the default of our own tooling is to do a thing which is likely dangerous for large installations. Thoughts?
river
github_2023
others
451
riverqueue
bgentry
@@ -276,9 +278,43 @@ INSERT INTO river_job( @queue, coalesce(sqlc.narg('scheduled_at')::timestamptz, now()), @state, - coalesce(@tags::varchar(255)[], '{}') + coalesce(@tags::varchar(255)[], '{}'), + @unique_key ) RETURNING *; +-- name: JobInsertUnique :one +INSERT INTO river_job( + args, ...
Oh wild, nice trick!
river
github_2023
go
451
riverqueue
bgentry
@@ -272,13 +272,61 @@ func (e *Executor) JobInsertFull(ctx context.Context, params *riverdriver.JobIns ScheduledAt: params.ScheduledAt, State: dbsqlc.RiverJobState(params.State), Tags: params.Tags, + UniqueKey: params.UniqueKey, }) if err != nil { return nil, interpretError(err) } re...
Yeah, I always hate this effect when I want to select one or two little things in addition to the entire row. I sorta wish sqlc adopted an embedded struct for this situation instead of inventing all new structs with a few extra fields.
river
github_2023
others
456
riverqueue
bgentry
@@ -15,4 +15,35 @@ INSERT INTO river_migration SELECT created_at, 'main', version FROM river_migration_old; -DROP TABLE river_migration_old; \ No newline at end of file +DROP TABLE river_migration_old; + +-- +-- Create `river_client` and derivative. +-- +-- This feature hasn't quite yet been implemented, but we're ...
While these are named very similarly, they seem to have very different purposes (if I'm understanding it correctly). One is a historical aggregate stat of how many jobs the client has worked on that queue, while the other is showing a real-time count of in-progress jobs. Almost wondering if we should name it more simil...
river
github_2023
others
456
riverqueue
bgentry
@@ -15,4 +15,35 @@ INSERT INTO river_migration SELECT created_at, 'main', version FROM river_migration_old; -DROP TABLE river_migration_old; \ No newline at end of file +DROP TABLE river_migration_old; + +-- +-- Create `river_client` and derivative. +-- +-- This feature hasn't quite yet been implemented, but we're ...
huh, I've always used and seen `DEFAULT now()` and never seen this form. Maybe we want to stick with `now()` for consistency within the project since we use it elsewhere?