fix(/join) fixed /join not responding with roomIDs

chore(seed) improved room creation for seeding
This commit is contained in:
2023-07-27 22:24:39 -04:00
parent a51d587487
commit c5bfdf440c
7 changed files with 124 additions and 63 deletions

View File

@@ -1,53 +1,9 @@
import { PrismaClient } from '@prisma/client'
import { genId } from 'discreetly-interfaces';
import { generateClaimCodes } from 'discreetly-claimcodes';
import { createRoom } from '../src/data/db';
const prisma = new PrismaClient();
const idc = genId(0n, "First User").toString();
const idc2 = genId(0n, "Second User").toString();
const claimCodes = generateClaimCodes(10);
// console.log(claimCodes);
let codeArr: any[] = [];
claimCodes.forEach(code => {
codeArr.push({ claimcode: code.code })
})
const seedData = {
where: {
roomId: genId(0n, "First Room").toString()
},
update: {},
create: {
roomId: genId(0n, "First Room").toString(),
name: "First Room",
identities: [idc, idc2],
claimCodes: {
create: codeArr
}
}
function main() {
createRoom('1 Second Room', 1000, 1, 10);
createRoom('10 Second Room', 10000, 2, 10);
createRoom('100 Second Room', 100000, 10, 10);
}
async function main() {
await prisma.rooms.upsert(seedData)
await prisma.rooms.upsert({
where: {
roomId: genId(0n, "Room Two").toString()
},
update: {},
create: {
roomId: genId(0n, "Room Two").toString(),
name: "Room Two",
identities: [idc],
claimCodes: {
create: codeArr
}
}
})
console.log(seedData);
}
main();

View File

@@ -15,7 +15,7 @@ console.log('SERVERID:', serverID);
export const serverConfig: ServerI = {
id: serverID,
name: 'Localhost',
serverInfoEndpoint: '3001',
messageHandlerSocket: '3002',
serverInfoEndpoint: 'localhost:3001',
messageHandlerSocket: 'localhost:3002',
version: '0.0.1'
};

View File

@@ -1,5 +1,12 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import { PrismaClient } from '@prisma/client';
import { RoomI } from 'discreetly-interfaces';
import { RoomI, genId } from 'discreetly-interfaces';
import { serverConfig } from '../config/serverConfig';
import { randn_bm } from '../utils';
import { generateClaimCodes } from 'discreetly-claimcodes';
import type { ClaimCodeT } from 'discreetly-claimcodes';
const prisma = new PrismaClient();
@@ -17,3 +24,61 @@ export function getRoomByID(id: string): RoomI | null {
.catch((err) => console.error(err));
return null;
}
/**
* Creates a new room with the given name and optional parameters.
* @param {string} name - The name of the room.
* @param {number} [rateLimit=1000] - The length of an epoch in milliseconds
* @param {number} [userMessageLimit=1] - The message limit per user per epoch
* @param {number} [numClaimCodes=0] - The number of claim codes to generate for the room.
* @param {number} [approxNumMockUsers=20] - The approximate number of mock users to generate for the room.
*/
export function createRoom(
name: string,
rateLimit: number = 1000,
userMessageLimit: number = 1,
numClaimCodes: number = 0,
approxNumMockUsers: number = 20
) {
function genMockUsers(numMockUsers: number): string[] {
// Generates random number of mock users between 0.5 x numMockusers and 2 x numMockUsers
const newNumMockUsers = randn_bm(numMockUsers / 2, numMockUsers * 2);
const mockUsers: string[] = [];
for (let i = 0; i < newNumMockUsers; i++) {
mockUsers.push(genId(serverConfig.id, 'Mock User ' + i).toString());
}
return mockUsers;
}
function genClaimCodeArray(numClaimCodes: number): { claimcode: string }[] {
const claimCodes = generateClaimCodes(numClaimCodes);
const codeArr: { claimcode: string }[] = claimCodes.map((code: ClaimCodeT) => ({
claimcode: code.code
}));
return codeArr;
}
const claimCodes: { claimcode: string }[] = genClaimCodeArray(numClaimCodes);
const mockUsers: string[] = genMockUsers(approxNumMockUsers);
const roomData = {
where: {
roomId: genId(serverConfig.id, name).toString()
},
update: {},
create: {
roomId: genId(serverConfig.id, name).toString(),
name: name,
rateLimit: rateLimit,
userMessageLimit: userMessageLimit,
identities: mockUsers,
claimCodes: {
create: claimCodes
}
}
};
prisma.rooms
.upsert(roomData)
.then(() => {})
.catch((err) => console.error(err));
}

View File

@@ -16,15 +16,17 @@ export function initEndpoints(app: Express) {
res.json(serverConfig);
});
app.get('/logclaimcodes', () => {
app.get('/logclaimcodes', (req, res) => {
pp('Express: fetching claim codes');
prisma.claimCodes
.findMany()
.then((claimCodes) => {
console.log(claimCodes);
res.status(401).send('Unauthorized');
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: 'Internal Server Error' });
});
});
@@ -56,7 +58,7 @@ export function initEndpoints(app: Express) {
code: string;
idc: string;
}
console.log(req.body);
const { code, idc } = req.body as JoinRequestBody;
pp(`Express[/join]: claiming code: ${code}`);
@@ -68,6 +70,7 @@ export function initEndpoints(app: Express) {
}
})
.then((codeStatus: { claimed: boolean; roomIds: string[] }) => {
console.log(codeStatus);
if (codeStatus.claimed === false) {
prisma.claimCodes
.update({
@@ -75,7 +78,7 @@ export function initEndpoints(app: Express) {
claimcode: code
},
data: {
claimed: true
claimed: false //TODO! This should be true and is only false for testing
}
})
.then((claimCode: { roomIds: string[] }) => {
@@ -93,8 +96,16 @@ export function initEndpoints(app: Express) {
}
}
})
.then((updatedRooms) => {
res.status(200).json(updatedRooms);
.then(async () => {
// return the room name of all the rooms that were updated
const updatedRooms = await prisma.rooms.findMany({
where: {
id: {
in: roomIds
}
}
});
res.status(200).json(updatedRooms.map((room) => room.roomId));
})
.catch((err) => {
console.error(err);

View File

@@ -27,12 +27,14 @@ const io = new SocketIOServer(socket_server, {
});
function initAppListeners() {
app.listen(serverConfig.serverInfoEndpoint, () => {
pp(`Express Http Server is running at port ${serverConfig.serverInfoEndpoint}`);
const expressServerPort = serverConfig.serverInfoEndpoint.split(':')[1];
const socketServerPort = serverConfig.messageHandlerSocket.split(':')[1];
app.listen(expressServerPort, () => {
pp(`Express Http Server is running at port ${expressServerPort}`);
});
socket_server.listen(serverConfig.messageHandlerSocket, () => {
pp(`SocketIO Server is running at port ${serverConfig.messageHandlerSocket}`);
socket_server.listen(socketServerPort, () => {
pp(`SocketIO Server is running at port ${socketServerPort}`);
});
}

View File

@@ -9,7 +9,11 @@ export function shim() {
};
}
// Pretty Print to console
/**
* Logs the provided string to the console with the specified log level.
* @param {any} str - The string to log.
* @param {string} [level='log'] - The log level to use. Can be one of 'log', 'debug', 'info', 'warn', 'warning', 'error', 'err', 'table', or 'assert'.
*/
export const pp = (str: any, level = 'log') => {
str = JSON.stringify(str, null, 2);
switch (level) {
@@ -37,3 +41,22 @@ export const pp = (str: any, level = 'log') => {
console.log(str);
}
};
// from: https://stackoverflow.com/a/49434653/957648
export function randn_bm(min: number, max: number, skew: number = 1) {
let u = 0,
v = 0;
while (u === 0) u = Math.random(); //Converting [0,1) to (0,1)
while (v === 0) v = Math.random();
let num = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
num = num / 10.0 + 0.5; // Translate to 0 -> 1
if (num > 1 || num < 0)
num = randn_bm(min, max, skew); // resample between 0 and 1 if out of range
else {
num = Math.pow(num, skew); // Skew
num *= max - min; // Stretch to fill range
num += min; // offset to min
}
return num;
}

View File

@@ -6,7 +6,7 @@
"target": "ES2022",
"module": "ES2022",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
"allowSyntheticDefaultImports": true,
},
"ts-node": {
"esm": true,
@@ -14,5 +14,9 @@
},
"files": [
"./src/server.ts"
],
"include": [
"src/**/*",
"src/types/index.ts"
]
}