mmmrrr

mmmrrr

Rustler return and pass reference from Rust to Elixir and back to Rust

The starting point: The Erlang ODBC client has a “bug” where it only allows 4096 bytes to be returned per cell. The Rust odbc client has no such limitations.

The reasoning: I’d like to avoid Rust for the web layer, since that would result in a lot of training for my peers.

The (probably insane) idea: Use Rustler to provide a custom “odbc driver” that can be used from Elixir.

The problem: I’d need to store the established connections somewhere in Elixir in order to pass them to the query functions and I’m not quite sure if this would work with Rustlers unsafe functions.

So the questions are:

  1. How do I return a Rust reference to a “thing” to Elixir in order to pass it again to Rust later on?
  2. Is there anything that disqualifies this idea categorically (except from the fact that it is probably a huge effort)

Marked As Solved

mickel8

mickel8

Membrane Core Team

@mmmrrr @dimitarvp I probably solved my issue. It turned out I should use rustler::init! and rustler::resource! macros. Here is full code. It compiles so that’s something

  use rustler::resource::ResourceArc;
  use rustler::{Env, Term, NifStruct};
  
  rustler::atoms! {
      ok,
      error
  }
  
  rustler::init!("PineSSL", [add], load=load);
  
  #[derive(NifStruct)]
  #[module = "MyStruct"]
  pub struct MyStruct {
      pub a: i64
  }
  
  fn load(env: Env, _info: Term) -> bool {
      rustler::resource!(MyStruct, env);
      true
  }
  
  #[rustler::nif]
  fn add(a: i64, b: i64) -> ResourceArc<MyStruct> {
      ResourceArc::new(MyStruct{a: a+b})
  }

macro rustler::resource! implements ResourceTypeProvider trait for MyStruct and in rustler::init! I can invoke my function load which then invokes rustler::resource!.

Also Liked

tessi

tessi

@hauleth 's suggestion is on point.

If you need an example, you could look at wasmex (GitHub - tessi/wasmex: Execute WebAssembly from Elixir · GitHub).

For example, a WebAssembly module instance has an elixir representation with an attached Rust struct. It is passed down in some methods defined here to the Rust-layer.

In Rust-land, we override the Wasmex::Native module with the respective rust functions taking that rust-struct reference.

In instance.rs you can see how to attach structs (instance in my case) to elixir objects (new_from_bytes) and how to extract structs from elixir objects (e.g. function_export_exists).

dimitarvp

dimitarvp

Here’s something that should work with minimal changes:

use rustler::resource::ResourceArc;
use rustler::{Encoder, Env, Term};

rustler::atoms! { error, ok, }

type MyRustReturnType = YOUR_RUST_TYPE_HERE;

enum MyResult {
    Success(ResourceArc<MyRustReturnType>),
    Failure(String),
}

impl<'a> Encoder for MyResult {
    fn encode<'b>(&self, env: Env<'b>) -> Term<'b> {
        match self {
            MyResult::Success(arc) => (ok(), arc).encode(env),
            MyResult::Failure(msg) => (error(), msg).encode(env),
        }
    }
}

// or DirtyCpu, or just remove the "schedule" option and leave the clause to be simply: `#[rustler::nif]`
#[rustler::nif(schedule = "DirtyIo")]
fn something() -> MyResult {
  match function_that_can_fail() {
    Ok(rust_object) => MyResult::Success(ResourceArc::(rust_object)),
    Err(e) => MyResult::Failure(e.to_string()),
  }
}

You might need to remove the lifetime qualifiers though, can’t remember why my code needed them now. Using Rustler’s ResourceArc is crucial here; thanks to it you will receive the Rust object wrapped in a nice Erlang Reference which in the case of this function you’ll see in your iex console like so (in the case of success):

{:ok, #Reference<0.679634982.4171759622.38993>}

…or in case of failure:

{:error, "error message from Rust here"}

Then on the Elixir side you should take care to have the same something() function that Rustler will wrap and pass through to Rust (this is covered in Rustler’s guide). That’s basically it. Poke me if you need more help, Rustler could be tricky and it seems the maintainers don’t have time for it for a long time now.

hauleth

hauleth

Use NIF resource for that, you probably will need to dig in Rustler docs how to do that in Rust.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement