Skip to content

Commit

Permalink
remove room service
Browse files Browse the repository at this point in the history
  • Loading branch information
czerwiukk committed Nov 4, 2024
1 parent 336e700 commit 70c3802
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 79 deletions.
28 changes: 14 additions & 14 deletions examples/room-manager/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
declare module 'fastify' {
interface FastifyInstance {
config: {
PORT: number;
WEBHOOK_URL?: string;
PEERLESS_PURGE_TIMEOUT?: number;
ENABLE_SIMULCAST: boolean;
MAX_PEERS?: number;
FISHJAM_URL: string;
FISHJAM_SERVER_TOKEN: string;
};
}
}

export const configSchema = {
type: 'object',
required: ['PORT', 'ENABLE_SIMULCAST', 'FISHJAM_URL', 'FISHJAM_SERVER_TOKEN'],
Expand Down Expand Up @@ -31,17 +45,3 @@ export const configSchema = {
},
},
};

declare module 'fastify' {
interface FastifyInstance {
config: {
PORT: number;
WEBHOOK_URL?: string;
PEERLESS_PURGE_TIMEOUT?: number;
ENABLE_SIMULCAST: boolean;
MAX_PEERS?: number;
FISHJAM_URL: string;
FISHJAM_SERVER_TOKEN: string;
};
}
}
9 changes: 5 additions & 4 deletions examples/room-manager/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import Fastify, { FastifyRequest } from 'fastify';
import cors from '@fastify/cors';
import { configSchema } from './config';
import fastifyEnv from '@fastify/env';
import { roomsEndpoints } from './routes/rooms';
import fastifySwagger from '@fastify/swagger';
import { ServerMessage } from '@fishjam-cloud/js-server-sdk/proto';
import healthcheck from 'fastify-healthcheck';
import fastifySwagger from '@fastify/swagger';
import { configSchema } from './config';

import { rooms } from './routes/rooms';
import openapi from './openapi';

