christhekeele

christhekeele

How to use Popcorn for isomorphic Elixir?

This is a bit of a hare-brained experiment, but I’d like to try using Popcorn for isomorphic Elixir, that is, to run the same Elixir code on the backend and frontend in the same project.

The core problem I am having is that I cannot tell what mix popcorn.cook is actually bundling up and have no visibility into contents of the bundle to verify my setup.

The core symptom I am experiencing is that debug logging tells me popcorn found my bundle.avm on the client, but the Popcorn.init Promise times out (and so therefore must never be finding my code that calls Popcorn.Wasm.register/1).

The setup isn’t trivial to minimally reproduce, and I’m sure whatever I’m doing wrong is not subtle, so I’ll summarize here in hopes of exposing a glaring conceptual misunderstanding. (I am happy to create the not-so-minimal-example anyways, as a submission to Popcorn examples if nothing else, but would rather get things working first before extracting my approach.) Also seeking any feedback on this approach.

  1. Popcorn appears to operate at the Application level of distribution, which makes sense. So I’ve set up an umbrella application with a Phoenix web app and a Popcorn sim app.
  2. In my config.exs I capture the MIX_ENV via config_target() and compile it into my applications’ envs and make it available at runtime on each Application, ex
    def target, do: Application.compile_env!(:sim, :target)
  3. I have popcorn.cook configured to always use :wasm for its target.
  4. I have popcorn configured to emit everything into the web apps’s assets directory.
  5. I require popcorn.js in my app.js bundle and call (async () => Popcorn.init(...))().then(popcorn => console.log(popcorn)) there.
  6. I copy over all of popcorn’s output, including the bundle, into my priv/static/assets to be served by Plug.Static.
  7. I also require the sim application as in_umbrella from my web application and add it to the list of extra_applications so that it starts in the backend as well as on page load.
  8. The sim application just starts a module-based DynamicSupervisor. In the module’s init method, before returning DynamicSupervisor.init(strategy: :one_for_one), I call:
if Simulation.Application.target() == :wasm do
  Popcorn.Wasm.register(__MODULE__)
end

The idea here is that sim gets started both in backend and frontend, and can start a worker with the same code in either place (with the right invocation of JS or Elixir). Simulation.Application.target() can be consulted to navigate any difference in behaviour required for where it is running.

Everything seems to work asset-wise, Popcorn.init is definitely finding my static bundle.avm asset and trying to start it, however the promise always times out, so it seems to not actually have sim correctly bundled and starting inside, or at least Popcorn.Wasm.register(__MODULE__) must never get called. Or I’m fat-fingering awaiting promises somehow, I guess. I have no idea how to debug from here!

I have tried making the register unconditional in case I’m messing up threading along the :wasm target throughout bundling, but the promise still times out so reaching register is unrelated to the target. I’ve tried logging anything in the sim application startup process in hopes of seeing what the target is, or anything at all, and see no console output. Any ideas?

For reference, I am using:

  • Erlang 26.0.2
  • Elixir 1.17.3-otp-26
  • Popcorn github: "software-mansion/popcorn", tag: "v0.1.8.17"

My console.log looks like:

Main: init, params:  {container: undefined, bundlePath: '/assets/js/popcorn/bundle.avm', wasmDir: '/assets/js/popcorn/', debug: true, onStdout: ƒ}
popcorn.js:389

Main: mount, container:  html
popcorn.js:389

Main: init, params:  {container: undefined, bundlePath: '/assets/js/popcorn/bundle.avm', wasmDir: '/assets/js/popcorn/', debug: true, onStdout: ƒ}
popcorn.js:389

Main: mount, container:  <html lang=​"en" data-theme=​"dark">​<head>​…​</head>​<body>​…​</body>​<iframe srcdoc=​"<html>
      <html lang="en" dir="ltr">
          <head>
            <meta name="bundle-path" content="../​/​assets/​js/​popcorn/​bundle.avm" /​>
          </​head>
          <script type="module" src="/​assets/​js/​popcorn/​popcorn.js" defer></​script>
          <script type="module" src="/​assets/​js/​popcorn/​AtomVM.mjs" defer></​script>
          <script type="module" src="/​assets/​js/​popcorn/​popcorn_iframe.js" defer></​script>
          <script type="module" defer>
            import { runIFrame }​ from "/​assets/​js/​popcorn/​popcorn_iframe.js";​
            runIFrame()​;​
          </​script>
      </​html>" style=​"visibility:​ hidden;​ width:​ 0px;​ height:​ 0px;​ border:​ none;​">​…​</iframe>​<iframe srcdoc=​"<html>
      <html lang="en" dir="ltr">
          <head>
            <meta name="bundle-path" content="../​/​assets/​js/​popcorn/​bundle.avm" /​>
          </​head>
          <script type="module" src="/​assets/​js/​popcorn/​popcorn.js" defer></​script>
          <script type="module" src="/​assets/​js/​popcorn/​AtomVM.mjs" defer></​script>
          <script type="module" src="/​assets/​js/​popcorn/​popcorn_iframe.js" defer></​script>
          <script type="module" defer>
            import { runIFrame }​ from "/​assets/​js/​popcorn/​popcorn_iframe.js";​
            runIFrame()​;​
          </​script>
      </​html>" style=​"visibility:​ hidden;​ width:​ 0px;​ height:​ 0px;​ border:​ none;​">​…​</iframe>​</html>​

// Some 30 seconds pass...

Promise timeout
app.ts:17
^ Where I call (async () => Popcorn.init(...))().then(popcorn => console.log(popcorn))

My (relevant) app.ts code looks like:

import { Popcorn } from "./popcorn/popcorn.js";
const popcorn = (async () => Popcorn.init({
    bundlePath: "/assets/js/popcorn/bundle.avm",
    wasmDir: "/assets/js/popcorn/",
    onStdout: console.log,
    debug: true,
}))()
    .then((popcorn) => {
        console.log(popcorn);
        return popcorn;
    })
    .catch((error) => {
        console.log(error);
        return undefined;
    });

Notes:

  • I am setting the right CORS headers to execute WASM on Plug.Static, so that’s not the issue (and I imagine it would manifest itself differently if it was)

Most Liked Switch mode

mat-hek

mat-hek

Membrane Core Team

Hi, can you share the repo so I can reproduce? :wink:

christhekeele

christhekeele

I’ll work up a repro sometime this week!

christhekeele

christhekeele

There are a few improvements to be made to Popcorn’s APIs to support umbrella applications better I might contribute back, but after digging deep into the machinery of popcorn init and sorting out a few problems I still had, no idea what’s up. The AtomVM is definitely starting in browser with the correct bundled Elixir code, and definitely nothing is happening once it does.

Last Post!

christhekeele

christhekeele

@mat-hek I lied, it took a month, but here’s my minimal repro setup broken down into bite-size commits: GitHub - christhekeele/isomorphic_popcorn: Repro of problem setting up isomorphic popcorn · GitHub

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement