Skip to content

Commit 6fa0dae

Browse files
authored
feat: filter builder, select, heartbeat telemetry and presence fixes (#44)
## Problem Several parity and correctness gaps remained: - postgres_changes bindings ignored `select`, so wide rows were sent in full. - Heartbeat health and round-trip latency were tracked internally but not observable. - There was no typed filter builder, only raw filter strings. - `presence_state` was read from the wrong nesting level (always empty), and presence diffs replaced whole keys instead of merging per `phx_ref`. - The HTTP fallback broadcast sent the prefixed `realtime:` topic and omitted `private`, so private-channel broadcasts failed authorization. - A spurious "no callback" warning fired when zero channels matched. ## Solution Add `Supabase.Realtime.Filter`, a pure typed builder with PostgREST quoting; accept `select` on postgres_changes bindings; emit `[:supabase, :realtime, :heartbeat]` telemetry with status and latency; add `Supabase.Realtime.Presence` with a per-`phx_ref` diff merge; fix the presence read path and the HTTP fallback body; and quiet the zero-channel warning. ## Rationale The filter builder is pure data in, wire string out, so it lives in the functional core and raises on invalid input while the `on/3` boundary still returns tuples. Telemetry is used instead of a callback because it composes and is idiomatic on the BEAM. The presence merge ports phoenix's `syncDiff` so multi-device presence stays correct.
1 parent 3aec1d6 commit 6fa0dae

18 files changed

Lines changed: 1532 additions & 54 deletions

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,15 @@ MyApp.Realtime.on(channel, "postgres_changes",
121121
event: :update, schema: "public", table: "users",
122122
filter: "id=eq.1"
123123
)
124+
125+
# With the typed filter builder and a column select list
126+
alias Supabase.Realtime.Filter
127+
128+
MyApp.Realtime.on(channel, "postgres_changes",
129+
event: :update, schema: "public", table: "users",
130+
filter: Filter.new() |> Filter.eq("id", 1) |> Filter.lt("age", 30),
131+
select: ["id", "first_name"]
132+
)
124133
```
125134

126135
### Broadcast Messages

‎guides/usage.md‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,12 @@ Set a custom presence key:
141141
{:ok, channel} = MyApp.Realtime.channel("room:lobby", presence: [key: "user_123"])
142142
```
143143

144+
The full presence state (what `{:presence, :sync, state}` receives) mirrors
145+
the server's map exactly: keys are presence keys, each entry holds a
146+
`metas` list. Multiple devices per key are supported: joins/leaves merge
147+
per `phx_ref` instead of replacing the whole key, so a second device
148+
joining adds its meta next to the first one's.
149+
144150
## Postgres Changes
145151

146152
Subscribe to database changes:
@@ -163,8 +169,61 @@ Subscribe to database changes:
163169
event: :update, schema: "public", table: "messages",
164170
filter: "room_id=eq.42"
165171
)
172+
173+
# With a typed filter builder and a column select list
174+
alias Supabase.Realtime.Filter
175+
176+
:ok = MyApp.Realtime.on(channel, "postgres_changes",
177+
event: :update, schema: "public", table: "messages",
178+
filter: Filter.new() |> Filter.eq("room_id", 42) |> Filter.lt("age", 30),
179+
select: ["id", "body"]
180+
)
166181
```
167182

183+
### Filter Builder
184+
185+
`Supabase.Realtime.Filter` builds the postgres_changes `filter` string with
186+
PostgREST operator syntax and quoting:
187+
188+
```elixir
189+
alias Supabase.Realtime.Filter
190+
191+
Filter.new() |> Filter.eq("id", 1) |> Filter.lt("age", 30) |> Filter.build()
192+
#=> "id=eq.1,age=lt.30"
193+
194+
Filter.within("status", ["active", "pending"])
195+
#=> status=in.(active,pending)
196+
197+
Filter.negate("deleted_at", :is, nil)
198+
#=> deleted_at=not.is.null
199+
```
200+
201+
Values containing reserved characters (`,` `(` `)` `"` `\`) or surrounding
202+
whitespace are double-quoted and escaped the way PostgREST does
203+
(`"a,b"`), so they survive the server's filter parser; all other values are
204+
sent verbatim. Invalid input raises at build time (it is an authoring-time
205+
error, not a runtime failure): `within/3` requires a non-empty list of
206+
scalars, `is/3` only accepts `nil`, booleans and the `"null" | "true" |
207+
"false" | "unknown"` keywords, and `negate/4` raises for unknown operators.
208+
209+
Pass the struct directly as the `:filter` value of `on/3`; it is serialized
210+
automatically.
211+
212+
### Column Select
213+
214+
The optional `:select` list restricts the columns the server sends back in
215+
the change payload's `record`:
216+
217+
```elixir
218+
:ok = MyApp.Realtime.on(channel, "postgres_changes",
219+
event: :insert, schema: "public", table: "messages",
220+
select: ["id", "body"]
221+
)
222+
```
223+
224+
It must be a non-empty list of column names, otherwise `on/3` returns
225+
`{:error, :invalid_select}`.
226+
168227
Handle the events:
169228

