miguelcoba

miguelcoba

Oban on phoenix apps with scope contexts

Hi there, I would like to know your thoughts about how to use Oban workers in a Phoenix app with Scopes.

When using scopes the context functions receive as first parameter the scope, f.e.

# lib/my_app/blog.ex
def list_posts(%Scope{} = scope) do
  Repo.all(from post in Post, where: post.user_id == ^scope.user.id)
end

If I needed to use the list_posts inside a worker, I’ll need somehow to build a scope in order to use those scoped functions:

defmodule MyApp.MyWorker do
  use Oban.Worker

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"id" => id}}) do
    scope = # ? how to get the scope at the time the worker runs

    list = Blog.list_posts(scope)
    # Do something with list
    :ok
  end
end

Option 1.

Pass the scope (or enought data to rebuild the scope) as params to `Worker.new()`

%{user_id: scope.user.id, other: "data"}
|> MyApp.Worker.new()
|> Oban.insert()

and in the worker use user_id to build a `scope` and continue from that.

Option 2.

Add additional heads in the Context that don’t require scope and are only used by trusted callers (in this case Oban)

# lib/my_app/blog.ex
# additional function head that does not use scope
def list_posts(user_id) do
  Repo.all(from post in Post, where: post.user_id == ^user_id)
end

defmodule MyApp.MyWorker do
  use Oban.Worker

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"id" => user_id}}) do
    # use the non-scoped functions
    list = Blog.list_posts(user_id)
    # Do something with list
    :ok
  end
end

None of the options is optimal, but from those two, the option 2 is the worst as it totally breaks the idea of scopes in the context modules by allowing anyone to bypass the scoped functions and use the non-scoped ones.

So I’m leaning on passing enough info to the worker params and use that to build a scope inside it and then use it to do whatever thing the worker needs to do using the scoped context functions.

Is there another way?

Do you have suggestions/ideas/experience implementing something like this?

Thanks in advance,

Miguel Cobá

Most Liked

tfwright

tfwright

My point was that this is all just business logic, so yeah. There is no “idea of scopes” that can be violated in this way. Usually validating at the edges is fine but depending on the specific requirements of the app/business it might not be. Even if you need to care about permission changes (it might even be the case roles/access are immutable!), it can also go the other way, that you need to respect what they were at the time of the request, or it might be necessary to raise a more specific error, etc etc. Checking on mount in a LV may very well be acceptable or exactly what’s required. I don’t think there is any general rule for any of this, and so there is no utility that Phoenix can/does provide that you can use to ensure you are using scopes “the correct way,” it’s just a nudge to start with a basic pattern in place.

pjode

pjode

I think it depends on the type of worker. If the job being run is a deferred action a user is making that should be run in the scope of a user, putting the data necessary to reconstruct a user scope in the job is the right choice IMO. If the job is something that executes in a more privileged way, I actually define a new scope for that. For example, I have a scope defined for ingest and use that in function heads instead of a user scope. So you could imagine something like

defmodule MyApp.Accounts do
  def create_user(%Accounts.Scope{admin: true} = scope, attrs) do
    # ...
  end

  def create_user(%Ingest.Scope{} = scope, attrs) do
    # ...
  end
end

and again you’d store what you need in the job to construct such a scope. This way functions still expect some form of scope regardless.

miguelcoba

miguelcoba

Interesting. I was trying to follow the docs and use the scope to harden/validate access to data. I didn’t even consider to break that “contract” as it seemed to me like diverging of the “good practices”. Maybe I should relax my view and view unscoped functions that are called from places where validation has already happened and it is safe to do so, is ok.

Yeah, maybe I’m reading too much and assigning too much weight to them and that introduces unflexibility

I’ll take a good thinking on this.

Thank you!

Last Post!

miguelcoba

miguelcoba

That’s interesting. I like that it can be used for auditing/logging purposes.

Unfortunately the “real” scope data that spawned the oban job is being used in the context scoped functions to scope the data accessed/modified by the function to the tenant/organization represented by the info stored in the scope. Because of that, even if the “myworker” was a good improvement to track who actually did something, I still need to pass the scope data (for example an organization id, and a user id) in order for the worker to affect only the data that belongs to that organization or user.

That said, this is definitely something that can be used to improve code quality by tracking the worker that did something.

Thanks!

Where Next?

Trending in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
tj0
I’ve been following the steps here for the upgrade from 1.6 to 1.7 and it has gone relatively smoothly all the way till the phoenix_view ...
New
cgraham
Hi! What is currently the best library/method for parsing text and tabular data out of PDF files in Elixir or Erlang?
New
stefanchrobot
Hi, I need a way to handle data migrations in my application. I found an article by @wojtekmach about manual migrations: Automatic and ma...
New
stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
webofbits
Squid Mesh is an open source workflow automation runtime for Elixir applications. It is aimed at Phoenix and OTP apps that want to defin...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New

We're in Beta

About us Mission Statement