RudolfVonKrugstein

RudolfVonKrugstein

Serving a file while it is being created in memory using chunked transfer

Hi,

I am new to elixir and phoenix and I am trying to solve the following problem:

In my application I create an audio file (using a tts system) that takes a while to create (up to several seceonds).

I want http clients (well, the browser) to be apple to get/stream that file:

  • while it is created
  • after it is created

I build a solution for this, but it feels kind of complicated. As I am an absolute beginner and not very experienced on how to build good solutions with elixir, I wonder if someone could give me some input on how to better solve this, or maybe even use existing solutions that I am not aware of. So maybe someone has some input on this?

My solution consists of:

  • an audio file provider, hat creates the audio file form tts
  • an Audio Buffer, that holds the audio created to far in memory. This is implemented as a GenServer.
  • an Audiofile Controller, that works as a phoenix controller and serves the audio file to the browser using chunked transfer

The Process is now like this:

  1. The TTS Creator starts working and sends data to the Audio Buffer GenServer
  2. The Browser requests the file from the Audiofile controller
  3. The controller ask the Audio Buffer for the data so far and …
  4. Receive the buffer with the data so far, which the controller sends to the browser.
  5. If the file is not yet finished, the Audiofile Controller has to receive the remaining data as it is created. For this I use the Phoenix PubSub on the “audiofile” topic, to which the Audiofile Controller subscribes and sends to the Browser the received data to the Browser.
┌───────────────┐    1    ┌──────────────────────┐                   
│               │  send   │                      │   5 send more data
│  TTS Creator  ├─────────►     Audio Buffer     ├───────────┐       
│               │  data   │                      │           │       
└───────────────┘         └────────▲────┬────────┘           │       
                          3 ask for│    │ 4 send        ┌────▼────┐  
                            data   │    │ data buffer   │ PubSub  │  
                       ┌───────────┴────▼─────────┐     └────┬────┘  
                       │                          │          │       
                       │   Audiofile Controller   ◄──────────┘       
                       │                          │                  
                       └─────────────▲────────────┘                  
                                     │2                              
                                     │Download AudioFile             
                              ┌──────┴─────┐                         
                              │            │                         
                              │  Browser   │                         
                              │            │                         
                              └────────────┘                         

For this I have implemented the AudioController like this (simplified pseudo code):

defmodule MyAppWeb.AudiofileController do
  use MyAppWeb, :controller
  require Logger

  def show(conn, %{"fileid" => file_id}) do
    # make sure we dont miss any messages ...
    MyAppWeb.Endpoint.subscribe("audiofiles")

    case FileStorage.get_file_data(file_id) do
      {:ok, data} ->
        conn = send_chunked(conn, 200)

        send_chunked_file(conn, file_id)
      # other cases
    end
  end

  def send_chunked_file(conn, file_id) do
    receive do
      %Phoenix.Socket.Broadcast{
        topic: "audiofiles",
        event: "filedata",
        payload: {:file_data, name, new_data}
      }
      when name == file_id ->
        conn
        |> chunk(new_data)

        send_chunked_file(conn, file_id)

      %Phoenix.Socket.Broadcast{
        topic: "audiofiles",
        event: "finish",
        payload: {:finish_file, name}
      }
      when name == file_id ->
        # we are done
        conn
    after
      5_000 ->
        Logger.error("Waiting for file #{file_id} timed out")
        conn
    end
  end
end

Especially the fiddling around with the PubSub Messages feels a little, like it could be better. Also this design means, that if multiple files are created in parallel, the PubSub messages from the Audio Buffer reach all Audiofile Controllers, even those serving other files than the one the PubSub message is for.

Does anyone have some Ideas for an more idiomatic way of doing this?

Thank you guys!

Most Liked

Hermanverschooten

Hermanverschooten

If you send self() to the function that now broadcasts on the pubsub, you can use Process.send/3 to send back the data, skipping the pubsub altogether and avoid that issue.

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