170229
```elixir
@@ -199,6 +258,24 @@ def handle_event({:connection, :state_change, %{old: old, new: new}}) do
199258
end
200259
```
201260

261+
## Heartbeat Telemetry
262+
263+
The connection emits `[:supabase, :realtime, :heartbeat]` telemetry events:
264+
`:sent` when a heartbeat goes out, `:ok` (with a `latency` measurement in
265+
milliseconds) when the server replies, and `:timeout` when a heartbeat went
266+
unanswered by the next tick. `latency` is present only on `:ok`; metadata
267+
carries `status`, the heartbeat `ref` and the client `base_url`:
268+
269+
```elixir
270+
:telemetry.attach("my-heartbeat", [:supabase, :realtime, :heartbeat], fn _e, m, md, _c ->
271+
case md.status do
272+
:sent -> :ok
273+
:ok -> MyApp.Metrics.observe("realtime.heartbeat.latency", m.latency)
274+
:timeout -> MyApp.Metrics.increment("realtime.heartbeat.timeouts")
275+
end
276+
end, nil)
277+
```
278+
202279
## Token Refresh
203280

204281
If your access token expires, provide an `:access_token_fn` when starting:

‎lib/supabase/realtime.ex‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,12 +235,18 @@ defmodule Supabase.Realtime do
235235
@type postgres_changes_event_type :: :all | :insert | :update | :delete
236236
@typedoc """
237237
Filter for PostgreSQL database changes.
238+
239+
The `:filter` value is either the wire string (PostgREST syntax) or a
240+
`Supabase.Realtime.Filter` struct, which `on/3` serializes automatically.
241+
The optional `:select` list restricts the columns the server sends back in
242+
the change payload's `record`.
238243
"""
239244
@type postgres_changes_filter :: %{
240245
required(:event) => postgres_changes_event_type() | String.t(),
241246
required(:schema) => String.t(),
242247
optional(:table) => String.t(),
243-
optional(:filter) => String.t()
248+
optional(:filter) => String.t() | Supabase.Realtime.Filter.t(),
249+
optional(:select) => [String.t()]
244250
}
245251
@type postgres_change_event ::
246252
{:postgres_changes, postgres_changes_event_type(), postgres_changes_filter()}
@@ -398,6 +404,17 @@ defmodule Supabase.Realtime do
398404
Realtime.on(channel, "broadcast", event: "new_message")
399405
Realtime.on(channel, "presence", event: "join")
400406
407+
# With a typed filter builder and a column `select` list
408+
alias Supabase.Realtime.Filter
409+
410+
Realtime.on(channel, "postgres_changes",
411+
event: :update,
412+
schema: "public",
413+
table: "users",
414+
filter: Filter.new() |> Filter.eq("id", 1) |> Filter.lt("age", 30),
415+
select: ["id", "first_name"]
416+
)
417+
401418
## Returns
402419
403420
* `:ok` - The binding was stored
@@ -407,6 +424,8 @@ defmodule Supabase.Realtime do
407424
join payload, so they cannot be added after the join started)
408425
* `{:error, :already_joined}` - Same, while the channel is joined. Broadcast
409426
bindings are allowed at any time.
427+
* `{:error, :invalid_select}` - A `postgres_changes` `select:` was given
428+
that is not a non-empty list of column names
410429
"""
411430
@spec on(channel(), String.t(), event_filter()) :: :ok | {:error, term()}
412431
def on(%Channel{} = channel, type, filter) when is_binary(type) and (is_list(filter) or is_map(filter)) do

‎lib/supabase/realtime/channel.ex‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ defmodule Supabase.Realtime.Channel do
4646
"""
4747

4848
alias Supabase.Realtime
49+
alias Supabase.Realtime.Filter
4950

5051
@typedoc """
5152
Channel structure for Supabase Realtime subscriptions.
@@ -151,6 +152,36 @@ defmodule Supabase.Realtime.Channel do
151152
}
152153
end
153154

155+
@doc """
156+
Parses and validates a binding filter for `type`.
157+
158+
For `"postgres_changes"`: serializes a `%Supabase.Realtime.Filter{}`
159+
given as the `:filter` value into its wire string, validates the optional
160+
`:select` column list (a non-empty list of binaries; an empty list or any
161+
non-binary element is rejected), and keeps the rest of the filter as-is.
162+
163+
For other types: keyword-to-map conversion and `event: :all`
164+
normalization (existing behavior).
165+
"""
166+
@spec normalize_filter(String.t(), map() | keyword()) :: {:ok, map()} | {:error, :invalid_select}
167+
def normalize_filter(type, filter) when is_binary(type) do
168+
filter = if is_list(filter), do: Map.new(filter), else: filter
169+
filter = normalize_event_filter(filter)
170+
171+
if type == "postgres_changes" do
172+
normalize_postgres_filter(filter)
173+
else
174+
{:ok, filter}
175+
end
176+
end
177+
178+
@doc """
179+
Whether this channel was created with `private: true` (RLS-protected).
180+
"""
181+
@spec private?(t()) :: boolean()
182+
def private?(%__MODULE__{params: %{config: %{private: private}}}), do: !!private
183+
def private?(_), do: false
184+
154185
@doc """
155186
Updates the channel state.
156187
@@ -445,6 +476,27 @@ defmodule Supabase.Realtime.Channel do
445476

446477
# Private helper functions
447478

479+
defp normalize_postgres_filter(%{filter: %Filter{} = f} = filter) do
480+
{:ok, %{filter | filter: Filter.build(f)}}
481+
end
482+
483+
defp normalize_postgres_filter(filter) do
484+
case Map.get(filter, :select) do
485+
nil -> {:ok, filter}
486+
select -> if valid_select?(select), do: {:ok, filter}, else: {:error, :invalid_select}
487+
end
488+
end
489+
490+
# A meaningful `select` is a non-empty list of column names. JS has no
491+
# runtime validation (its type says string[]); an empty array is never
492+
# meaningful on the wire, so it is rejected explicitly instead of being a
493+
# silent no-op.
494+
defp valid_select?(select) when is_list(select) and select != [] do
495+
Enum.all?(select, &is_binary/1)
496+
end
497+
498+
defp valid_select?(_), do: false
499+
448500
defp binding_match?(binding, filter) do
449501
filter_keys = Map.keys(filter)
450502

‎lib/supabase/realtime/channel/registry.ex‎

Lines changed: 39 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ defmodule Supabase.Realtime.Channel.Registry do
3838
alias Supabase.Realtime.Channel.Store
3939
alias Supabase.Realtime.Connection
4040
alias Supabase.Realtime.PostgresTypes
41+
alias Supabase.Realtime.Presence
4142

4243
require Logger
4344

@@ -110,6 +111,11 @@ defmodule Supabase.Realtime.Channel.Registry do
110111
join payload, so they cannot be added after the join started). Broadcast
111112
bindings are allowed at any time.
112113
114+
For `postgres_changes` bindings, the `:filter` value may be a
115+
`%Supabase.Realtime.Filter{}` struct (serialized here) and the `:select`
116+
option must be a non-empty list of column names, else the call returns
117+
`{:error, :invalid_select}`.
118+
113119
## Parameters
114120
115121
* `server` - The server PID or name
@@ -118,7 +124,7 @@ defmodule Supabase.Realtime.Channel.Registry do
118124
* `filter` - The event filter
119125
"""
120126
@spec subscribe(GenServer.server(), Channel.t(), String.t(), map() | keyword()) ::
121-
:ok | {:error, :channel_not_found | :already_joined | :already_joining}
127+
:ok | {:error, :channel_not_found | :already_joined | :already_joining | :invalid_select}
122128
def subscribe(server, %Channel{} = channel, type, filter) do
123129
GenServer.call(server, {:subscribe, channel, type, filter})
124130
end
@@ -206,14 +212,7 @@ defmodule Supabase.Realtime.Channel.Registry do
206212
{:reply, {:error, error}, state}
207213

208214
{:ok, found} ->
209-
{:ok, updated} = Store.add_binding(state.store, found, type, filter)
210-
211-
if updated.state in [:closed, :errored] do
212-
{:reply, :ok, state, {:continue, {:join, updated}}}
213-
else
214-
# broadcast bindings on a joining/joined channel
215-
{:reply, :ok, state}
216-
end
215+
subscribe_binding(found, type, filter, state)
217216

218217
{:error, :not_found} ->
219218
{:reply, {:error, :channel_not_found}, state}
@@ -241,6 +240,25 @@ defmodule Supabase.Realtime.Channel.Registry do
241240
{:reply, state.presence_state, state}
242241
end
243242

243+
# normalize before store: an invalid filter is replied as an error without
244+
# being stored
245+
defp subscribe_binding(found, type, filter, state) do
246+
case Channel.normalize_filter(type, filter) do
247+
{:ok, filter} ->
248+
{:ok, updated} = Store.add_binding(state.store, found, type, filter)
249+
250+
if updated.state in [:closed, :errored] do
251+
{:reply, :ok, state, {:continue, {:join, updated}}}
252+
else
253+
# broadcast bindings on a joining/joined channel
254+
{:reply, :ok, state}
255+
end
256+
257+
{:error, :invalid_select} ->
258+
{:reply, {:error, :invalid_select}, state}
259+
end
260+
end
261+
244262
@impl true
245263
def handle_cast({:connection_state_changed, old, new}, state) do
246264
channels = Store.all(state.store)
@@ -464,20 +482,18 @@ defmodule Supabase.Realtime.Channel.Registry do
464482
end
465483

466484
defp handle_presence_state(channels, payload, state) do
467-
new_state = %{state | presence_state: Map.get(payload, "state", %{})}
468-
dispatch_event(new_state, channels, {:presence, :sync, new_state.presence_state})
485+
# bug 20: the server sends the state map DIRECTLY as the payload
486+
new_state = %{state | presence_state: payload}
487+
dispatch_event(new_state, channels, {:presence, :sync, payload})
469488
{:noreply, new_state}
470489
end
471490

472491
defp handle_presence_diff(channels, payload, state) do
473492
joins = Map.get(payload, "joins", %{})
474493
leaves = Map.get(payload, "leaves", %{})
475494

476-
# Update presence state
477-
new_state =
478-
state
479-
|> add_presence_joins(joins)
480-
|> remove_presence_leaves(leaves)
495+
# bug 21: per-phx_ref merge instead of per-key clobber
496+
new_state = %{state | presence_state: Presence.sync_diff(state.presence_state, payload)}
481497

482498
# Dispatch joins/leaves events if present
483499
if map_size(joins) != 0,
@@ -529,7 +545,6 @@ defmodule Supabase.Realtime.Channel.Registry do
529545

530546
defp maybe_update_binding_ids(_channel, _payload, _state), do: :ok
531547

532-
# Helper to dispatch events to the callback module if available
533548
# Wire-event dispatch. One function head per event keeps each clause's
534549
# cyclomatic complexity flat as the event table grows.
535550
defp dispatch_message("phx_close", msg, state), do: handle_phx_close(msg_topic(msg), state)
@@ -564,35 +579,18 @@ defmodule Supabase.Realtime.Channel.Registry do
564579
defp msg_payload(msg), do: Map.get(msg, "payload", %{})
565580
defp topic_channels(msg, state), do: Store.find_all_by_topic(state.store, msg_topic(msg))
566581

567-
defp dispatch_event(state, channels, event) do
568-
if channels != [] and function_exported?(state.module, :handle_event, 1) do
582+
# Helper to dispatch events to the callback module if available. Zero
583+
# matching channels is a normal no-op, not a missing callback; the warning
584+
# stays for the genuinely-missing-callback case with channels present.
585+
defp dispatch_event(_state, [], _event), do: :ok
586+
587+
defp dispatch_event(state, _channels, event) do
588+
if function_exported?(state.module, :handle_event, 1) do
569589
Task.start(fn ->
570590
:ok = state.module.handle_event(event)
571591
end)
572592
else
573593
Logger.warning("No handle_event/1 callback defined in #{state.module}")
574594
end
575595
end
576-
577-
# Helper to add presences (joins)
578-
defp add_presence_joins(state, joins) do
579-
presences =
580-
Enum.reduce(joins, state.presence_state, fn {key, presence}, acc ->
581-
Map.put(acc, key, presence)
582-
end)
583-
584-
%{state | presence_state: presences}
585-
end
586-
587-
# Helper to remove presences (leaves)
588-
defp remove_presence_leaves(state, leaves) do
589-
presences =
590-
leaves
591-
|> Map.keys()
592-
|> Enum.reduce(state.presence_state, fn key, acc ->
593-
Map.delete(acc, key)
594-
end)
595-
596-
%{state | presence_state: presences}
597-
end
598596
end

0 commit comments

Comments
 (0)