-
Notifications
You must be signed in to change notification settings - Fork 0
Add socket.io realtime infrastructure backed by Redis #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
VectoDE
merged 6 commits into
main
from
codex/integrate-socket.io-and-redis-for-real-time-updates
Nov 3, 2025
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
50bca8e
feat: add realtime infrastructure
VectoDE 70858b2
Avoid blocking Prisma writes on realtime queue
VectoDE fa4982d
Guard Prisma realtime registration when middleware unavailable
VectoDE c17c8a0
Fix navigation path guards and realtime typings
VectoDE 9d2a549
Fix Prisma middleware typing for realtime events
VectoDE 69719c0
Define typed parameters for Prisma realtime middleware
VectoDE File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| "use client" | ||
|
|
||
| import type { ReactNode } from "react" | ||
| import { useEffect } from "react" | ||
| import { useRouter } from "next/navigation" | ||
| import { getRealtimeClient } from "@/lib/realtime-client" | ||
|
|
||
| interface RealtimeProviderProps { | ||
| children: ReactNode | ||
| } | ||
|
|
||
| export function RealtimeProvider({ children }: RealtimeProviderProps) { | ||
| const router = useRouter() | ||
|
|
||
| useEffect(() => { | ||
| const controller = new AbortController() | ||
|
|
||
| fetch("/api/socket/io", { signal: controller.signal }).catch(() => { | ||
| // The socket route will respond immediately once the server is ready. | ||
| }) | ||
|
|
||
| const socket = getRealtimeClient() | ||
|
|
||
| if (!socket) { | ||
| controller.abort() | ||
| return | ||
| } | ||
|
|
||
| const handleEvent = () => { | ||
| router.refresh() | ||
| } | ||
|
|
||
| const handleConnect = () => { | ||
| router.refresh() | ||
| } | ||
|
|
||
| socket.on("connect", handleConnect) | ||
|
|
||
| socket.on("realtime:event", handleEvent) | ||
|
|
||
| return () => { | ||
| controller.abort() | ||
| socket.off("realtime:event", handleEvent) | ||
| socket.off("connect", handleConnect) | ||
| } | ||
| }, [router]) | ||
|
|
||
| return <>{children}</> | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| "use client" | ||
|
|
||
| import { io, type Socket } from "socket.io-client" | ||
|
|
||
| let socketInstance: Socket | null = null | ||
|
|
||
| export function getRealtimeClient() { | ||
| if (typeof window === "undefined") { | ||
| return null | ||
| } | ||
|
|
||
| if (!socketInstance) { | ||
| socketInstance = io({ | ||
| path: "/api/socket/io", | ||
| transports: ["websocket", "polling"], | ||
| autoConnect: true, | ||
| reconnection: true, | ||
| reconnectionDelay: 1000, | ||
| reconnectionDelayMax: 5000, | ||
| }) | ||
| } | ||
|
|
||
| return socketInstance | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import type { PrismaClient } from "@prisma/client" | ||
|
|
||
| import { enqueueRealtimeEvent } from "@/lib/realtime-queue" | ||
|
|
||
| const MUTATION_ACTIONS = new Set([ | ||
| "create", | ||
| "createMany", | ||
| "update", | ||
| "updateMany", | ||
| "upsert", | ||
| "delete", | ||
| "deleteMany", | ||
| ]) | ||
|
|
||
| const globalForRealtime = globalThis as unknown as { | ||
| prismaRealtimeRegistered?: boolean | ||
| } | ||
|
|
||
| export function registerPrismaRealtime(prisma: PrismaClient) { | ||
| if (globalForRealtime.prismaRealtimeRegistered) { | ||
| return | ||
| } | ||
|
|
||
| prisma.$use(async (params, next) => { | ||
|
Check failure on line 24 in lib/realtime-events.ts
|
||
| const result = await next(params) | ||
|
|
||
| if (MUTATION_ACTIONS.has(params.action)) { | ||
| const model = params.model ?? "unknown" | ||
|
|
||
| try { | ||
| await enqueueRealtimeEvent(`prisma:${model}:${params.action}`, { | ||
| model, | ||
| action: params.action, | ||
| args: params.args, | ||
| result, | ||
| timestamp: Date.now(), | ||
| }) | ||
| } catch (error) { | ||
| console.error("Failed to enqueue realtime Prisma event", error) | ||
| } | ||
| } | ||
|
|
||
| return result | ||
| }) | ||
|
|
||
| globalForRealtime.prismaRealtimeRegistered = true | ||
| } | ||
|
|
||
| export async function broadcastRealtimeEvent(event: string, payload: unknown) { | ||
| try { | ||
| await enqueueRealtimeEvent(event, payload) | ||
| } catch (error) { | ||
| console.error("Failed to enqueue realtime event", error) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import { Queue, Worker } from "bullmq" | ||
| import type { JobsOptions } from "bullmq" | ||
|
|
||
| import { createRedisConnection, getRedisUrl } from "@/lib/redis" | ||
| import { getRealtimeIO } from "@/lib/realtime" | ||
|
|
||
| const queueName = "realtime-events" | ||
|
|
||
| const globalForQueue = globalThis as unknown as { | ||
| realtimeQueue?: Queue | ||
| realtimeWorker?: Worker | ||
| realtimeQueueConnection?: ReturnType<typeof createRedisConnection> | ||
| realtimeWorkerConnection?: ReturnType<typeof createRedisConnection> | ||
| } | ||
|
|
||
| function ensureConnections() { | ||
| if (!globalForQueue.realtimeQueueConnection) { | ||
| globalForQueue.realtimeQueueConnection = createRedisConnection() | ||
| } | ||
|
|
||
| if (!globalForQueue.realtimeWorkerConnection) { | ||
| globalForQueue.realtimeWorkerConnection = createRedisConnection() | ||
| } | ||
| } | ||
|
|
||
| export function getRealtimeQueue() { | ||
| ensureConnections() | ||
|
|
||
| if (!globalForQueue.realtimeQueue) { | ||
| globalForQueue.realtimeQueue = new Queue(queueName, { | ||
| connection: globalForQueue.realtimeQueueConnection, | ||
| }) | ||
| } | ||
|
|
||
| return globalForQueue.realtimeQueue | ||
| } | ||
|
|
||
| function ensureWorker() { | ||
| ensureConnections() | ||
|
|
||
| if (!globalForQueue.realtimeWorker) { | ||
| globalForQueue.realtimeWorker = new Worker( | ||
| queueName, | ||
| async job => { | ||
| const io = getRealtimeIO() | ||
|
|
||
| if (io) { | ||
| io.emit("realtime:event", { | ||
| event: job.name, | ||
| payload: job.data, | ||
| jobId: job.id, | ||
| timestamp: Date.now(), | ||
| }) | ||
|
|
||
| io.emit(job.name, job.data) | ||
| } | ||
| }, | ||
| { connection: globalForQueue.realtimeWorkerConnection }, | ||
| ) | ||
|
|
||
| globalForQueue.realtimeWorker.on("error", error => { | ||
| console.error("Realtime worker error", error) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| export async function enqueueRealtimeEvent(event: string, payload: unknown, options?: JobsOptions) { | ||
| const queue = getRealtimeQueue() | ||
| ensureWorker() | ||
|
|
||
| await queue.add(event, payload, { | ||
| removeOnComplete: { age: 60, count: 1000 }, | ||
| removeOnFail: { age: 60 * 60, count: 100 }, | ||
| ...options, | ||
| }) | ||
| } | ||
|
|
||
| export function describeRealtimeQueue() { | ||
| return { | ||
| name: queueName, | ||
| redis: getRedisUrl(), | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import type { Server as IOServer } from "socket.io" | ||
|
|
||
| const globalForRealtime = globalThis as unknown as { | ||
| realtimeIO?: IOServer | ||
| } | ||
|
|
||
| export function getRealtimeIO() { | ||
| return globalForRealtime.realtimeIO | ||
| } | ||
|
|
||
| export function setRealtimeIO(io: IOServer) { | ||
| globalForRealtime.realtimeIO = io | ||
| return io | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import IORedis from "ioredis" | ||
|
|
||
| const redisUrl = process.env.REDIS_URL || "redis://127.0.0.1:6379" | ||
|
|
||
| const baseOptions = { | ||
| maxRetriesPerRequest: null as number | null, | ||
| enableReadyCheck: true, | ||
| } | ||
|
|
||
| const globalForRedis = globalThis as unknown as { | ||
| redisConnection?: IORedis | ||
| } | ||
|
|
||
| export function createRedisConnection() { | ||
| return new IORedis(redisUrl, baseOptions) | ||
| } | ||
|
|
||
| export function getRedisConnection() { | ||
| if (!globalForRedis.redisConnection) { | ||
| globalForRedis.redisConnection = createRedisConnection() | ||
| } | ||
|
|
||
| return globalForRedis.redisConnection | ||
| } | ||
|
|
||
| export function getRedisUrl() { | ||
| return redisUrl | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| /// <reference types="next" /> | ||
| /// <reference types="next/image-types/global" /> | ||
| /// <reference types="next/navigation-types/compat/navigation" /> | ||
|
|
||
| // NOTE: This file should not be edited | ||
| // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import type { NextApiRequest } from "next" | ||
| import { Server as IOServer } from "socket.io" | ||
|
|
||
| import type { NextApiResponseServerIO } from "@/types/next" | ||
| import { getRealtimeIO, setRealtimeIO } from "@/lib/realtime" | ||
|
|
||
| export const config = { | ||
| api: { | ||
| bodyParser: false, | ||
| }, | ||
| } | ||
|
|
||
| export default function handler(req: NextApiRequest, res: NextApiResponseServerIO) { | ||
| const existingServer = res.socket.server as typeof res.socket.server & { io?: IOServer } | ||
|
|
||
| if (!existingServer.io) { | ||
| const io = new IOServer(res.socket.server, { | ||
| path: "/api/socket/io", | ||
| cors: { | ||
| origin: process.env.NEXT_PUBLIC_SITE_URL || "*", | ||
| }, | ||
| }) | ||
|
|
||
| setRealtimeIO(io) | ||
| existingServer.io = io | ||
|
|
||
| io.on("connection", socket => { | ||
| socket.emit("realtime:event", { | ||
| event: "socket:connected", | ||
| socketId: socket.id, | ||
| timestamp: Date.now(), | ||
| }) | ||
|
|
||
| socket.on("disconnect", reason => { | ||
| socket.broadcast.emit("realtime:event", { | ||
| event: "socket:disconnected", | ||
| socketId: socket.id, | ||
| reason, | ||
| timestamp: Date.now(), | ||
| }) | ||
| }) | ||
| }) | ||
| } else if (!getRealtimeIO()) { | ||
| setRealtimeIO(existingServer.io) | ||
| } | ||
|
|
||
| res.end() | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Each Prisma mutation
awaitsenqueueRealtimeEvent, and the Redis clients created inlib/redis.tssetmaxRetriesPerRequest: null(infinite retries). When Redis is unavailable or misconfigured,queue.addnever resolves nor rejects, so every database write waits forever before the middleware returns. This change effectively makes all writes dependent on Redis uptime even though the realtime queue is optional. Consider not awaiting the enqueue call or adding a bounded timeout/retry so mutations can complete even when Redis is offline.Useful? React with 👍 / 👎.