Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

9.5 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { NODE_ENV } from "@carbon/env";
import { getLogger } from "@carbon/logger";
import { toast, useCarbon } from "@carbon/react";
import type { RealtimeChannel, SupabaseClient } from "@supabase/supabase-js";
import { REALTIME_SUBSCRIBE_STATES } from "@supabase/supabase-js";
import { useCallback, useEffect, useRef } from "react";

const log = getLogger("react", "realtime-channel");

// Browsers throttle a hidden tab's timers hard after five minutes, so the
// socket's heartbeat can no longer vouch for it. Before that a joined channel
// is live and still receiving, and reconnecting it only reloads the page.
const RECONNECT_AFTER_HIDDEN_MS = 5 * 60_000;

// One "Realtime disconnected" toast however many channels are down: they share
// its id, and it goes when the last channel that is down reconnects or unmounts.
const DISCONNECTED_TOAST_ID = "realtime-disconnected";
const disconnectedChannels = new Set<object>();

function showDisconnected(channel: object) {
  disconnectedChannels.add(channel);
  toast.loading("Realtime disconnected", {
    id: DISCONNECTED_TOAST_ID,
    description: "Trying to reconnect…",
    duration: Number.POSITIVE_INFINITY,
    dismissible: false
  });
}

function clearDisconnected(channel: object) {
  if (disconnectedChannels.delete(channel) && disconnectedChannels.size === 0) {
    toast.dismiss(DISCONNECTED_TOAST_ID);
  }
}

function formatSubscribeErr(err: unknown): string {
  if (err == null) return "No error details";
  if (typeof err === "string") return err.trim() || "No error details";
  if (err instanceof Error) return err.message || "No error details";
  if (typeof err === "object") {
    const o = err as Record<string, unknown>;
    if (typeof o.message === "string" && o.message.trim()) return o.message;
  }
  try {
    return JSON.stringify(err);
  } catch {
    return String(err);
  }
}

interface UseRealtimeChannelOptions<TDeps extends any[]> {
  topic: string;
  setup: (
    channel: RealtimeChannel,
    carbon: SupabaseClient,
    deps: TDeps
  ) => RealtimeChannel;
  enabled?: boolean;
  dependencies?: TDeps;
  /**
   * Join a private channel: Realtime checks the `realtime.messages` policies
   * for this topic once, at join. Every broadcast topic is private.
   */
  private?: boolean;
  /**
   * Called on each successful join. `isReconnect` is true after the first: no
   * message is replayed, so the caller catches up on what it missed.
   */
  onSubscribed?: (isReconnect: boolean) => void;
  /** When true, CHANNEL_ERROR / TIMED_OUT open a toast. Defaults to true in dev, false in prod. */
  notifyOnSubscribeError?: boolean;
}

export const useRealtimeChannel = <TDeps extends any[]>(
  options: UseRealtimeChannelOptions<TDeps>
) => {
  const {
    topic,
    setup,
    enabled = true,
    dependencies = [],
    private: isPrivate = false,
    onSubscribed,
    notifyOnSubscribeError = NODE_ENV === "development"
  } = options;
  const channelRef = useRef<RealtimeChannel | null>(null);
  const isTearingDownRef = useRef(false);
  const toastKeyRef = useRef({});
  const retryCountRef = useRef(0);
  const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const isSilentReconnectRef = useRef(false);
  // Updated each effect run so the retry timer always calls the latest subscribe closure.
  const doSubscribeRef = useRef<() => Promise<void>>(() => Promise.resolve());
  const hasSubscribedRef = useRef(false);
  const onSubscribedRef = useRef(onSubscribed);
  onSubscribedRef.current = onSubscribed;
  const { carbon, isRealtimeAuthSet } = useCarbon();

  // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
  const memoSetup = useCallback(setup, [topic, ...dependencies]);

  // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
  useEffect(() => {
    if (!carbon) return;

    // Define teardown inline - NOT in dependency array
    const teardown = async () => {
      if (isTearingDownRef.current) return;

      const channel = channelRef.current;
      if (!channel) return;

      isTearingDownRef.current = true;
      try {
        // Add timeout to prevent hanging indefinitely
        await Promise.race([
          carbon.removeChannel(channel),
          new Promise((_, reject) =>
            setTimeout(() => reject(new Error("Channel removal timeout")), 5000)
          )
        ]);
      } catch (error) {
        log.error("Error removing channel", { topic, error });
      } finally {
        channelRef.current = null;
        isTearingDownRef.current = false;
      }
    };

    if (!isRealtimeAuthSet || !enabled) {
      if (retryTimerRef.current) {
        clearTimeout(retryTimerRef.current);
        retryTimerRef.current = null;
      }
      retryCountRef.current = 0;
      void teardown();
      return;
    }

    const doSubscribe = async () => {
      // Ensure previous instance is gone before creating a new one
      if (channelRef.current) {
        await teardown();
      }

      try {
        const channel = isPrivate
          ? carbon.channel(topic, { config: { private: true } })
          : carbon.channel(topic);
        const configuredChannel = memoSetup(
          channel,
          carbon,
          dependencies as TDeps
        );
        channelRef.current = configuredChannel;

        configuredChannel.subscribe(async (status, err) => {
          if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
            retryCountRef.current = 0;
            onSubscribedRef.current?.(hasSubscribedRef.current);
            hasSubscribedRef.current = true;
            clearDisconnected(toastKeyRef.current);
            return;
          }

          const isRetriableError =
            status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR ||
            status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT;

          if (
            isRetriableError &&
            notifyOnSubscribeError &&
            !isSilentReconnectRef.current
          ) {
            // A calm "reconnecting" indicator rather than a red toast; the
            // underlying error is only logged.
            if (err) {
              log.warning("Realtime subscribe error", {
                topic,
                status,
                error: formatSubscribeErr(err)
              });
            }
            showDisconnected(toastKeyRef.current);
          }

          if (isRetriableError) {
            await teardown();
            // Exponential backoff: 1s, 2s, 5s, 10s, 30s, 60s max — faster
            // recovery on transient blips, still polite at steady state.
            const schedule = [1_000, 2_000, 5_000, 10_000, 30_000, 60_000];
            const delay =
              schedule[Math.min(retryCountRef.current, schedule.length - 1)]!;
            retryCountRef.current++;
            retryTimerRef.current = setTimeout(() => {
              retryTimerRef.current = null;
              void doSubscribeRef.current();
            }, delay);
          } else if (status === REALTIME_SUBSCRIBE_STATES.CLOSED) {
            await teardown();
          }
        });
      } catch (error) {
        log.error("Failed to subscribe to realtime channel", {
          topic,
          error
        });
        if (notifyOnSubscribeError) {
          toast.error(`Realtime setup failed (${topic})`, {
            description:
              error instanceof Error ? error.message : formatSubscribeErr(error)
          });
        }
      }
    };

    // Keep ref up-to-date so retry timers always call the latest closure.
    doSubscribeRef.current = doSubscribe;
    hasSubscribedRef.current = false;
    void doSubscribe();

    const forceReconnect = (silent: boolean) => {
      if (retryTimerRef.current) {
        clearTimeout(retryTimerRef.current);
        retryTimerRef.current = null;
      }
      retryCountRef.current = 0;
      isSilentReconnectRef.current = silent;
      void doSubscribeRef.current().finally(() => {
        isSilentReconnectRef.current = false;
      });
    };

    // A tab that was hidden for long may hold a dead socket, so it reconnects.
    // Time in another tab does not: every reconnect reloads the page's data,
    // since nothing is replayed.
    let hiddenAt: number | null = null;
    const handleVisibilityChange = () => {
      if (document.visibilityState !== "visible") {
        hiddenAt = performance.now();
        return;
      }
      const hiddenFor = hiddenAt === null ? 0 : performance.now() - hiddenAt;
      hiddenAt = null;
      if (
        hiddenFor >= RECONNECT_AFTER_HIDDEN_MS ||
        channelRef.current?.state !== "joined"
      ) {
        forceReconnect(true);
      }
    };
    const handleOnline = () => forceReconnect(true);

    document.addEventListener("visibilitychange", handleVisibilityChange);
    window.addEventListener("online", handleOnline);

    // Cleanup on unmount or dependency change
    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
      window.removeEventListener("online", handleOnline);
      if (retryTimerRef.current) {
        clearTimeout(retryTimerRef.current);
        retryTimerRef.current = null;
      }
      retryCountRef.current = 0;
      clearDisconnected(toastKeyRef.current);
      void teardown();
    };
  }, [
    carbon,
    isRealtimeAuthSet,
    enabled,
    topic,
    isPrivate,
    memoSetup,
    notifyOnSubscribeError
    // teardown/doSubscribe are NOT in dependencies - defined inline
  ]);

  return channelRef;
};