sreyansjain

sreyansjain

Hi I am trying to use Server Sent Events.
I want to send chunked responses.

I am able to send them like so

conn
      |> put_resp_header("cache-control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("content-type", "text/event-stream;")
      |> send_chunked(200)
      |> chunk("This is some respsonse")

The responses are being sent, but without gzip compression.
How do i get responses to be sent with gzip compression?

I am using the latest phoenix with latest bandit.
Please advise.

PS If I don’t send chunked response, it gets compressed. For ex -

conn
      |> put_resp_header("cache-control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("content-type", "text/event-stream;")
      |> text("This would get compressed")

Is some magic happening in the text/2 method?

Showing Posts 1 to 3

sreyansjain

sreyansjain OP

Got it to work.
We need to set the content-encoding to gzip
and then manually compress the responses like so

conn
      |> put_resp_header("cache-control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("content-type", "text/event-stream;")
      |> put_resp_header("content-encoding", "gzip")
      |> send_chunked(200)

And then compress the message manually and send them

defp send_chunk(conn, message) do
    message = :zlib.gzip(message)
    {:ok, conn} =
      conn
      |> prepare_sse()
      |> chunk(message)
    conn
  end
hubertlepicki

hubertlepicki

thank you for reporting back, I am sure it’ll be useful to someone

sreyansjain

sreyansjain OP

SSE compression in long lived connection for streaming updates –

# lib/aet_web/controllers/sse_controller.ex
defmodule AetWeb.SseController do
  use AetWeb, :controller

  def stream(conn, _params) do
    conn =
      conn
      |> put_resp_header("content-type", "text/event-stream")
      |> put_resp_header("content-encoding", "gzip")
      |> put_resp_header("cache-control", "no-cache")
      # |> put_resp_header("connection", "keep-alive")
      |> send_chunked(200)

    # Initialize zlib compression context with gzip wrapper
    z = :zlib.open()
    :ok = :zlib.deflateInit(z, 9, :deflated, 31, 8, :default)  # 31 = gzip format

    # Subscribe to PubSub
    Phoenix.PubSub.subscribe(Aet.PubSub, "events")

    # Start streaming
    try do
      stream_events(conn, z)
    after
      # IO.puts("Finalizing stream...")
      compressed_end = :zlib.deflate(z, "", :finish)
      # IO.inspect(compressed_end, label: "Final chunk")
      Plug.Conn.chunk(conn, compressed_end)
      cleanup_zlib(z)
    end
  end

  defp stream_events(conn, z) do
    receive do
      {:event, data} ->
        # Compress incrementally with sync flush
        compressed_chunk = :zlib.deflate(z, data, :sync)  # :sync flushes immediately

        case Plug.Conn.chunk(conn, compressed_chunk) do
          {:ok, conn} ->
            IO.puts("Chunk sent successfully")
            stream_events(conn, z)
          {:error, :closed} ->
            IO.puts("Client disconnected")
            conn  # Cleanup handled in `after` clause
        end
    after
      1000 ->  # Timeout to prevent infinite loop if no events
        IO.puts("No events received in 1s, continuing...")
        stream_events(conn, z)
    end
  end

  defp cleanup_zlib(z) do
    IO.puts("Cleaning up zlib context...")
    case :zlib.deflateEnd(z) do
      :ok -> :zlib.close(z)
      error ->
        IO.inspect(error, label: "DeflateEnd error")
        :zlib.close(z)
    end
  rescue
    e ->
      IO.inspect(e, label: "Cleanup error")
      :zlib.close(z)
  end
end
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews