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 / WASM from Elixir).

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.

rm-rf-etc

rm-rf-etc

Sure, sorry. I dropped details over in the thread in the rust forums.

The problem was the lifetimes. I needed to replace any datatype that requires a lifetime, with the equivalent datatype that doesn’t (e.g. &strString, and &[&str]Vec<String>). I didn’t understand that lifetimes aren’t needed for what I’m doing. They’re only used at compile-time, so in my situation it doesn’t make sense to accept a lifetime parameter. For example, &str requires a known length at compile-time, but my string values are dynamic length.

So instead of…

struct SlidingWindow<'a> {
    map: HashMap<&'a str, Vec<Option<f32>>>,
    labels: &'a [&'a str],
    index: usize,
    length: usize,
    width: usize,
}

…we need to use…

struct SlidingWindow {
    map: HashMap<String, Vec<Option<f32>>>,
    labels: Vec<String>,
    index: usize,
    length: usize,
    width: usize,
}

And one other helpful thing. I realized you can package probably any mutable data in this generic structure:

struct Container {
    mutex: Mutex<MyStruct>,
}

rustler::init!(
    "Elixir.MyNif",
    [func1, func2],
    load = |env: Env, _| {
        rustler::resource!(Container, env);
        true
    }
);

So you put whatever you want into MyStruct, and you wrap it up for elixir like this…

let my_new_struct = MyStruct { ... };
let mutex = Mutex::new(my_new_struct);
let container = Container { mutex };
Ok(ResourceArc::new(container))

…then you can receive the same thing back, lock the mutex, unpack it, and do whatever mutations you need.

#[rustler::nif]
fn print(arc: ResourceArc<Container>) {
    arc.mutex.lock().unwrap().print();
}

I’m happy to say that I have everything working in my project, have a look at master if you’re interested.

dimitarvp

dimitarvp

Oh, I did exactly the same for my sqlite3 library! Glad that you found the idiom!

Sigh, I should start blogging on these topics. I know it will help a lot of people.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
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

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement