Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

1.4 KB
Raw Blame
import { logger, toErrorFields } from "@/lib/axiom/server";
import { conn } from "@/lib/planetscale";
import { redis } from "../redis";
import { RedisStream } from "./client";

const STREAM_KEY = "link:click:events";

export const linkClickEventStream = new RedisStream(STREAM_KEY);

export interface LinkClickEvent {
  linkId: string;
  timestamp: string;
  workspaceId?: string;
}

// Publishes a link click event to the stream to update:
// - link clicks count + lastClicked timestamp
// - workspace usage + totalClicks
export const publishLinkClickEvent = async ({
  linkId,
  timestamp,
  workspaceId,
}: LinkClickEvent) => {
  const payload = {
    linkId,
    timestamp,
    ...(workspaceId && { workspaceId }),
  };

  try {
    return await redis.xadd(STREAM_KEY, "*", payload);
  } catch (error) {
    logger.error("stream.publish_failed", {
      service: "upstash",
      streamKey: STREAM_KEY,
      error: toErrorFields(error),
      correlation: {
        linkId,
        workspaceId,
      },
    });

    return await Promise.allSettled([
      conn.execute(
        "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
        [linkId],
      ),

      workspaceId
        ? conn.execute(
            "UPDATE Project p SET p.usage = p.usage + 1, p.totalClicks = p.totalClicks + 1 WHERE id = ?",
            [workspaceId],
          )
        : null,

      logger.flush(),
    ]);
  }
};