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, func(s string) string {
+ println(s) | 这里为什么要 `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, func(s string) string {
+ println(s)
+ // remove hashtag
+ for strings.HasPrefix(s, "#") {
+ s = s[1:]
+ }
+ // remove space
+ s = s[1:] | 这个写法有点奇怪,能用 `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, func(s string) string {
+ println(s)
+ // remove hashtag
+ for strings.HasPrefix(s, "#") { | 这个写法也有点奇怪,能换成 `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
- interfacebloat # we do in fact want >10 methods on the Adapter interface or wherever we see fit.
+ - gocognit # yells that "cognitive complexity" is too high; why
+ - gocyclo # ANOTHER "cyclomatic complexity" checker (see also "cyclop" and "gocyclo")
- godox # bans TODO statements; total non-starter at the moment
- err113 # wants all errors to be defined as variables at the package level; quite obnoxious
+ - maintidx # ANOTHER ANOTHER "cyclomatic complexity" lint (see also "cyclop" and "gocyclo")
- mnd # detects "magic numbers", which it defines as any number; annoying
+ - nestif # yells when if blocks are nested; what planet do these people come from? | 🤣 |
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
- interfacebloat # we do in fact want >10 methods on the Adapter interface or wherever we see fit.
+ - gocognit # yells that "cognitive complexity" is too high; why
+ - gocyclo # ANOTHER "cyclomatic complexity" checker (see also "cyclop" and "gocyclo")
- godox # bans TODO statements; total non-starter at the moment
- err113 # wants all errors to be defined as variables at the package level; quite obnoxious
+ - maintidx # ANOTHER ANOTHER "cyclomatic complexity" lint (see also "cyclop" and "gocyclo")
- mnd # detects "magic numbers", which it defines as any number; annoying
+ - nestif # yells when if blocks are nested; what planet do these people come from?
- ireturn # bans returning interfaces; questionable as is, but also buggy as hell; very, very annoying
- lll # restricts maximum line length; annoying
- nlreturn # requires a blank line before returns; annoying
- wsl # a bunch of style/whitespace stuff; annoying
-linters-settings:
- depguard:
- rules:
- all:
- files: ["$all"]
- allow:
- deny:
- - desc: "Use `github.com/google/uuid` package for UUIDs instead."
- pkg: "github.com/xtgo/uuid"
- not-test:
- files: ["!$test"]
- deny:
- - desc: "Don't use `dbadaptertest` package outside of test environments."
- pkg: "github.com/riverqueue/river/internal/dbadaptertest"
- - desc: "Don't use `riverinternaltest` package outside of test environments."
- pkg: "github.com/riverqueue/river/internal/riverinternaltest"
+ settings:
+ depguard:
+ rules:
+ all:
+ files:
+ - $all
+ deny:
+ - pkg: github.com/xtgo/uuid
+ desc: Use `github.com/google/uuid` package for UUIDs instead. | 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")
- } else if orderBy.Order == SortOrderDesc {
+ case SortOrderDesc:
orderByBuilder.WriteString(" DESC")
+ case SortOrderUnspecified: | 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:gochecknoglobals
+ dbPoolMu sync.RWMutex //nolint:gochecknoglobals
+)
+
+// DBPool gets a lazily initialized database pool for `TEST_DATABASE_URL` or
+// `river_test` if the former isn't specified.
+func DBPool(ctx context.Context, tb testing.TB) *pgxpool.Pool { | 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 the caller doesn't need to use a `mustGetEnv` type util when calling it.
I guess the downside is that this arg would need to cascade down through `TestTx` and `TestTxPool`, whose APIs are more likely to be called in a lot of places. |
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 DBPool that points to
+// `TEST_DATABASE_URL` or `river_test` if the former wasn't specified.
+func TestTx(ctx context.Context, tb testing.TB) pgx.Tx {
+ tb.Helper()
+ return TestTxPool(ctx, tb, DBPool(ctx, tb))
+}
+
+// TestTxPool starts a test transaction that's rolled back automatically as the
+// test case is cleaning itself up.
+//
+// This variant starts the test transaction on the specified database pool.
+func TestTxPool(ctx context.Context, tb testing.TB, dbPool *pgxpool.Pool) pgx.Tx {
+ tb.Helper()
+
+ tx, err := dbPool.Begin(ctx)
+ require.NoError(tb, err)
+
+ tb.Cleanup(func() {
+ // Tests may inerit context from `t.Context()` which is cancelled after
+ // tests run and before calling clean up. We need a non-cancelled
+ // context to issue rollback here, so use a bit of a bludgeon to do so
+ // with `context.WithoutCancel()`.
+ ctx := context.WithoutCancel(ctx) | 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 Middleware (the latter may contain both job insert and worker middleware)") | 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[NoOpArgs]) error {
+ fmt.Printf("NoOpWorker.Work ran\n")
+ return nil
+} | 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.WorkerDefaults`, so maybe limited on where that would be useful. |
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 insertParams {
+ // Global hooks.
+ for _, hook := range c.hooksInsertBegin {
+ if err := hook.InsertBegin(ctx, params); err != nil {
+ return nil, err
+ }
+ }
+
+ // Job specific hooks.
+ //
+ // TODO: Memoize this based on job kind. | 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 arg type and cache that indefinitely. |
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 to inherit an IsAnyHook implementation, then implement one
+// of the more specific hook interfaces like HookInsertBegin or HookWorkBegin. A
+// hook struct may also implement multiple specific hook interfaces which are
+// logically related and benefit from being grouped together.
+//
+// Hooks differ from middleware in that they're invoked at a specific lifecycle
+// phase, but finish immediately instead of wrapping an inner call like a
+// middleware does. One of the main ramifications of this different is that a
+// hook cannot modify context in any useful way to pass down into the stack.
+// Like a normal function, any changes it makes to its context are discarded on
+// return.
+//
+// All else equal, hooks should generally be preferred over middleware because
+// they don't add anything to the call stack. Call stacks that get overly deep
+// can become a bit of an operational nightmare because they get hard to read.
+//
+// In a language with more specific type capabilities, this should be a union
+// type. In Go we implement it somewhat awkwardly so that we can get future
+// extensibility, but also some typing guarantees to prevent misuse (i.e. if
+// Hook was an empty interface, then any object could be passed as a hook, but
+// having a single function to implement forces the caller to make some token
+// motions in the direction of implementing hooks).
+type Hook interface {
+ // IsAnyHook is a sentinel function to check that a type is implementing
+ // Hook on purpose and not by accident (Hook would otherwise be an empty
+ // interface). Hooks should embed river.HookDefaults to pick up an
+ // implementation for this function automatically.
+ IsAnyHook() bool
+}
+
+// HookInsertBegin is an interface to a hook that runs before job insertion.
+type HookInsertBegin interface {
+ Hook
+
+ InsertBegin(ctx context.Context, params *JobInsertParams) error
+}
+
+// HookWorkBegin is an interface to a hook that runs after a job has been locked
+// for work and before it's worked.
+type HookWorkBegin interface {
+ Hook
+
+ WorkBegin(ctx context.Context, job *JobRow) error
+} | 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 (it's not really the "beginning" of the operation").
IMO this is enough of a setback from the alternative names that it warrants breaking the convention of focusing on sort order & autocompletion as the top priority over legibility & intuitiveness. |
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 insertParams {
+ // TODO(brandur): This range clause and the one below it are
+ // identical, and it'd be nice to merge them together, but in such a
+ // way that doesn't require array allocation. I think we can do this
+ // using iterators after we drop support for Go 1.22. | 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
+ // invariant of the specific contents of a job. Hooks are extract by | ```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 interface insufficient to provide the necessary range of functionality we wanted, and this is a secondary middleware facility that won't be in use for many users, so it seemed worthwhile.
### Changed
- The `river.RecordOutput` function now returns an error if the output is too large. The output is limited to 32MB in size. [PR #782](https://github.com/riverqueue/river/pull/782).
- **Breaking change:** The `Worker` interface's `Middleware` function now takes a `JobRow` parameter instead of a generic `Job[T]`. This was necessary to expand the potential of what middleware can do: by letting the executor extract a middleware stack from a worker before a job is fully unmarshaled, the middleware can also participate in the unmarshaling process. [PR #783](https://github.com/riverqueue/river/pull/783).
+- `JobList` has been reimplemented to use sqlc. [PR #XXX](https://github.com/riverqueue/river/pull/XXX). | 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 present in context, short circuit quickly.
- container, containerOK := ctx.Value(contextKey{}).(*contextContainer)
- if !containerOK {
+ var (
+ container, containerOK = ctx.Value(contextKey{}).(*contextContainer)
+ sqlContainsTemplate = strings.Contains(sql, "/* TEMPLATE")
+ )
+ switch {
+ case containerOK && !sqlContainsTemplate:
+ return "", nil, errors.New("sqlctemplate found context container but SQL contains no templates; bug?")
+
+ case !containerOK && sqlContainsTemplate:
+ return "", nil, errors.New("sqlctemplate found template(s) in SQL, but no context container; bug?")
+
+ case !containerOK && !sqlContainsTemplate:
+ // Neither context container or template in SQL; short circuit fast because there's no work to do.
return sql, args, nil | 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 otherwise impossible.
+//
+// Replacement is carried out from within invocations of sqlc's generated DBTX
+// interface, after sqlc generated code runs, but before queries are executed.
+// This is accomplished by implementing DBTX, calling Replacer.Run from within
+// them, and injecting parameters in with WithReplacements (which is unfortunately
+// the only way of injecting them).
+//
+// Templates are modeled as SQL comments so that they're still parseable as
+// valid SQL. An example use of the basic /* TEMPLATE ... */ syntax:
+//
+// -- name: JobCountByState :one
+// SELECT count(*)
+// FROM /* TEMPLATE: schema */river_job
+// WHERE state = @state;
+//
+// An open/close syntax is also available for when SQL is required before
+// processing for the query to be valid. For example, a WHERE or ORDER BY clause
+// can't be empty, so the SQL includes a sentinel value that's parseable which
+// is then replaced later with template values:
+//
+// -- name: JobList :many
+// SELECT *
+// FROM river_job
+// WHERE /* TEMPLATE_BEGIN: where_clause */ 1 /* TEMPLATE_END */
+// ORDER BY /* TEMPLATE_BEGIN: order_by_clause */ id /* TEMPLATE_END */
+// LIMIT @max::int;
+//
+// Be careful not to place a template on a line by itself because sqlc will
+// strip any lines that start with a comment. For example, this does NOT work:
+//
+// -- name: JobList :many
+// SELECT *
+// FROM river_job
+// /* TEMPLATE_BEGIN: where_clause */
+// LIMIT @max::int; | 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-driven job timeout.
if err := e.WorkUnit.UnmarshalJob(); err != nil {
return &jobExecutorResult{Err: err, MetadataUpdates: metadataUpdates}
}
- doInner := execution.MiddlewareChain(e.GlobalMiddleware, e.WorkUnit.Middleware(), e.WorkUnit.Work, e.JobRow)
+ encodedArgs := e.JobRow.EncodedArgs
+ doInner := execution.Func(func(ctx context.Context) error {
+ // The middleware stack is allowed an opportunity to modify EncodedArgs.
+ // If we do detect a modification, unmarshal args again.
+ if bytes.Compare(encodedArgs, e.JobRow.EncodedArgs) != 0 {
+ if err := e.WorkUnit.UnmarshalJob(); err != nil {
+ return err
+ }
+ }
+
+ return e.WorkUnit.Work(ctx) | 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 args would be incompatible with having a job-specific timeout, because you wouldn't have access to the decrypted args when calling `.Timeout()` prior to the middleware chain 🤔 That's not great either as it would complicate the matrix of which features can/can't work together.
This feels a bit like an ordering issue, where we have some middleware (like the one you're working on) which we want to run _first_ before unmarshalling, and then subsequent middleware (application of the job timeout, most other middleware) that would run afterward. I don't know if it's a great idea to add something to the middleware interface to indicate when it should run, but it's an idea that came to mind while thinking about this. |
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-driven job timeout.
if err := e.WorkUnit.UnmarshalJob(); err != nil {
return &jobExecutorResult{Err: err, MetadataUpdates: metadataUpdates}
}
- doInner := execution.MiddlewareChain(e.GlobalMiddleware, e.WorkUnit.Middleware(), e.WorkUnit.Work, e.JobRow)
+ encodedArgs := e.JobRow.EncodedArgs
+ doInner := execution.Func(func(ctx context.Context) error {
+ // The middleware stack is allowed an opportunity to modify EncodedArgs.
+ // If we do detect a modification, unmarshal args again.
+ if bytes.Compare(encodedArgs, e.JobRow.EncodedArgs) != 0 {
+ if err := e.WorkUnit.UnmarshalJob(); err != nil {
+ return err
+ }
+ }
+
+ return e.WorkUnit.Work(ctx)
+ })
+
+ executeFunc := execution.MiddlewareChain(e.GlobalMiddleware, e.WorkUnit.Middleware(), doInner, e.JobRow)
jobTimeout := valutil.FirstNonZero(e.WorkUnit.Timeout(), e.ClientJobTimeout)
ctx, cancel := execution.MaybeApplyTimeout(ctx, jobTimeout)
defer cancel()
- return &jobExecutorResult{Err: doInner(ctx), MetadataUpdates: metadataUpdates}
+ return &jobExecutorResult{Err: executeFunc(ctx), MetadataUpdates: metadataUpdates} | 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, MetadataUpdates: metadataUpdates}
- }
+ doInner := execution.Func(func(ctx context.Context) error {
+ if err := e.WorkUnit.UnmarshalJob(); err != nil {
+ return err
+ }
+
+ jobTimeout := valutil.FirstNonZero(e.WorkUnit.Timeout(), e.ClientJobTimeout)
+ ctx, cancel := execution.MaybeApplyTimeout(ctx, jobTimeout)
+ defer cancel()
+
+ return e.WorkUnit.Work(ctx)
+ })
- doInner := execution.MiddlewareChain(e.GlobalMiddleware, e.WorkUnit.Middleware(), e.WorkUnit.Work, e.JobRow)
- jobTimeout := valutil.FirstNonZero(e.WorkUnit.Timeout(), e.ClientJobTimeout)
- ctx, cancel := execution.MaybeApplyTimeout(ctx, jobTimeout)
- defer cancel() | 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()` so ensure that the context is 100% always canceled for all layers once execution is done? |
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 := time.Now().Truncate(time.Second)
+ errData := []byte("error occurred")
+ result := JobSetStateCancelled(id, finalizedAt, errData, nil)
+ require.Equal(t, id, result.ID)
+ require.Equal(t, errData, result.ErrData)
+ require.NotNil(t, result.FinalizedAt)
+ require.True(t, result.FinalizedAt.Equal(finalizedAt), "expected FinalizedAt to equal %v, got %v", finalizedAt, result.FinalizedAt)
+ require.Nil(t, result.MetadataUpdates)
+ require.False(t, result.MetadataDoMerge)
+ require.Equal(t, rivertype.JobStateCancelled, result.State)
+ })
+
+ t.Run("NonEmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(1)
+ finalizedAt := time.Now().Truncate(time.Second)
+ errData := []byte("error occurred")
+ metadata := []byte(`{"key": "value"}`)
+ result := JobSetStateCancelled(id, finalizedAt, errData, metadata)
+ require.Equal(t, id, result.ID)
+ require.Equal(t, errData, result.ErrData)
+ require.NotNil(t, result.FinalizedAt)
+ require.True(t, result.FinalizedAt.Equal(finalizedAt), "expected FinalizedAt to equal %v, got %v", finalizedAt, result.FinalizedAt)
+ require.Equal(t, metadata, result.MetadataUpdates)
+ require.True(t, result.MetadataDoMerge)
+ require.Equal(t, rivertype.JobStateCancelled, result.State)
+ })
+}
+
+func TestJobSetStateCompleted(t *testing.T) {
+ t.Parallel()
+
+ t.Run("EmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(2)
+ finalizedAt := time.Now().Truncate(time.Second)
+ result := JobSetStateCompleted(id, finalizedAt, nil)
+ require.Equal(t, id, result.ID)
+ require.NotNil(t, result.FinalizedAt)
+ require.True(t, result.FinalizedAt.Equal(finalizedAt))
+ require.True(t, result.FinalizedAt.Equal(finalizedAt), "expected FinalizedAt to equal %v, got %v", finalizedAt, result.FinalizedAt)
+ require.False(t, result.MetadataDoMerge)
+ require.Nil(t, result.MetadataUpdates)
+ require.Equal(t, rivertype.JobStateCompleted, result.State)
+ })
+
+ t.Run("NonEmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(2)
+ finalizedAt := time.Now().Truncate(time.Second)
+ metadata := []byte(`{"key": "value"}`)
+ result := JobSetStateCompleted(id, finalizedAt, metadata)
+ require.Equal(t, id, result.ID)
+ require.NotNil(t, result.FinalizedAt)
+ require.True(t, result.FinalizedAt.Equal(finalizedAt))
+ require.True(t, result.MetadataDoMerge)
+ require.Equal(t, metadata, result.MetadataUpdates)
+ require.Equal(t, rivertype.JobStateCompleted, result.State)
+ })
+}
+
+func TestJobSetStateDiscarded(t *testing.T) {
+ t.Parallel()
+
+ t.Run("EmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(3)
+ finalizedAt := time.Now().Truncate(time.Second)
+ errData := []byte("discard error")
+ result := JobSetStateDiscarded(id, finalizedAt, errData, nil)
+ require.Equal(t, id, result.ID)
+ require.Equal(t, errData, result.ErrData)
+ require.NotNil(t, result.FinalizedAt)
+ require.True(t, result.FinalizedAt.Equal(finalizedAt))
+ require.False(t, result.MetadataDoMerge)
+ require.Nil(t, result.MetadataUpdates)
+ require.Equal(t, rivertype.JobStateDiscarded, result.State)
+ })
+
+ t.Run("NonEmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(3)
+ finalizedAt := time.Now().Truncate(time.Second)
+ errData := []byte("discard error")
+ metadata := []byte(`{"key": "value"}`)
+ result := JobSetStateDiscarded(id, finalizedAt, errData, metadata)
+ require.Equal(t, id, result.ID)
+ require.Equal(t, errData, result.ErrData)
+ require.NotNil(t, result.FinalizedAt)
+ require.True(t, result.FinalizedAt.Equal(finalizedAt))
+ require.Equal(t, metadata, result.MetadataUpdates)
+ require.True(t, result.MetadataDoMerge)
+ require.Equal(t, rivertype.JobStateDiscarded, result.State)
+ })
+}
+
+func TestJobSetStateErrorAvailable(t *testing.T) {
+ t.Parallel()
+
+ t.Run("EmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(4)
+ scheduledAt := time.Now().Truncate(time.Second)
+ errData := []byte("error available")
+ result := JobSetStateErrorAvailable(id, scheduledAt, errData, nil)
+ require.Equal(t, id, result.ID)
+ require.Equal(t, errData, result.ErrData)
+ require.False(t, result.MetadataDoMerge)
+ require.Nil(t, result.MetadataUpdates)
+ require.NotNil(t, result.ScheduledAt)
+ require.True(t, result.ScheduledAt.Equal(scheduledAt))
+ require.Equal(t, rivertype.JobStateAvailable, result.State)
+ })
+
+ t.Run("NonEmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(4)
+ scheduledAt := time.Now().Truncate(time.Second)
+ errData := []byte("error available")
+ metadata := []byte(`{"key": "value"}`)
+ result := JobSetStateErrorAvailable(id, scheduledAt, errData, metadata)
+ require.Equal(t, id, result.ID)
+ require.True(t, result.MetadataDoMerge)
+ require.Equal(t, metadata, result.MetadataUpdates)
+ require.NotNil(t, result.ScheduledAt)
+ require.True(t, result.ScheduledAt.Equal(scheduledAt))
+ require.Equal(t, errData, result.ErrData)
+ })
+}
+
+func TestJobSetStateErrorRetryable(t *testing.T) {
+ t.Parallel()
+
+ t.Run("EmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(5)
+ scheduledAt := time.Now().Truncate(time.Second)
+ errData := []byte("retryable error")
+ result := JobSetStateErrorRetryable(id, scheduledAt, errData, nil)
+ require.Equal(t, id, result.ID)
+ require.False(t, result.MetadataDoMerge)
+ require.Nil(t, result.MetadataUpdates)
+ require.NotNil(t, result.ScheduledAt)
+ require.True(t, result.ScheduledAt.Equal(scheduledAt))
+ require.Equal(t, errData, result.ErrData)
+ require.Equal(t, rivertype.JobStateRetryable, result.State)
+ })
+
+ t.Run("NonEmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(5)
+ scheduledAt := time.Now().Truncate(time.Second)
+ errData := []byte("retryable error")
+ metadata := []byte(`{"key": "value"}`)
+ result := JobSetStateErrorRetryable(id, scheduledAt, errData, metadata)
+ require.Equal(t, id, result.ID)
+ require.True(t, result.MetadataDoMerge)
+ require.Equal(t, metadata, result.MetadataUpdates)
+ require.NotNil(t, result.ScheduledAt)
+ require.True(t, result.ScheduledAt.Equal(scheduledAt))
+ require.Equal(t, errData, result.ErrData)
+ })
+}
+
+func TestJobSetStateSnoozed(t *testing.T) { //nolint:dupl
+ t.Parallel()
+
+ t.Run("EmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+
+ id := int64(6)
+ scheduledAt := time.Now().Truncate(time.Second)
+ attempt := 2
+ result := JobSetStateSnoozed(id, scheduledAt, attempt, nil)
+ require.Equal(t, id, result.ID)
+ require.NotNil(t, result.Attempt)
+ require.Equal(t, attempt, *result.Attempt)
+ require.False(t, result.MetadataDoMerge)
+ require.Nil(t, result.MetadataUpdates)
+ require.NotNil(t, result.ScheduledAt)
+ require.True(t, result.ScheduledAt.Equal(scheduledAt))
+ require.Equal(t, rivertype.JobStateScheduled, result.State)
+ })
+
+ t.Run("NonEmptyMetadata", func(t *testing.T) {
+ t.Parallel()
+ id := int64(6)
+ scheduledAt := time.Now().Truncate(time.Second)
+ attempt := 2
+ metadata := []byte("snoozed metadata")
+ result := JobSetStateSnoozed(id, scheduledAt, attempt, metadata)
+ require.Equal(t, id, result.ID)
+ require.NotNil(t, result.Attempt)
+ require.Equal(t, attempt, *result.Attempt)
+ require.True(t, result.MetadataDoMerge)
+ require.Equal(t, metadata, result.MetadataUpdates)
+ require.NotNil(t, result.ScheduledAt)
+ require.True(t, result.ScheduledAt.Equal(scheduledAt))
+ require.Equal(t, rivertype.JobStateScheduled, result.State)
+ })
+}
+
+func TestJobSetStateSnoozedAvailable(t *testing.T) { //nolint:dupl
+ t.Parallel()
+
+ t.Run("empty metadata", func(t *testing.T) { | ```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_update.snooze_do_increment
- THEN river_job.metadata || jsonb_build_object('snoozes', coalesce((river_job.metadata->>'snoozes')::int, 0) + 1)
+ metadata = CASE WHEN job_to_update.metadata_do_merge
+ THEN river_job.metadata || job_to_update.metadata_updates
ELSE river_job.metadata END,
scheduled_at = CASE WHEN NOT job_to_update.should_cancel AND job_to_update.scheduled_at_do_update THEN job_to_update.scheduled_at
ELSE river_job.scheduled_at END,
state = CASE WHEN job_to_update.should_cancel THEN 'cancelled'::river_job_state
ELSE job_to_update.state END
FROM job_to_update
WHERE river_job.id = job_to_update.id
+ AND river_job.state = 'running'
+ RETURNING river_job.*
+),
+updated_metadata_only AS (
+ UPDATE river_job
+ SET metadata = river_job.metadata || job_to_update.metadata_updates
+ FROM job_to_update
+ WHERE river_job.id = job_to_update.id
+ AND river_job.id NOT IN (SELECT id FROM updated_running)
+ AND river_job.state != 'running'
+ AND job_to_update.metadata_do_merge | ```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, MetadataKeyOutput).Raw) | 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'd have to remember to do that for every worker you made.
* You presumably want to get as much output as possible, so you'd do `RecordOutput` at the bottom of the work function, but doesn't that mean you lose everything if you return early?
I probably would've taken a completely approach for this — given that the project is pretty tied into slog already, I would've added a slog handler that could persist log output to context, and then maybe an easy way to get a per-worker invocation slog logger that'd persist everything the user logged into it after the worker finished up.
Perhaps the difference is that I don't 100% understand what you mean by "output". What kind of data is output do you expect to go in here exactly? |
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
- ScheduledAt *time.Time
- SnoozeDoIncrement bool
- State rivertype.JobState
-}
-
-func JobSetStateCancelled(id int64, finalizedAt time.Time, errData []byte) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, ErrData: errData, FinalizedAt: &finalizedAt, State: rivertype.JobStateCancelled}
-}
-
-func JobSetStateCompleted(id int64, finalizedAt time.Time) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, FinalizedAt: &finalizedAt, State: rivertype.JobStateCompleted}
-}
-
-func JobSetStateDiscarded(id int64, finalizedAt time.Time, errData []byte) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, ErrData: errData, FinalizedAt: &finalizedAt, State: rivertype.JobStateDiscarded}
-}
-
-func JobSetStateErrorAvailable(id int64, scheduledAt time.Time, errData []byte) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, ErrData: errData, ScheduledAt: &scheduledAt, State: rivertype.JobStateAvailable}
-}
-
-func JobSetStateErrorRetryable(id int64, scheduledAt time.Time, errData []byte) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, ErrData: errData, ScheduledAt: &scheduledAt, State: rivertype.JobStateRetryable}
-}
-
-func JobSetStateSnoozed(id int64, scheduledAt time.Time, attempt int) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, Attempt: &attempt, ScheduledAt: &scheduledAt, SnoozeDoIncrement: true, State: rivertype.JobStateScheduled}
-}
-
-func JobSetStateSnoozedAvailable(id int64, scheduledAt time.Time, attempt int) *JobSetStateIfRunningParams {
- return &JobSetStateIfRunningParams{ID: id, Attempt: &attempt, ScheduledAt: &scheduledAt, SnoozeDoIncrement: true, State: rivertype.JobStateAvailable}
+ ID int64
+ Attempt *int
+ ErrData []byte
+ FinalizedAt *time.Time
+ MetadataDoMerge bool
+ MetadataUpdates []byte
+ ScheduledAt *time.Time
+ State rivertype.JobState
+}
+
+func JobSetStateCancelled(id int64, finalizedAt time.Time, errData []byte, metadataUpdates []byte) *JobSetStateIfRunningParams {
+ metadataDoUpdate := len(metadataUpdates) > 0 | 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. The skip parameter should be
+// adjusted so that frames you want to hide (like the ones generated by the
+// tracing functions themselves) are excluded.
+func captureStackTraceSkipFrames(skip int) string {
+ // Allocate room for up to 100 callers; adjust as needed.
+ pcs := make([]uintptr, 100)
+ // Skip the specified number of frames.
+ n := runtime.Callers(skip, pcs)
+ frames := runtime.CallersFrames(pcs[:n])
+
+ var stackTrace string
+ for {
+ frame, more := frames.Next()
+ stackTrace += fmt.Sprintf("%s\n\t%s:%d\n", frame.Function, frame.File, frame.Line) | 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(t *testing.T) *testBundle {
+ t.Helper()
+
+ return &testBundle{
+ config: &river.Config{ID: "rivertest-worker"},
+ driver: riverpgxv5.New(nil),
+ tx: riverinternaltest.TestTx(ctx, t),
+ }
+ }
+
+ t.Run("HandlesANilRiverConfig", func(t *testing.T) { | 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 err != nil {
+ tb.Fatalf("failed to insert job: %s", err)
+ }
+ return result.Job
+}
+
// Work allocates a synthetic job with the provided arguments and optional
// insert options, then works it.
-func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, args T, opts *river.InsertOpts) error {
+func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) error {
tb.Helper()
- job := makeJobFromArgs(tb, w.config, args, opts)
- return w.WorkJob(ctx, tb, job)
+
+ job := w.insertJob(ctx, tb, tx, args, opts)
+ return w.WorkJob(ctx, tb, tx, 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 context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) error {
tb.Helper()
- job := makeJobFromArgs(tb, w.config, args, opts)
+
+ job := w.insertJob(ctx, tb, tx, args, opts)
return w.WorkJobTx(ctx, tb, tx, job)
}
// WorkJob works the provided job. The job must be constructed to be a realistic
// job using external logic prior to calling this method. Unlike the other
// variants, this method offers total control over the job's attributes.
-func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, job *river.Job[T]) error {
+func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, tx TTx, job *rivertype.JobRow) error {
tb.Helper()
-
- var exec riverdriver.Executor
- if w.client.Driver().HasPool() {
- exec = w.client.Driver().GetExecutor()
- }
-
- return w.workJobExec(ctx, tb, exec, job)
+ return w.workJob(ctx, tb, tx, job)
}
// WorkJobTx works the provided job in the given transaction. The job must be
// constructed to be a realistic job using external logic prior to calling this
// method. Unlike the other variants, this method offers total control over the
// job's attributes.
-func (w *Worker[T, TTx]) WorkJobTx(ctx context.Context, tb testing.TB, tx TTx, job *river.Job[T]) error {
+func (w *Worker[T, TTx]) WorkJobTx(ctx context.Context, tb testing.TB, tx TTx, job *rivertype.JobRow) error {
tb.Helper()
- return w.workJobExec(ctx, tb, w.client.Driver().UnwrapExecutor(tx), job)
+ return w.workJob(ctx, tb, tx, job)
}
-func (w *Worker[T, TTx]) workJobExec(ctx context.Context, tb testing.TB, exec riverdriver.Executor, job *river.Job[T]) error {
+func (w *Worker[T, TTx]) workJob(ctx context.Context, tb testing.TB, tx TTx, job *rivertype.JobRow) error {
tb.Helper()
+ exec := w.client.Driver().UnwrapExecutor(tx)
+ subscribeCh := make(chan []jobcompleter.CompleterJobUpdated, 1)
+ archetype := riversharedtest.BaseServiceArchetype(tb)
+ completer := jobcompleter.NewInlineCompleter(archetype, exec, w.client.Pilot(), subscribeCh)
+ tb.Cleanup(completer.Stop) | 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 err != nil {
+ tb.Fatalf("failed to insert job: %s", err)
+ }
+ return result.Job
+}
+
// Work allocates a synthetic job with the provided arguments and optional
// insert options, then works it.
-func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, args T, opts *river.InsertOpts) error {
+func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) error {
tb.Helper()
- job := makeJobFromArgs(tb, w.config, args, opts)
- return w.WorkJob(ctx, tb, job)
+
+ job := w.insertJob(ctx, tb, tx, args, opts)
+ return w.WorkJob(ctx, tb, tx, 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 context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) error {
tb.Helper()
- job := makeJobFromArgs(tb, w.config, args, opts)
+
+ job := w.insertJob(ctx, tb, tx, args, opts)
return w.WorkJobTx(ctx, tb, tx, job)
}
// WorkJob works the provided job. The job must be constructed to be a realistic
// job using external logic prior to calling this method. Unlike the other
// variants, this method offers total control over the job's attributes.
-func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, job *river.Job[T]) error {
+func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, tx TTx, job *rivertype.JobRow) error {
tb.Helper()
-
- var exec riverdriver.Executor
- if w.client.Driver().HasPool() {
- exec = w.client.Driver().GetExecutor()
- }
-
- return w.workJobExec(ctx, tb, exec, job)
+ return w.workJob(ctx, tb, tx, job)
}
// WorkJobTx works the provided job in the given transaction. The job must be
// constructed to be a realistic job using external logic prior to calling this
// method. Unlike the other variants, this method offers total control over the
// job's attributes.
-func (w *Worker[T, TTx]) WorkJobTx(ctx context.Context, tb testing.TB, tx TTx, job *river.Job[T]) error {
+func (w *Worker[T, TTx]) WorkJobTx(ctx context.Context, tb testing.TB, tx TTx, job *rivertype.JobRow) error {
tb.Helper()
- return w.workJobExec(ctx, tb, w.client.Driver().UnwrapExecutor(tx), job)
+ return w.workJob(ctx, tb, tx, job)
}
-func (w *Worker[T, TTx]) workJobExec(ctx context.Context, tb testing.TB, exec riverdriver.Executor, job *river.Job[T]) error {
+func (w *Worker[T, TTx]) workJob(ctx context.Context, tb testing.TB, tx TTx, job *rivertype.JobRow) error {
tb.Helper()
+ exec := w.client.Driver().UnwrapExecutor(tx)
+ subscribeCh := make(chan []jobcompleter.CompleterJobUpdated, 1)
+ archetype := riversharedtest.BaseServiceArchetype(tb)
+ completer := jobcompleter.NewInlineCompleter(archetype, exec, w.client.Pilot(), subscribeCh) | 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, bundle.tx, testArgs{Value: "test"}, nil) | 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 context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) error {
+ tb.Helper()
+ job := makeJobFromArgs(tb, w.config, args, opts)
+ return w.WorkJobTx(ctx, tb, tx, job)
+}
+
// WorkJob works the provided job. The job must be constructed to be a realistic
// job using external logic prior to calling this method. Unlike the other
// variants, this method offers total control over the job's attributes.
func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, job *river.Job[T]) error {
tb.Helper()
+ var exec riverdriver.Executor
+ if w.client.Driver().HasPool() {
+ exec = w.client.Driver().GetExecutor()
+ }
+
+ return w.workJobExec(ctx, tb, exec, job)
+}
+
+// WorkJobTx works the provided job in the given transaction. The job must be
+// constructed to be a realistic job using external logic prior to calling this
+// method. Unlike the other variants, this method offers total control over the
+// job's attributes.
+func (w *Worker[T, TTx]) WorkJobTx(ctx context.Context, tb testing.TB, tx TTx, job *river.Job[T]) error {
+ tb.Helper()
+ return w.workJobExec(ctx, tb, w.client.Driver().UnwrapExecutor(tx), job)
+}
+
+func (w *Worker[T, TTx]) workJobExec(ctx context.Context, tb testing.TB, exec riverdriver.Executor, job *river.Job[T]) error {
+ tb.Helper()
+
+ // Try to transition an existing job row to running, but also tolerate the
+ // row not existing in the database. Most of the time you don't need to
+ // insert a real job row to use this function (it's only necessary if you
+ // want to use `JobCompleteTx`).
+ if exec != nil {
+ updatedJobRow, err := exec.JobUpdate(ctx, &riverdriver.JobUpdateParams{
+ ID: job.ID,
+ StateDoUpdate: true,
+ State: rivertype.JobStateRunning,
+ })
+ if err != nil && !errors.Is(err, rivertype.ErrNotFound) {
+ return err
+ }
+ if updatedJobRow != nil {
+ job.JobRow = updatedJobRow
+ }
+ }
+
+ // Regardless of whether the job was actually in the database, transition it
+ // to running.
+ job.JobRow.State = rivertype.JobStateRunning | 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 updating the job, and also making sure they're set on the actual job struct. |
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 context.Context, tb testing.TB, tx TTx, args T, opts *river.InsertOpts) error {
+ tb.Helper()
+ job := makeJobFromArgs(tb, w.config, args, opts)
+ return w.WorkJobTx(ctx, tb, tx, job)
+}
+
// WorkJob works the provided job. The job must be constructed to be a realistic
// job using external logic prior to calling this method. Unlike the other
// variants, this method offers total control over the job's attributes.
func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, job *river.Job[T]) error {
tb.Helper()
+ var exec riverdriver.Executor
+ if w.client.Driver().HasPool() {
+ exec = w.client.Driver().GetExecutor()
+ }
+
+ return w.workJobExec(ctx, tb, exec, job)
+}
+
+// WorkJobTx works the provided job in the given transaction. The job must be
+// constructed to be a realistic job using external logic prior to calling this
+// method. Unlike the other variants, this method offers total control over the
+// job's attributes.
+func (w *Worker[T, TTx]) WorkJobTx(ctx context.Context, tb testing.TB, tx TTx, job *river.Job[T]) error {
+ tb.Helper()
+ return w.workJobExec(ctx, tb, w.client.Driver().UnwrapExecutor(tx), job)
+}
+
+func (w *Worker[T, TTx]) workJobExec(ctx context.Context, tb testing.TB, exec riverdriver.Executor, job *river.Job[T]) error {
+ tb.Helper()
+
+ // Try to transition an existing job row to running, but also tolerate the
+ // row not existing in the database. Most of the time you don't need to
+ // insert a real job row to use this function (it's only necessary if you
+ // want to use `JobCompleteTx`).
+ if exec != nil {
+ updatedJobRow, err := exec.JobUpdate(ctx, &riverdriver.JobUpdateParams{
+ ID: job.ID,
+ StateDoUpdate: true,
+ State: rivertype.JobStateRunning,
+ })
+ if err != nil && !errors.Is(err, rivertype.ErrNotFound) {
+ return err
+ }
+ if updatedJobRow != nil {
+ job.JobRow = updatedJobRow
+ }
+ } | 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 we're going to start making DB queries in most cases regardless of whether it's a real job or a fake one, is that original design still reasonable?
I'm also a little worried about the potential to introduce test flakiness by attempting to update a job whose ID was synthetically generated from the in-memory sequence as it may correspond to a real (but different) job in the table.
Perhaps we should just go all in by always using transactions and always inserting real job records? We could even leverage the inline completer after execution. I think that might resolve any potential functionality issues I can think of—although we'd probably need to extract some of the executor logic to be able to reuse it here. |
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.Job[testArgs]) error
+ }
+
+ setup := func(t *testing.T) (*Worker[testArgs, pgx.Tx], *testBundle) {
+ t.Helper()
+
+ var (
+ config = &river.Config{}
+ driver = riverpgxv5.New(nil)
+ )
+
+ client, err := river.NewClient(driver, config)
+ require.NoError(t, err)
+
+ bundle := &testBundle{
+ client: client,
+ driver: driver,
+ tx: riverinternaltest.TestTx(ctx, t),
+ workFunc: func(ctx context.Context, job *river.Job[testArgs]) error { return nil },
+ }
+
+ worker := river.WorkFunc(func(ctx context.Context, job *river.Job[testArgs]) error {
+ return bundle.workFunc(ctx, job)
+ })
+
+ return NewWorker(t, driver, config, worker), bundle
+ }
+
+ t.Run("Success", func(t *testing.T) {
+ t.Parallel()
+
+ testWorker, bundle := setup(t)
+
+ bundle.workFunc = func(ctx context.Context, job *river.Job[testArgs]) error {
+ require.Equal(t, rivertype.JobStateRunning, job.State)
+ return nil
+ }
+
+ require.NoError(t, testWorker.WorkTx(ctx, t, bundle.tx, testArgs{}, nil))
+ })
+} | > 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 that it will error because the job doesn't actually exist, right? Maybe that was a mistake and we should just go all in w/ inserting real job rows.
|
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](https://github.com/riverqueue/river/pull/739).
- `JobCompleteTx` now returns `rivertype.ErrNotFound` if the job doesn't exist instead of panicking. [PR #753](https://github.com/riverqueue/river/pull/753).
+- - `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. [PR #760](https://github.com/riverqueue/river/pull/760) | ```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/river/pull/760)
``` |
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/river/rivershared/util/valutil"
+ "github.com/riverqueue/river/rivertype"
+)
+
+type Worker[T river.JobArgs, TTx any] struct {
+ client *river.Client[TTx]
+ config *river.Config
+ worker river.Worker[T]
+}
+
+func NewWorker[T river.JobArgs, TTx any](t *testing.T, driver riverdriver.Driver[TTx], config *river.Config, worker river.Worker[T]) *Worker[T, TTx] {
+ t.Helper()
+
+ config = config.WithDefaults()
+ client, err := river.NewClient(driver, config)
+ require.NoError(t, err)
+
+ return &Worker[T, TTx]{
+ client: client,
+ config: config,
+ worker: worker,
+ }
+}
+
+func (w *Worker[T, TTx]) Work(ctx context.Context, t *testing.T, args T) error {
+ t.Helper()
+ return w.WorkOpts(ctx, t, args, nil)
+}
+
+func (w *Worker[T, TTx]) WorkJob(ctx context.Context, t *testing.T, job *river.Job[T]) error {
+ t.Helper()
+ return w.WorkJobOpts(ctx, t, job, nil)
+}
+
+func (w *Worker[T, TTx]) WorkJobOpts(ctx context.Context, t *testing.T, job *river.Job[T], opts *river.InsertOpts) error {
+ t.Helper()
+
+ // populate river client into context:
+ ctx = WorkContext(ctx, w.client)
+
+ doInner := w.buildMiddlewareChain(job)
+ return doInner(ctx)
+}
+
+func (w *Worker[T, TTx]) WorkOpts(ctx context.Context, t *testing.T, args T, opts *river.InsertOpts) error {
+ t.Helper()
+
+ job, err := makeJobFromArgs(t, w.config, args, opts)
+ if err != nil {
+ return err
+ }
+
+ return w.WorkJobOpts(ctx, t, job, opts)
+}
+
+func (w *Worker[T, TTx]) buildMiddlewareChain(job *river.Job[T]) func(ctx context.Context) error {
+ // apply global middleware from client, as well as worker-specific middleware
+ workerMiddleware := w.worker.Middleware(job)
+
+ doInner := func(ctx context.Context) error {
+ jobTimeout := w.worker.Timeout(job)
+ if jobTimeout == 0 {
+ jobTimeout = w.config.JobTimeout
+ }
+
+ // No timeout if a -1 was specified.
+ // TODO: is this timeout being applied in the wrong place? Should it apply
+ // on the *outside* of all middleware?
+ if jobTimeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, jobTimeout)
+ defer cancel()
+ }
+
+ return w.worker.Work(ctx, job)
+ } | 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/river/rivershared/baseservice"
+ "github.com/riverqueue/river/rivershared/testfactory"
+ "github.com/riverqueue/river/rivershared/util/ptrutil"
+ "github.com/riverqueue/river/rivershared/util/sliceutil"
+ "github.com/riverqueue/river/rivershared/util/valutil"
+ "github.com/riverqueue/river/rivertype"
+)
+
+// Worker makes it easier to test river workers. Once built, the worker can be
+// used to work any number of synthetic jobs without touching the database:
+//
+// worker := rivertest.NewWorker(t, driver, config, worker)
+// if err := worker.Work(ctx, t, args); err != nil {
+// t.Fatalf("failed to work job: %s", err)
+// }
+//
+// if err := worker.WorkOpts(ctx, t, args, river.InsertOpts{Queue: "custom_queue"}); err != nil {
+// t.Fatalf("failed to work job: %s", err)
+// }
+//
+// In all cases the underlying [river.Worker] will be called with the synthetic
+// job. The execution environment has a realistic River context with access to
+// all River features, including [river.ClientFromContext] and worker
+// middleware.
+type Worker[T river.JobArgs, TTx any] struct {
+ client *river.Client[TTx]
+ config *river.Config
+ worker river.Worker[T]
+}
+
+// NewWorker creates a new test Worker for testing the provided [river.Worker].
+// The worker uses the provided driver and River config to populate default
+// values on test jobs and to configure the execution environment.
+//
+// The database is not required to use this helper, and a pool-less driver is
+// recommended for most usage. This enables individual test cases to run in
+// parallel and with full isolation, even using a single shared `Worker`
+// instance across many test cases.
+func NewWorker[T river.JobArgs, TTx any](tb testing.TB, driver riverdriver.Driver[TTx], config *river.Config, worker river.Worker[T]) *Worker[T, TTx] {
+ tb.Helper()
+
+ config = config.WithDefaults()
+ client, err := river.NewClient(driver, config)
+ if err != nil {
+ tb.Fatalf("failed to create client: %s", err)
+ }
+
+ return &Worker[T, TTx]{
+ client: client,
+ config: config,
+ worker: worker,
+ }
+}
+
+// Work allocates a synthetic job with the provided arguments and works it.
+func (w *Worker[T, TTx]) Work(ctx context.Context, tb testing.TB, args T) error {
+ tb.Helper()
+ return w.WorkOpts(ctx, tb, args, river.InsertOpts{})
+}
+
+// WorkJob works the provided job. The job must be constructed to be a realistic
+// job using external logic prior to calling this method. Unlike the other
+// variants, this method offers total control over the job's attributes.
+func (w *Worker[T, TTx]) WorkJob(ctx context.Context, tb testing.TB, job *river.Job[T]) error {
+ tb.Helper()
+
+ // populate river client into context:
+ ctx = WorkContext(ctx, w.client)
+
+ doInner := execution.MiddlewareChain(
+ w.config.WorkerMiddleware,
+ w.worker.Middleware(job),
+ func(ctx context.Context) error { return w.worker.Work(ctx, job) },
+ job.JobRow,
+ )
+
+ jobTimeout := valutil.FirstNonZero(w.worker.Timeout(job), w.config.JobTimeout)
+ ctx, cancel := execution.MaybeApplyTimeout(ctx, jobTimeout)
+ defer cancel()
+
+ return doInner(ctx)
+}
+
+// WorkOpts allocates a synthetic job with the provided arguments and insert
+// options, then works it.
+func (w *Worker[T, TTx]) WorkOpts(ctx context.Context, tb testing.TB, args T, opts river.InsertOpts) error { | > 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.
Works for me I suppose, but just a note that you could state that exact same rationale as to why `Insert` should've been broken into `Insert` + `InsertOpts`. |
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/river/rivershared/baseservice"
+ "github.com/riverqueue/river/rivershared/testfactory"
+ "github.com/riverqueue/river/rivershared/util/ptrutil"
+ "github.com/riverqueue/river/rivershared/util/sliceutil"
+ "github.com/riverqueue/river/rivershared/util/valutil"
+ "github.com/riverqueue/river/rivertype"
+)
+
+// Worker makes it easier to test river workers. Once built, the worker can be
+// used to work any number of synthetic jobs without touching the database:
+//
+// worker := rivertest.NewWorker(t, driver, config, worker)
+// if err := worker.Work(ctx, t, args); err != nil {
+// t.Fatalf("failed to work job: %s", err)
+// }
+//
+// if err := worker.WorkOpts(ctx, t, args, river.InsertOpts{Queue: "custom_queue"}); err != nil {
+// t.Fatalf("failed to work job: %s", err)
+// }
+//
+// In all cases the underlying [river.Worker] will be called with the synthetic
+// job. The execution environment has a realistic River context with access to
+// all River features, including [river.ClientFromContext] and worker
+// middleware. | 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 necessary to do it here. |
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/river/rivershared/baseservice"
+ "github.com/riverqueue/river/rivershared/testfactory"
+ "github.com/riverqueue/river/rivershared/util/ptrutil"
+ "github.com/riverqueue/river/rivershared/util/sliceutil"
+ "github.com/riverqueue/river/rivershared/util/valutil"
+ "github.com/riverqueue/river/rivertype"
+)
+
+// Worker makes it easier to test river workers. Once built, the worker can be
+// used to work any number of synthetic jobs without touching the database:
+//
+// worker := rivertest.NewWorker(t, driver, config, worker)
+// if err := worker.Work(ctx, t, args, nil); err != nil {
+// t.Fatalf("failed to work job: %s", err)
+// }
+//
+// if err := worker.Work(ctx, t, args, &river.InsertOpts{Queue: "custom_queue"}); err != nil {
+// t.Fatalf("failed to work job: %s", err)
+// }
+//
+// In all cases the underlying [river.Worker] will be called with the synthetic
+// job. The execution environment has a realistic River context with access to
+// all River features, including [river.ClientFromContext] and worker
+// middleware.
+//
+// When relying on features that require a database record (such as JobCompleteTx),
+// the job must be inserted into the database first and then executed with
+// WorkJob. | 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 now. They could `Client.Insert`, but then it'd get stuck there.
A couple possibilities:
* We could provide a test helper for inserting jobs in any state similar to our internal factories.
* We could have the test helpers here check to see if a job exists in the DB when running. If so, transition the job to `running`. |
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 TimeGenerator interface {
+ // NowUTC returns the current time. This may be a stubbed time if the time
+ // has been actively stubbed in a test.
+ NowUTC() time.Time
+
+ // NowUTCOrNil returns if the currently stubbed time _if_ the current time
+ // is stubbed, and returns nil otherwise. This is generally useful in cases
+ // where a component may want to use a stubbed time if the time is stubbed,
+ // but to fall back to a database time default otherwise.
+ NowUTCOrNil() *time.Time
+
+ // StubNowUTC stubs the current time. It will panic if invoked outside of
+ // tests. Returns the same time passed as parameter for convenience.
+ StubNowUTC(nowUTC time.Time) time.Time
+}
+
+// UnStubbableTimeGenerator is a TimeGenerator implementation that can't be
+// stubbed. It's always the generator used outside of tests.
+type UnStubbableTimeGenerator struct{} | 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 TimeGenerator interface {
+ // NowUTC returns the current time. This may be a stubbed time if the time
+ // has been actively stubbed in a test.
+ NowUTC() time.Time
+
+ // NowUTCOrNil returns if the currently stubbed time _if_ the current time
+ // is stubbed, and returns nil otherwise. This is generally useful in cases
+ // where a component may want to use a stubbed time if the time is stubbed,
+ // but to fall back to a database time default otherwise.
+ NowUTCOrNil() *time.Time
+
+ // StubNowUTC stubs the current time. It will panic if invoked outside of
+ // tests. Returns the same time passed as parameter for convenience.
+ StubNowUTC(nowUTC time.Time) time.Time | 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 because they won't have access to the `TimeGenerator` on a River client after they've set it (archetype is not exported).
We could potentially fix this by breaking `TimeGenerator` into two related interfaces along with a wrapper like:
``` go
diff --git a/client.go b/client.go
index 74643ad..06c9533 100644
--- a/client.go
+++ b/client.go
@@ -510,7 +510,11 @@ func NewClient[TTx any](driver riverdriver.Driver[TTx], config *Config) (*Client
archetype := baseservice.NewArchetype(config.Logger)
if config.time != nil {
- archetype.Time = config.time
+ if withStub, ok := config.time.(baseservice.TimeGeneratorWithStub); ok {
+ archetype.Time = withStub
+ } else {
+ archetype.Time = &baseservice.TimeGeneratorWithStubWrapper{TimeGenerator: config.time}
+ }
}
client := &Client[TTx]{
diff --git a/rivershared/baseservice/base_service.go b/rivershared/baseservice/base_service.go
index 764c0f3..d5b1fe2 100644
--- a/rivershared/baseservice/base_service.go
+++ b/rivershared/baseservice/base_service.go
@@ -25,7 +25,7 @@ type Archetype struct {
// `time.Now().UTC()`, but is riverinternaltest.timeStub in tests to allow
// the current time to be stubbed. Services should try to use this function
// instead of the vanilla ones from the `time` package for testing purposes.
- Time TimeGenerator
+ Time TimeGeneratorWithStub
}
// NewArchetype returns a new archetype. This function is most suitable for
@@ -90,12 +90,28 @@ type TimeGenerator interface {
// where a component may want to use a stubbed time if the time is stubbed,
// but to fall back to a database time default otherwise.
NowUTCOrNil() *time.Time
+}
+
+type TimeGeneratorWithStub interface {
+ TimeGenerator
// StubNowUTC stubs the current time. It will panic if invoked outside of
// tests. Returns the same time passed as parameter for convenience.
StubNowUTC(nowUTC time.Time) time.Time
}
+// TimeGeneratorWithStubWrapper provides a wrapper around TimeGenerator that
+// implements missing TimeGeneratorWithStub functions. This is used so that we
+// only need to expose the minimal TimeGenerator interface publicly, but can
+// keep a stubbable version of widely available for internal use.
+type TimeGeneratorWithStubWrapper struct {
+ TimeGenerator
+}
+
+func (g *TimeGeneratorWithStubWrapper) StubNowUTC(nowUTC time.Time) time.Time {
+ panic("time not stubbable outside tests")
+}
+
// UnStubbableTimeGenerator is a TimeGenerator implementation that can't be
// stubbed. It's always the generator used outside of tests.
type UnStubbableTimeGenerator struct{}
```
Thoughts? |
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 sync.RWMutex
+ nowUTC *time.Time
+}
+
+// NowUTC returns the current time. This may be a stubbed time if the time has
+// been actively stubbed in a test.
+func (t *TimeStub) NowUTC() time.Time {
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+
+ if t.nowUTC == nil {
+ return time.Now().UTC()
+ }
+
+ return *t.nowUTC
+}
+
+// NowUTCOrNil returns if the currently stubbed time _if_ the current time
+// is stubbed, and returns nil otherwise. This is generally useful in cases
+// where a component may want to use a stubbed time if the time is stubbed,
+// but to fall back to a database time default otherwise.
+func (t *TimeStub) NowUTCOrNil() *time.Time {
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+
+ return t.nowUTC
+}
+
+// StubNowUTC stubs the current time. It will panic if invoked outside of tests.
+// Returns the same time passed as parameter for convenience.
+func (t *TimeStub) StubNowUTC(nowUTC time.Time) time.Time { | 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 surprised it wasn't considered breaking TBH. |
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_args_index and river_job_metadata_index).
+ ReindexerIndexes []string | 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 run daily at midnight UTC by default. Each of these settings can be customized on the `river.Config` type via `ReindexerIndexes` and `ReindexerSchedule`. [PR #XXX](https://github.com/riverqueue/river/pull/XXX). | ```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 `ReindexerIndexes` and `ReindexerSchedule`. [PR #718](https://github.com/riverqueue/river/pull/718).
``` |
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.
+ return time.Unix(1<<63-1, 0)
+} | 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)
+}
+
+// ScheduleNever returns a PeriodicSchedule that never runs.
+func ScheduleNever() PeriodicSchedule {
+ return &neverSchedule{}
+} | 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, `{"encoded": "args"}`, string(job.EncodedArgs)) | 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.
+ //
+ // This can be set to true to allow a client to insert jobs which are
+ // intended to be worked by a different client which effectively makes
+ // the client's insertion behavior mimic that of an insert-only client.
+ //
+ // Defaults to false.
+ SkipUnknownJobCheck bool | 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.JobSetStateIfRunningManyParams{
- ID: make([]int64, len(setStateBatch)),
- ErrData: make([][]byte, len(setStateBatch)),
- FinalizedAt: make([]*time.Time, len(setStateBatch)),
- MaxAttempts: make([]*int, len(setStateBatch)),
- ScheduledAt: make([]*time.Time, len(setStateBatch)),
- State: make([]rivertype.JobState, len(setStateBatch)),
+ ID: make([]int64, len(setStateBatch)),
+ Attempt: make([]*int, len(setStateBatch)),
+ ErrData: make([][]byte, len(setStateBatch)),
+ FinalizedAt: make([]*time.Time, len(setStateBatch)),
+ ScheduledAt: make([]*time.Time, len(setStateBatch)),
+ SnoozeIncrement: make([]bool, len(setStateBatch)), | 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.Getenv("PGDATABASE") != ""
+} | 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 ensure reasonable
-// distribution of randomness between nodes and services, and wrapped so that
-// access to it is concurrent safe.
-//
-// This project uses this technique instead of falling back on crypto/rand
-// because uses of randomness don't need to be cryptographically secure, and the
-// non-crypto variant is about twenty times faster.
-func NewCryptoSeededConcurrentSafeRand() *mathrand.Rand {
- return mathrand.New(newCryptoSeededConcurrentSafeSource())
-}
-
// DurationBetween generates a random duration in the range of [lowerLimit, upperLimit).
-//
-// TODO: When we drop Go 1.21 support, switch to `math/rand/v2` and kill the
-// `rand.Rand` argument.
-func DurationBetween(rand *mathrand.Rand, lowerLimit, upperLimit time.Duration) time.Duration {
- return time.Duration(IntBetween(rand, int(lowerLimit), int(upperLimit)))
+func DurationBetween(lowerLimit, upperLimit time.Duration) time.Duration { | 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 the maximum number of jobs that were requested,
+ // implying there may be more in the queue. Trigger another fetch when
+ // slots are available.
+ p.fetchWhenSlotsAreAvailable = true | 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 future so that
+// existing code isn't unexpectedly broken during an upgrade.
+type JobMiddlewareDefaults struct{}
+
+func (l *JobMiddlewareDefaults) Insert(ctx context.Context, params *rivertype.JobInsertParams, doInner func(ctx context.Context) (*rivertype.JobInsertResult, error)) (*rivertype.JobInsertResult, error) {
+ return doInner(ctx)
+}
+
+func (l *JobMiddlewareDefaults) InsertMany(ctx context.Context, manyParams []*rivertype.JobInsertParams, doInner func(ctx context.Context) (int, error)) (int, error) {
+ return doInner(ctx)
+}
+
+func (l *JobMiddlewareDefaults) Work(ctx context.Context, job *rivertype.JobRow, doInner func(ctx context.Context) error) error {
+ return doInner(ctx)
+} | 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 fulfilled by either of those types to indicate to the middleware what it should do).
The problem with trying to do that here is the args have already been encoded, so there's no longer any access to the underlying `JobArgs` type. Is there any path to potentially having the middleware stack get called _before_ the JSON encoding part? That could more easily enable dynamic behavior based on the type.
Additionally, this might be further exposing the somewhat confusing split between `JobArgs` and `Worker` implementations. We had some recent customer feedback about it being a little weird that i.e. the timeout must be customized on the `Worker` and can't easily be tweaked at insertion time via the args. In this case though you mentioned potentially allowing for middleware to be configured at the `JobArgs` level, which seems fine for insert time but IMO doesn't make any sense for the `Work()` middleware. I don't want to have two separate middleware stacks/concepts, but it does feel a bit odd to have both of these on a single interface given the way this split is designed today 🤔 |
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 []string
+}
+
+// JobMiddleware provides an interface for middleware that integrations can use
+// to encapsulate common logic around various phases of a job's lifecycle.
+//
+// Implementations should embed river.JobMiddlewareDefaults to inherit default
+// implementations for phases where no custom code is needed, and for forward
+// compatibility in case new functions are added to this interface.
+type JobMiddleware interface {
+ // Insert is invoked around an insert operation. Implementations must always
+ // include a call to doInner to call down the middleware stack and perfom
+ // the insertion, and may run custom code before and after.
+ //
+ // Returning an error from this function will fail the overarching insert
+ // operation, even if the inner insertion originally succeeded.
+ //
+ // Insert is *not* invoked on batch insertions using Client.InsertMany or
+ // Client.InsertManyTx. InsertMany should be implemented separately.
+ Insert(ctx context.Context, params *JobInsertParams, doInner func(ctx context.Context) (*JobInsertResult, error)) (*JobInsertResult, error)
+
+ // InsertMany is invoked around a batch insert operation. Implementations
+ // must always include a call to doInner to call down the middleware stack
+ // and perfom the batch insertion, and may run custom code before and after.
+ //
+ // Returning an error from this function will fail the overarching insert
+ // operation, even if the inner insertion originally succeeded.
+ InsertMany(ctx context.Context, manyParams []*JobInsertParams, doInner func(ctx context.Context) (int, error)) (int, error)
+
+ // Work is invoked around a job's JSON args being unmarshaled and the job
+ // worked. Implementations must always include a call to doInner to call
+ // down the middleware stack and perfom the batch insertion, and may run
+ // custom code before and after.
+ //
+ // Returning an error from this function will fail the overarching work
+ // operation, even if the inner work originally succeeded.
+ Work(ctx context.Context, job *JobRow, doInner func(ctx context.Context) error) error
+
+ //
+ // below this line was an experiment and commented out now
+ //
+
+ // InsertBegin is invoked immediately before doing a job uniqueness check
+ // and (provided there was no duplicate), inserting it to the database. A
+ // lifecycle hook may make modifications to insert params, but should be
+ // careful doing so as it'll fundamentally modify the job.
+ //
+ // Returns a context that'll be used during the insert operation. Hooks that
+ // don't need to modify context should pass through the input ctx.
+ //
+ // InsertBegin is *not* invoked on a batch insertion with InsertMany or
+ // InsertManyTx. Integrations should implement InsertManyBegin separately.
+ // InsertBegin(ctx context.Context, params *JobLifecycleInsertParams) (context.Context, error) | 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) {
- inserted, err := tx.JobInsertFastMany(ctx, insertParams)
- if err != nil {
- return inserted, err
- }
+func (c *Client[TTx]) insertFastMany(ctx context.Context, tx riverdriver.ExecutorTx, manyParams []*rivertype.JobInsertParams) (int, error) {
+ doInner := func(ctx context.Context) (int, error) {
+ manyInsertParams := sliceutil.Map(manyParams, func(params *rivertype.JobInsertParams) *riverdriver.JobInsertFastParams {
+ return (*riverdriver.JobInsertFastParams)(params) | 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 implementations.
The downside is they lose the ability to directly access the encoded json bytes, but then I'm not sure I know of any cases where that's desirable. For metadata, sure, but not for args. |
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` if it wishes to not have any job inserted. However, this was either never working or was broken at some point. It's now fixed. Thanks [@semanser](https://github.com/semanser)! [PR #572](https://github.com/riverqueue/river/pull/572).
+- 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 #XXX](https://github.com/riverqueue/river/pull/XXX). | ```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 (Workers not configure)") | ```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.TestDB(ctx, t)
+
+ client := newTestClient(t, dbPool, &Config{})
+
+ require.PanicsWithValue(t, "created a subscription on a client that will never work jobs (Workers not configure)", func() { | ```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.JobInsertManyReturningParams{
+ Args: make([]string, len(params)),
+ Kind: make([]string, len(params)),
+ MaxAttempts: make([]int16, len(params)),
+ Metadata: make([]string, len(params)),
+ Priority: make([]int16, len(params)),
+ Queue: make([]string, len(params)),
+ ScheduledAt: make([]time.Time, len(params)),
+ State: make([]string, len(params)),
+ Tags: make([]string, len(params)),
+ }
+ now := time.Now()
+
+ for i := 0; i < len(params); i++ {
+ params := params[i]
+
+ scheduledAt := now
+ if params.ScheduledAt != nil {
+ scheduledAt = *params.ScheduledAt
+ }
+
+ tags := params.Tags
+ if tags == nil {
+ tags = []string{}
+ }
+
+ defaultObject := "{}"
+
+ insertJobsParams.Args[i] = valutil.ValOrDefault(string(params.EncodedArgs), defaultObject) | 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)
+ JobInsertManyReturning(ctx context.Context, params []*JobInsertFastParams) ([]*rivertype.JobRow, error) | 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 the suffix (i.e. so they're flipped).
Maybe:
* `JobInsertFastMany` (called from `InsertManyFast`) -> `JobInsertFastManyNoReturning`
* `JobInsertManyReturning` (called from `InsertMany`) -> `JobInsertFastMany` |
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, "database-url", "", "URL of the database to benchmark (should look like `postgres://...` or `postgresql://...`") | ```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 wrap. |
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/docs/current/libpq-connect.html#LIBPQ-CONNSTRING-URIS. | 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/context#Context) (see `userKey`).
To make this work you would also need the getter function to be exposed in this package though (`withClient`). |
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.
+//
+// In particual, adds a client to the context so that river.ClientFromContext is
+// usable in the test suite.
+func WorkContext[TTx any](ctx context.Context, client *river.Client[TTx]) context.Context {
+ return context.WithValue(ctx, rivercommon.ContextKeyClient{}, client)
+} | 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 maybe it makes more sense for the possible job-running helper instead of this one. |
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 StopAndCancel is called before start up | 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)
+}
+
+// High level integration tests that operate on the Cobra command directly. This
+// isn't always appropriate because there's no way to inject a test transaction.
+func TestBaseCommandSetIntegration(t *testing.T) {
+ t.Parallel()
+
+ type testBundle struct {
+ out *bytes.Buffer
+ }
+
+ setup := func(t *testing.T) (*cobra.Command, *testBundle) {
+ t.Helper()
+
+ cli := NewCLI(&Config{
+ DriverProcurer: &TestDriverProcurer{},
+ Name: "River",
+ })
+
+ var out bytes.Buffer
+ cli.SetOut(&out)
+
+ return cli.BaseCommandSet(), &testBundle{
+ out: &out,
+ }
+ }
+
+ t.Run("DebugVerboseMutallyExclusive", func(t *testing.T) {
+ t.Parallel()
+
+ cmd, _ := setup(t)
+
+ cmd.SetArgs([]string{"--debug", "--verbose"})
+ require.EqualError(t, cmd.Execute(), `if any flags in the group [debug verbose] are set none of the others can be; [debug verbose] were all set`)
+ })
+
+ t.Run("MigrateDownMissingDatabaseURL", func(t *testing.T) {
+ t.Parallel()
+
+ cmd, _ := setup(t)
+
+ cmd.SetArgs([]string{"migrate-down"})
+ require.EqualError(t, cmd.Execute(), `required flag(s) "database-url" not set`)
+ })
+
+ t.Run("VersionFlag", func(t *testing.T) {
+ t.Parallel()
+
+ cmd, bundle := setup(t)
+
+ cmd.SetArgs([]string{"--version"})
+ require.NoError(t, cmd.Execute())
+
+ buildInfo, _ := debug.ReadBuildInfo()
+
+ require.Equal(t, strings.TrimSpace(fmt.Sprintf(`
+River version (unknown)
+Built with %s
+ `, buildInfo.GoVersion)), strings.TrimSpace(bundle.out.String())) | 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 {
select {
case <-ctx.Done():
return
case <-ticker.C:
- p.Logger.InfoContext(ctx, p.Name+": Heartbeat",
- slog.Uint64("num_completed_jobs", p.numJobsRan.Load()),
- slog.Int("num_jobs_running", int(p.numJobsActive.Load())),
- slog.String("queue", p.config.Queue),
- )
+ cur := state{jobsRan: p.numJobsRan.Load(), jobsActive: int(p.numJobsActive.Load())}
+ if cur != prev {
+ p.Logger.InfoContext(ctx, p.Name+": Heartbeat", | 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 {
select {
case <-ctx.Done():
return
case <-ticker.C:
- p.Logger.InfoContext(ctx, p.Name+": Heartbeat",
- slog.Uint64("num_completed_jobs", p.numJobsRan.Load()),
- slog.Int("num_jobs_running", int(p.numJobsActive.Load())),
- slog.String("queue", p.config.Queue),
- )
+ curCount := jobCount{ran: p.numJobsRan.Load(), active: int(p.numJobsActive.Load())}
+ if curCount != prevCount {
+ p.Logger.InfoContext(ctx, p.Name+": producer job count changed", | 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 {
select {
case <-ctx.Done():
return
case <-ticker.C:
- p.Logger.InfoContext(ctx, p.Name+": Heartbeat",
- slog.Uint64("num_completed_jobs", p.numJobsRan.Load()),
- slog.Int("num_jobs_running", int(p.numJobsActive.Load())),
- slog.String("queue", p.config.Queue),
- )
+ curCount := jobCount{ran: p.numJobsRan.Load(), active: int(p.numJobsActive.Load())}
+ if curCount != prevCount {
+ p.Logger.InfoContext(ctx, p.Name+": Producer job count changed", | 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/river/riverdriver/riverdatabasesql => ../../riverdriver/riverdatabasesql
+replace github.com/riverqueue/river/riverdriver => ../../riverdriver
-// replace github.com/riverqueue/river/riverdriver/riverpgxv5 => ../../riverdriver/riverpgxv5
+replace github.com/riverqueue/river/riverdriver/riverdatabasesql => ../../riverdriver/riverdatabasesql
-// replace github.com/riverqueue/river/rivertype => ../../rivertype
+replace github.com/riverqueue/river/riverdriver/riverpgxv5 => ../../riverdriver/riverpgxv5
+
+replace github.com/riverqueue/river/rivertype => ../../rivertype | 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 (linux/amd64)
/opt/hostedtoolcache/go/1.21.12/x64/bin/go env GOMODCACHE
/opt/hostedtoolcache/go/1.21.12/x64/bin/go env GOCACHE
/home/runner/go/pkg/mod
/home/runner/.cache/go-build
Cache Size: ~1[16](https://github.com/riverqueue/river/actions/runs/10312078359/job/28546717441#step:4:17) MB (122068102 B)
/usr/bin/tar -xf /home/runner/work/_temp/3fd374b5-c372-4fe0-bb5a-72c9ec40afc9/cache.tzst -P -C /home/runner/work/river/river --use-compress-program unzstd
Received 12[20](https://github.com/riverqueue/river/actions/runs/10312078359/job/28546717441#step:4:21)68102 of 122068102 (100.0%), 116.4 MBs/sec
Cache restored successfully
Cache restored from key: setup-go-Linux-ubuntu22-go-1.22.5-7e42e876c7fc43348578ac5ddfec93c5643eb4a8c880ab849c10c6fbcbbb6cc8
go version go1.[22](https://github.com/riverqueue/river/actions/runs/10312078359/job/28546717441#step:4:23).5 linux/amd64
``` |
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, exists)
+
+ // Will be rolled back by the test transaction.
+ _, err = exec.Exec(ctx, "CREATE SCHEMA another_schema_123")
+ require.NoError(t, err)
+
+ _, err = exec.Exec(ctx, "SET search_path = another_schema_123") | 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
- options: >-
- --health-cmd pg_isready
- --health-interval 2s
- --health-timeout 5s
- --health-retries 5
- ports:
- - 5432:5432
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 10 | 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, where the container jobs are _so_ slow that they really do have a substantial effect on the productivity loop. |
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 in `JobList` / `JobListTx` results. [PR #477](https://github.com/riverqueue/river/pull/477). | 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 in `JobList` / `JobListTx` results. [PR #477](https://github.com/riverqueue/river/pull/477).
+- Quote strings when using `Client.JobList` functions with the `database/sql` driver. [PR #XXX](https://github.com/riverqueue/river/pull/XXX). | ```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.Job(ctx, t, exec, &testfactory.JobOpts{
- Attempt: ptrutil.Ptr(3),
- AttemptedAt: &now,
- CreatedAt: &now,
- EncodedArgs: []byte(`{"encoded": "args"}`),
- Errors: [][]byte{[]byte(`{"error": "message1"}`), []byte(`{"error": "message2"}`)},
- FinalizedAt: &now,
- Metadata: []byte(`{"meta": "data"}`),
- ScheduledAt: &now,
- State: ptrutil.Ptr(rivertype.JobStateCompleted),
- Tags: []string{"tag"},
- })
-
- fetchedJobs, err := exec.JobList(
- ctx,
- fmt.Sprintf("SELECT %s FROM river_job WHERE id = @job_id_123", exec.JobListFields()),
- map[string]any{"job_id_123": job.ID},
- )
- require.NoError(t, err)
- require.Len(t, fetchedJobs, 1)
-
- fetchedJob := fetchedJobs[0]
- require.Equal(t, job.Attempt, fetchedJob.Attempt)
- require.Equal(t, job.AttemptedAt, fetchedJob.AttemptedAt)
- require.Equal(t, job.CreatedAt, fetchedJob.CreatedAt)
- require.Equal(t, job.EncodedArgs, fetchedJob.EncodedArgs)
- require.Equal(t, "message1", fetchedJob.Errors[0].Error)
- require.Equal(t, "message2", fetchedJob.Errors[1].Error)
- require.Equal(t, job.FinalizedAt, fetchedJob.FinalizedAt)
- require.Equal(t, job.Kind, fetchedJob.Kind)
- require.Equal(t, job.MaxAttempts, fetchedJob.MaxAttempts)
- require.Equal(t, job.Metadata, fetchedJob.Metadata)
- require.Equal(t, job.Priority, fetchedJob.Priority)
- require.Equal(t, job.Queue, fetchedJob.Queue)
- require.Equal(t, job.ScheduledAt, fetchedJob.ScheduledAt)
- require.Equal(t, job.State, fetchedJob.State)
- require.Equal(t, job.Tags, fetchedJob.Tags)
+ job := testfactory.Job(ctx, t, exec, &testfactory.JobOpts{
+ Attempt: ptrutil.Ptr(3),
+ AttemptedAt: &now,
+ CreatedAt: &now,
+ EncodedArgs: []byte(`{"encoded": "args"}`),
+ Errors: [][]byte{[]byte(`{"error": "message1"}`), []byte(`{"error": "message2"}`)},
+ FinalizedAt: &now,
+ Metadata: []byte(`{"meta": "data"}`),
+ ScheduledAt: &now,
+ State: ptrutil.Ptr(rivertype.JobStateCompleted),
+ Tags: []string{"tag"},
+ })
+
+ fetchedJobs, err := exec.JobList(
+ ctx,
+ fmt.Sprintf("SELECT %s FROM river_job WHERE id = @job_id_123", exec.JobListFields()),
+ map[string]any{"job_id_123": job.ID},
+ )
+ require.NoError(t, err)
+ require.Len(t, fetchedJobs, 1)
+
+ fetchedJob := fetchedJobs[0]
+ require.Equal(t, job.Attempt, fetchedJob.Attempt)
+ require.Equal(t, job.AttemptedAt, fetchedJob.AttemptedAt)
+ require.Equal(t, job.CreatedAt, fetchedJob.CreatedAt)
+ require.Equal(t, job.EncodedArgs, fetchedJob.EncodedArgs)
+ require.Equal(t, "message1", fetchedJob.Errors[0].Error)
+ require.Equal(t, "message2", fetchedJob.Errors[1].Error)
+ require.Equal(t, job.FinalizedAt, fetchedJob.FinalizedAt)
+ require.Equal(t, job.Kind, fetchedJob.Kind)
+ require.Equal(t, job.MaxAttempts, fetchedJob.MaxAttempts)
+ require.Equal(t, job.Metadata, fetchedJob.Metadata)
+ require.Equal(t, job.Priority, fetchedJob.Priority)
+ require.Equal(t, job.Queue, fetchedJob.Queue)
+ require.Equal(t, job.ScheduledAt, fetchedJob.ScheduledAt)
+ require.Equal(t, job.State, fetchedJob.State)
+ require.Equal(t, job.Tags, fetchedJob.Tags)
+ })
+
+ t.Run("QuotesStrigngs", func(t *testing.T) { | ```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
+// string replacement given we're only injecting a very basic value anyway.
+func replaceNamed(query string, namedArgs map[string]any) (string, error) {
+ for name, value := range namedArgs {
+ var escapedValue string
+
+ switch typedValue := value.(type) { | 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), then run `river migrate-up` to finalize the process (it will tolerate an index that already exists):
+
+```sql
+ALTER TABLE river_job
+ ADD COLUMN unique_key bytea;
+
+CREATE UNIQUE INDEX CONCURRENTLY river_job_kind_unique_key_idx ON river_job (kind, unique_key) WHERE unique_key IS NOT NULL;
+``` | 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,
+ created_at,
+ finalized_at,
+ kind,
+ max_attempts,
+ metadata,
+ priority,
+ queue,
+ scheduled_at,
+ state,
+ tags,
+ unique_key
+) VALUES (
+ @args,
+ coalesce(sqlc.narg('created_at')::timestamptz, now()),
+ @finalized_at,
+ @kind,
+ @max_attempts,
+ coalesce(@metadata::jsonb, '{}'),
+ @priority,
+ @queue,
+ coalesce(sqlc.narg('scheduled_at')::timestamptz, now()),
+ @state,
+ coalesce(@tags::varchar(255)[], '{}'),
+ @unique_key
+)
+ON CONFLICT (kind, unique_key) WHERE unique_key IS NOT NULL
+ -- Something needs to be updated for a row to be returned on a conflict.
+ DO UPDATE SET kind = EXCLUDED.kind
+RETURNING *, (xmax != 0) AS unique_skipped_as_duplicate; | 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)
}
return jobRowFromInternal(job)
}
+func (e *Executor) JobInsertUnique(ctx context.Context, params *riverdriver.JobInsertUniqueParams) (*riverdriver.JobInsertUniqueResult, error) {
+ insertRes, err := e.queries.JobInsertUnique(ctx, e.dbtx, &dbsqlc.JobInsertUniqueParams{
+ Args: params.EncodedArgs,
+ CreatedAt: params.CreatedAt,
+ Kind: params.Kind,
+ MaxAttempts: int16(min(params.MaxAttempts, math.MaxInt16)),
+ Metadata: params.Metadata,
+ Priority: int16(min(params.Priority, math.MaxInt16)),
+ Queue: params.Queue,
+ ScheduledAt: params.ScheduledAt,
+ State: dbsqlc.RiverJobState(params.State),
+ Tags: params.Tags,
+ UniqueKey: params.UniqueKey,
+ })
+ if err != nil {
+ return nil, interpretError(err)
+ }
+
+ jobRow, err := jobRowFromInternal(&dbsqlc.RiverJob{
+ ID: insertRes.ID,
+ Args: insertRes.Args,
+ Attempt: insertRes.Attempt,
+ AttemptedAt: insertRes.AttemptedAt,
+ AttemptedBy: insertRes.AttemptedBy,
+ CreatedAt: insertRes.CreatedAt,
+ Errors: insertRes.Errors,
+ FinalizedAt: insertRes.FinalizedAt,
+ Kind: insertRes.Kind,
+ MaxAttempts: insertRes.MaxAttempts,
+ Metadata: insertRes.Metadata,
+ Priority: insertRes.Priority,
+ Queue: insertRes.Queue,
+ ScheduledAt: insertRes.ScheduledAt,
+ State: insertRes.State,
+ Tags: insertRes.Tags,
+ UniqueKey: insertRes.UniqueKey,
+ }) | 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 taking advantage of
+-- the migration to add the schema early so that we can add it later without an
+-- additional migration.
+--
+
+CREATE UNLOGGED TABLE river_client (
+ name text PRIMARY KEY NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ metadata jsonb NOT NULL DEFAULT '{}' ::jsonb,
+ paused_at timestamptz,
+ updated_at timestamptz NOT NULL,
+ CONSTRAINT name_length CHECK (char_length(name) > 0 AND char_length(name) < 128)
+);
+
+-- Differs from `river_queue` in that it tracks the queue state for a particular
+-- active client.
+CREATE UNLOGGED TABLE river_client_queue (
+ river_client_name text NOT NULL REFERENCES river_client (name) ON DELETE CASCADE,
+ name text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ max_workers bigint NOT NULL DEFAULT 0,
+ num_jobs_completed bigint NOT NULL DEFAULT 0,
+ num_jobs_running bigint NOT NULL DEFAULT 0, | 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 similarly to `max_workers`.
Minor though, I don't feel strongly about it. |
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 taking advantage of
+-- the migration to add the schema early so that we can add it later without an
+-- additional migration.
+--
+
+CREATE UNLOGGED TABLE river_client (
+ name text PRIMARY KEY NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ metadata jsonb NOT NULL DEFAULT '{}' ::jsonb,
+ paused_at timestamptz,
+ updated_at timestamptz NOT NULL,
+ CONSTRAINT name_length CHECK (char_length(name) > 0 AND char_length(name) < 128)
+);
+
+-- Differs from `river_queue` in that it tracks the queue state for a particular
+-- active client.
+CREATE UNLOGGED TABLE river_client_queue (
+ river_client_name text NOT NULL REFERENCES river_client (name) ON DELETE CASCADE,
+ name text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, | 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? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.