|
| 1 | +import { $replica } from "~/db.server"; |
| 2 | +import { requireUserId } from "~/services/session.server"; |
| 3 | +import { EnvironmentParamSchema } from "~/utils/pathBuilder"; |
| 4 | +import { env } from "~/env.server"; |
| 5 | +import { DevPresenceStream } from "~/presenters/v3/DevPresenceStream.server"; |
| 6 | +import { logger } from "~/services/logger.server"; |
| 7 | +import { createSSELoader, type SendFunction } from "~/utils/sse"; |
| 8 | +import Redis from "ioredis"; |
| 9 | + |
| 10 | +export const loader = createSSELoader({ |
| 11 | + timeout: env.DEV_PRESENCE_TTL_MS, |
| 12 | + interval: env.DEV_PRESENCE_POLL_INTERVAL_MS, |
| 13 | + debug: true, |
| 14 | + handler: async ({ id, controller, debug, request, params }) => { |
| 15 | + const userId = await requireUserId(request); |
| 16 | + const { organizationSlug, projectParam, envParam } = EnvironmentParamSchema.parse(params); |
| 17 | + |
| 18 | + const environment = await $replica.runtimeEnvironment.findFirst({ |
| 19 | + where: { |
| 20 | + slug: envParam, |
| 21 | + type: "DEVELOPMENT", |
| 22 | + project: { |
| 23 | + slug: projectParam, |
| 24 | + }, |
| 25 | + organization: { |
| 26 | + slug: organizationSlug, |
| 27 | + members: { |
| 28 | + some: { |
| 29 | + userId, |
| 30 | + }, |
| 31 | + }, |
| 32 | + }, |
| 33 | + }, |
| 34 | + }); |
| 35 | + |
| 36 | + if (!environment) { |
| 37 | + throw new Response("Not Found", { status: 404 }); |
| 38 | + } |
| 39 | + |
| 40 | + const presenceKey = DevPresenceStream.getPresenceKey(environment.id); |
| 41 | + const presenceChannel = DevPresenceStream.getPresenceChannel(environment.id); |
| 42 | + |
| 43 | + // Create two Redis clients - one for subscribing and one for regular commands |
| 44 | + const redisConfig = { |
| 45 | + port: env.RUN_ENGINE_DEV_PRESENCE_REDIS_PORT ?? undefined, |
| 46 | + host: env.RUN_ENGINE_DEV_PRESENCE_REDIS_HOST ?? undefined, |
| 47 | + username: env.RUN_ENGINE_DEV_PRESENCE_REDIS_USERNAME ?? undefined, |
| 48 | + password: env.RUN_ENGINE_DEV_PRESENCE_REDIS_PASSWORD ?? undefined, |
| 49 | + enableAutoPipelining: true, |
| 50 | + ...(env.RUN_ENGINE_DEV_PRESENCE_REDIS_TLS_DISABLED === "true" ? {} : { tls: {} }), |
| 51 | + }; |
| 52 | + |
| 53 | + // Subscriber client for pubsub |
| 54 | + const subRedis = new Redis(redisConfig); |
| 55 | + |
| 56 | + // Command client for regular Redis commands |
| 57 | + const cmdRedis = new Redis(redisConfig); |
| 58 | + |
| 59 | + const checkAndSendPresence = async (send: SendFunction) => { |
| 60 | + try { |
| 61 | + // Use the command client for the GET operation |
| 62 | + const currentPresenceValue = await cmdRedis.get(presenceKey); |
| 63 | + const isConnected = !!currentPresenceValue; |
| 64 | + |
| 65 | + // Format lastSeen as ISO string if it exists |
| 66 | + let lastSeen = null; |
| 67 | + if (currentPresenceValue) { |
| 68 | + // Check if it's a numeric timestamp |
| 69 | + if (!isNaN(Number(currentPresenceValue))) { |
| 70 | + // Convert numeric timestamp to ISO string |
| 71 | + lastSeen = new Date(parseInt(currentPresenceValue, 10)).toISOString(); |
| 72 | + } else { |
| 73 | + // It's already a string format, make sure it's ISO |
| 74 | + try { |
| 75 | + lastSeen = new Date(currentPresenceValue).toISOString(); |
| 76 | + } catch (e) { |
| 77 | + // If parsing fails, use current time as fallback |
| 78 | + lastSeen = new Date().toISOString(); |
| 79 | + logger.warn("Failed to parse lastSeen value, using current time", { |
| 80 | + originalValue: currentPresenceValue, |
| 81 | + }); |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + send({ |
| 87 | + event: "presence", |
| 88 | + data: JSON.stringify({ |
| 89 | + type: isConnected ? "connected" : "disconnected", |
| 90 | + environmentId: environment.id, |
| 91 | + timestamp: new Date().toISOString(), // Also standardize this to ISO |
| 92 | + lastSeen: lastSeen, |
| 93 | + }), |
| 94 | + }); |
| 95 | + |
| 96 | + return isConnected; |
| 97 | + } catch (error) { |
| 98 | + // Handle the case where the controller is closed |
| 99 | + logger.debug("Failed to send presence data, stream might be closed", { error }); |
| 100 | + return false; |
| 101 | + } |
| 102 | + }; |
| 103 | + |
| 104 | + return { |
| 105 | + beforeStream: async () => { |
| 106 | + logger.debug("Start dev presence listening SSE session", { |
| 107 | + environmentId: environment.id, |
| 108 | + presenceChannel, |
| 109 | + }); |
| 110 | + }, |
| 111 | + initStream: async ({ send }) => { |
| 112 | + await checkAndSendPresence(send); |
| 113 | + |
| 114 | + //start subscribing with the subscriber client |
| 115 | + await subRedis.subscribe(presenceChannel); |
| 116 | + |
| 117 | + subRedis.on("message", async (channel, message) => { |
| 118 | + if (channel === presenceChannel) { |
| 119 | + try { |
| 120 | + await checkAndSendPresence(send); |
| 121 | + } catch (error) { |
| 122 | + logger.error("Failed to parse presence message", { error, message }); |
| 123 | + } |
| 124 | + } |
| 125 | + }); |
| 126 | + |
| 127 | + send({ event: "time", data: new Date().toISOString() }); |
| 128 | + }, |
| 129 | + iterator: async ({ send, date }) => { |
| 130 | + await checkAndSendPresence(send); |
| 131 | + }, |
| 132 | + cleanup: async ({ send }) => { |
| 133 | + await checkAndSendPresence(send); |
| 134 | + |
| 135 | + await subRedis.unsubscribe(presenceChannel); |
| 136 | + await subRedis.quit(); |
| 137 | + await cmdRedis.quit(); |
| 138 | + }, |
| 139 | + }; |
| 140 | + }, |
| 141 | +}); |
0 commit comments