const envToLogger = {
Expand Down Expand Up @@ -40,7 +41,7 @@ async function setupServer() {

await fastify.register(fastifySwagger, { openapi });
await fastify.register(healthcheck);
await fastify.register(roomsEndpoints, { prefix: '/api/rooms' });
await fastify.register(rooms, { prefix: '/api/rooms' });

fastify.listen({ port: fastify.config.PORT, host: '0.0.0.0' }, (err) => {
if (err) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
import fp from 'fastify-plugin';
import { type FastifyInstance } from 'fastify';
import { FishjamClient, Room, RoomNotFoundException } from '@fishjam-cloud/js-server-sdk';
import { ServerMessage } from '@fishjam-cloud/js-server-sdk/proto';
import { fastify } from './index';
import type { PeerAccessData } from './schema';
import { RoomManagerError } from './errors';

export class RoomService {
private readonly peerNameToAccessMap = new Map<string, PeerAccessData>();
private readonly roomNameToRoomIdMap = new Map<string, string>();
private readonly fishjamClient: FishjamClient;

constructor(fishjamUrl: string, managementToken: string) {
this.fishjamClient = new FishjamClient({
fishjamUrl,
managementToken,
});
import { RoomManagerError } from '../errors';
import { PeerAccessData } from '../schema';

declare module 'fastify' {
interface FastifyInstance {
fishjam: {
getPeerAccess: (roomName: string, username: string) => Promise<PeerAccessData>;
handleFishjamMessage: (notification: ServerMessage) => Promise<void>;
};
}
}

export const fishjamPlugin = fp(async (fastify: FastifyInstance): Promise<void> => {
if (fastify.hasDecorator('fishjam')) {
throw new Error('The `fishjamPlugin` plugin has already been registered.');
}

async getPeerAccess(roomName: string, username: string): Promise<PeerAccessData> {
const room = await this.findOrCreateRoomInFishjam(roomName);
const peerAccess = this.peerNameToAccessMap.get(username);
const fishjamClient = new FishjamClient({
fishjamUrl: fastify.config.FISHJAM_URL,
managementToken: fastify.config.FISHJAM_SERVER_TOKEN,
});

const peerNameToAccessMap = new Map<string, PeerAccessData>();
const roomNameToRoomIdMap = new Map<string, string>();

async function getPeerAccess(roomName: string, username: string): Promise<PeerAccessData> {
const room = await findOrCreateRoomInFishjam(roomName);
const peerAccess = peerNameToAccessMap.get(username);

const peer = room.peers.find((peer) => peer.id === peerAccess?.peer.id);

Expand All @@ -31,7 +42,7 @@ export class RoomService {

if (!peer) {
fastify.log.info({ name: 'Creating peer' });
return await this.createPeer(roomName, username);
return await createPeer(roomName, username);
}

if (!peerAccess?.peerToken) throw new RoomManagerError('Missing peer token in room');
Expand All @@ -41,7 +52,7 @@ export class RoomService {
return peerAccess;
}

async handleJellyfishMessage(notification: ServerMessage): Promise<void> {
async function handleFishjamMessage(notification: ServerMessage): Promise<void> {
Object.entries(notification)
.filter(([_, value]) => value)
.forEach(([name, value]) => {
Expand All @@ -53,7 +64,7 @@ export class RoomService {
if (peerToBeRemoved) {
const { roomId, peerId } = peerToBeRemoved;

const userAccess = [...this.peerNameToAccessMap.values()].find(
const userAccess = [...peerNameToAccessMap.values()].find(
({ room, peer }) => room.id === roomId && peer.id === peerId
);

Expand All @@ -62,21 +73,21 @@ export class RoomService {
return;
}

this.peerNameToAccessMap.delete(userAccess.peer.name);
peerNameToAccessMap.delete(userAccess.peer.name);

fastify.log.info({ name: 'Peer deleted from cache', roomId, peerId: peerId });
}

const roomToBeRemovedId = (notification.roomDeleted ?? notification.roomCrashed)?.roomId;

if (roomToBeRemovedId) {
const roomName = this.roomNameToRoomIdMap.get(roomToBeRemovedId);
if (roomName) this.roomNameToRoomIdMap.delete(roomName);
const roomName = roomNameToRoomIdMap.get(roomToBeRemovedId);
if (roomName) roomNameToRoomIdMap.delete(roomName);

const usersToRemove = [...this.peerNameToAccessMap.values()].filter((user) => user.room.id === roomToBeRemovedId);
const usersToRemove = [...peerNameToAccessMap.values()].filter((user) => user.room.id === roomToBeRemovedId);

usersToRemove.forEach(({ peer }) => {
this.peerNameToAccessMap.delete(peer.name);
peerNameToAccessMap.delete(peer.name);
});

fastify.log.info({
Expand All @@ -86,12 +97,12 @@ export class RoomService {
}
}

private async createPeer(roomName: string, peerName: string): Promise<PeerAccessData> {
const roomId = this.roomNameToRoomIdMap.get(roomName);
async function createPeer(roomName: string, peerName: string): Promise<PeerAccessData> {
const roomId = roomNameToRoomIdMap.get(roomName);

if (!roomId) throw new RoomManagerError('Room not found');

const { peer, peerToken } = await this.fishjamClient.createPeer(roomId, {
const { peer, peerToken } = await fishjamClient.createPeer(roomId, {
enableSimulcast: fastify.config.ENABLE_SIMULCAST,
metadata: { username: peerName },
});
Expand All @@ -102,20 +113,20 @@ export class RoomService {
peerToken,
};

this.peerNameToAccessMap.set(peerName, peerAccess);
peerNameToAccessMap.set(peerName, peerAccess);

fastify.log.info('Created peer', { peerName, ...peerAccess });

return peerAccess;
}

private async findOrCreateRoomInFishjam(roomName: string): Promise<Room> {
const roomId = this.roomNameToRoomIdMap.get(roomName);
async function findOrCreateRoomInFishjam(roomName: string): Promise<Room> {
const roomId = roomNameToRoomIdMap.get(roomName);

if (roomId) {
try {
const room = await this.fishjamClient.getRoom(roomId);
fastify.log.info({ name: 'Room already exist in the Fishjam', room });
const room = await fishjamClient.getRoom(roomId);
fastify.log.info({ name: 'Room already exist in Fishjam', room });

return room;
} catch (err) {
Expand All @@ -126,21 +137,23 @@ export class RoomService {
}

fastify.log.info({
name: 'Creating room in the Fishjam',
name: 'Creating room in Fishjam',
roomId,
roomName,
});

const newRoom = await this.fishjamClient.createRoom({
const newRoom = await fishjamClient.createRoom({
maxPeers: fastify.config.MAX_PEERS,
webhookUrl: fastify.config.WEBHOOK_URL,
peerlessPurgeTimeout: fastify.config.PEERLESS_PURGE_TIMEOUT,
});

this.roomNameToRoomIdMap.set(roomName, newRoom.id);
roomNameToRoomIdMap.set(roomName, newRoom.id);

fastify.log.info({ name: 'Room created', newRoom });

return newRoom;
}
}

fastify.decorate('fishjam', { getPeerAccess, handleFishjamMessage });
});
19 changes: 0 additions & 19 deletions examples/room-manager/src/plugins/roomService.ts

This file was deleted.

10 changes: 5 additions & 5 deletions examples/room-manager/src/routes/rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { ServerMessage } from '@fishjam-cloud/js-server-sdk/proto';
import { GetPeerAccessQueryParams, startRecordingSchema, queryStringPeerEndpointSchema } from '../schema';
import { parseError } from '../errors';
import { roomServicePlugin } from '../plugins/roomService';
import { fishjamPlugin } from '../plugins/fishjam';
import { httpToWebsocket, removeTrailingSlash } from '../utils';

export async function roomsEndpoints(fastify: FastifyInstance) {
await fastify.register(roomServicePlugin);
export async function rooms(fastify: FastifyInstance) {
await fastify.register(fishjamPlugin);

const getRoomAccessHandler = async (roomName: string, peerName: string, res: FastifyReply) => {
try {
const accessData = await fastify.roomService.getPeerAccess(roomName, peerName);
const accessData = await fastify.fishjam.getPeerAccess(roomName, peerName);
const url = httpToWebsocket(fastify.config.FISHJAM_URL);

// When creating a URL object from a URL without a path (e.g., `http://localhost:5002`),
Expand All @@ -25,7 +25,7 @@ export async function roomsEndpoints(fastify: FastifyInstance) {
};

const webhookHandler = async (req: FastifyRequest<{ Body: ServerMessage }>, res: FastifyReply) => {
await fastify.roomService.handleJellyfishMessage(req.body);
await fastify.fishjam.handleFishjamMessage(req.body);
return res.status(200).send();
};

Expand Down

0 comments on commit 70c3802

Please sign in to comment.