riverqueue / river

Fast and reliable background jobs in Go
https://riverqueue.com
Mozilla Public License 2.0
3.51k stars 94 forks source link

Allow customize context used in Work func with provided key/values in Insert #513

Closed TC5027 closed 2 months ago

TC5027 commented 2 months ago

Currently the context used in Work function is not linked with the one used in Insert. I have a use case where I would like to bring a metadata (contained in the context I use to insert) into the context used in Work function

I will try to submit a PR for this

bgentry commented 2 months ago

This is not possible or even desirable in River. Your jobs will be worked with a child of the context you pass to the client that works them, but this has no connection to the client which inserts the jobs.

rgalanakis commented 2 months ago

If I understand the request correctly, I was originally confused by how to do this sort of thing- @TC5027 if you have 'globals' you want to pass to the work, you should store them on the worker. Like:

type Args struct {
    DocumentId sometypes.DocumentId
}

func (Args) Kind() string { return "my job" }

type Worker struct {
    river.WorkerDefaults[Args]
        client SomeClient
}

type Input struct {
  Client SomeClient
}

func New(input Input) river.Worker[Args] {
    return &Worker{client: input.Client}
}

func (w *Worker) Work(ctx context.Context, rjob *river.Job[Args]) error {
  return w.client.DoThingWithId(rjob.Args.DocumentId)
}

// And where you create your worker:
river.AddWorker(workers, myworker.New(myworker.Input{Client: myAppGlobals.Client}))

That will make this shared Client object available to all jobs.

To be clear, this is fundamentally different from your request, but it seems like it may solve the problem you're trying to solve. Or maybe not! If you have job-specific fields, they should be on Args.

TC5027 commented 2 months ago

Thanks for your response :) Indeed after looking at the river's code the natural way to perform what i want is to incorporate in job's args. My use case was to pass user-agent data stored in the context to the Work func (ideally in the context directly to be able to use the same piece of code for retrieval) I closed the issue as it does not fit with the river's philosophy (from my understanding)