Skip to content

Commit

Permalink
feat: use redis for sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
lewxdev committed Aug 18, 2024
1 parent 78134ed commit 4bf885f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
6 changes: 3 additions & 3 deletions app/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import next from "next";
import { Server } from "socket.io";
import type { SocketServer } from "@/types";
import { Field } from "@/utils/game";
import * as redis from "@/utils/redis";

const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
const sessions = new Set<string>();

async function main() {
const app = next({ dev, hostname, port });
Expand All @@ -25,7 +25,7 @@ async function main() {
io.use(async (socket, next) => {
const { sessionID } = socket.handshake.auth;
if (sessionID) {
if (!sessions.has(sessionID)) {
if (await redis.isDeadSession(sessionID)) {
return next(new Error("invalid session"));
}
socket.data.sessionID = sessionID;
Expand All @@ -37,7 +37,7 @@ async function main() {
});

io.on("connection", (socket) => {
sessions.add(socket.data.sessionID);
redis.startSession(socket.data.sessionID);

socket.emit("session", {
sessionID: socket.data.sessionID,
Expand Down
32 changes: 23 additions & 9 deletions app/utils/redis.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
import { Redis } from "ioredis";
import _ from "lodash";

const key = "field:data";
const fieldKey = "field:data";
const sessionKey = "user:sessions";

function getClient() {
return new Redis(process.env["REDIS_URL"]!, { family: 6 });
}
const redis = new Redis(process.env["REDIS_URL"]!, { family: 6 });

export async function decodeData() {
const redis = getClient();
const value = await redis.get(key);
const value = await redis.get(fieldKey);
if (typeof value !== "string" || !value) {
throw new Error(`unexpected data on key: ${key}`);
throw new Error(`unexpected data on key: ${fieldKey}`);
}
return Array.from(value, (char) => char.charCodeAt(0));
}

export async function encodeData(value: number[]) {
const redis = getClient();
const binaryString = Buffer.from(value).toString("binary");
await redis.set(key, binaryString);
await redis.set(fieldKey, binaryString);
return value;
}

export async function startSession(sessionId: string) {
return redis.sadd(sessionKey, sessionId);
}

export async function killSession(sessionId: string) {
return redis.srem(sessionKey, sessionId);
}

export async function isDeadSession(sessionId: string) {
const result = await redis.sismember(sessionKey, sessionId);
return !!result;
}

export async function resetSessions() {
return redis.del(sessionKey);
}

0 comments on commit 4bf885f

Please sign in to comment.