michalmuskala / plug_attack

A plug building toolkit for blocking and throttling abusive requests
420 stars 21 forks source link

Override init/1 to pass options into the rule macro #21

Open ribanez7 opened 3 years ago

ribanez7 commented 3 years ago

Is it possible to override the init function and make available those options into the rule macro?

Use case:

init/1 runs at compile time, and allows to set calculations into the options that cannot be computed in a module attribute definition. Lets say I want to compile some patterns in compile time using the :binary.compile_pattern(["some", "nice", "patterns"]) to later use them into some function. That cannot be done in a module attribute since it only support specific values easy to escape. Init would be the way to go then, but the options won't be available into the rule macro, and I don't won't to override also the call/2 function to assign those values into the conn, since that computation doesn't relate to the conn at all.

Thanks!

michalmuskala commented 2 years ago

The values that are allowed in module attributes are also the same values that are allowed in compile-time init return values (since it ends up in a module attribute eventually). So i"m not sure this would actually help for the use case you talk about.

One way to solve it for patterns specifically could be to leverage the persistent_term module which seems ideal for things like that that never change. Something like:

pattern =
  case :persistent_term.get(__MODULE__, nil) do
    nil ->  
      pattern = :binary.compile_pattern(["some", "nice", "patterns"])
      :persistent_term.put(__MODULE__, pattern)
      pattern
    pattern ->
      pattern
  end