openvidu/meet-ce/backend/tests/integration/api/participants/participant-name.service.test.ts
Carlos Santos 3d4f04feb1 Migrate to pnpm
chore: migrate project to pnpm and update workspace configuration

- Added pnpm workspace configuration in pnpm-workspace.yaml to manage packages.
- Updated prepare.sh script to use pnpm for installing and building packages.
- Modified testapp/package.json scripts to use pnpm instead of npm.
- Enhanced tsconfig.client.json and tsconfig.json with additional options and exclusions.
- Updated typings README.md to reflect the use of pnpm for installation and building.

streamline build process in prepare script and update dependency installation

Refactor code structure for improved readability and maintainability

refactor: optimize Dockerfile for better layer caching and dependency installation

refactor: migrate typings from '@lib/typings/ce' to '@openvidu-meet/typings'

- Updated imports across multiple components and services to use the new '@openvidu-meet/typings' package.
- Removed legacy typings references and adjusted paths in the frontend and webcomponent projects.
- Cleaned up the typings package structure and added build scripts for TypeScript.
- Removed the sync-types.sh script as it is no longer needed with the new structure.
- Updated README and package.json files to reflect the new package name and structure.
feat: add nodemon configuration for API documentation updates and enhance development scripts

feat: implement type checking in watch mode and update development scripts

feat: enhance development scripts with wait-for-typings and watch-typings utilities

fix: remove obsolete sync:backend script and enhance dev script with preserveWatchOutput option

feat: enhance development scripts with typings guard and improve watch behavior

Refactors build and dev scripts

Simplifies and consolidates build and development-related scripts for improved maintainability.

- Updates the build process to be more streamlined.
- Improves the development workflow by consolidating common tasks.
- Removes redundant scripts.

Replaces prepare script with meet script

Replaces the old `prepare.sh` script with a new `meet.sh` script to provide a more user-friendly and comprehensive interface for building and managing the project.

- Integrates command-line arguments for different build targets.
- Includes documentation generation for web components and REST APIs.
- Provides improved error handling and user feedback.
- Simplifies the build process with `pnpm`.

chore: update typescript version to 5.9.2 across multiple package.json files
refactor: replace constructor injection with inject function for AppDataService

feat: add commands to build webcomponent and run unit tests

meet.sh: add end-to-end testing support for webcomponent with optional Playwright browser installation

chore: update pnpm version to 10 and streamline test commands in workflows

meet.sh: rename build_webcomponent_only to build_webcomponent and streamline dependency installation

gitignore: add test-results directory to ignore list

meet.sh: rename build_webcomponent_only to build_webcomponent for consistency

Updated pnpm-lock.yml

refactor: streamline build scripts and enhance service start options in meet.sh

ci: update OpenVidu Meet actions to use meet-pnpm-migration version

refactor: update import paths for WebComponentCommand and WebComponentEvent to use shared typings

fix: add moduleNameMapper for typings path in jest configuration

fix: correct action version syntax for OpenVidu Meet setup in workflow

fix: update typings imports to use shared @openvidu-meet/typings package

fix: add skip-install and skip-typings options to meet.sh and update workflows

meet.sh: add development mode command and update start services options

fix: format code in meeting.component.ts and remove unused export in public-api.ts

added openvidu-components-angular to the local workspace and watch for changes in dev mode

fix: update Node.js action to v5 and streamline build steps in wc-unit-test.yaml

fix: remove pnpm install from build scripts in package.json

fix: update backend unit test workflow and add test unit command in meet.sh

fix: update unit test command in package.json to use pnpm exec

Updates import path for LiveKit permissions

Updates the import path for LiveKit permissions to align with the new typings package location, ensuring the test suite remains functional after the project's dependencies are migrated.

fix: remove redundant dependency installation and build steps in start_services function

fix: update Node.js setup action version and adjust OpenVidu actions for pnpm migration

fix: update tsconfig.json to exclude specific type declaration paths

fix: remove deprecated dependencies and update openapi-generate-html version

fix: update build messages and streamline start commands for production and CI modes

fix: update OpenVidu Meet and Testapp actions to use main branch and streamline pre-startup commands

Refactors type import for auth mode

Updates the import path for the authentication transport mode type.

This change ensures consistency across the application by using a centralized type definition.

Refactors backend integration tests

Streamlines the backend integration test workflow.

Consolidates test jobs for better organization and efficiency.
Leverages matrix testing for recordings API with different storage providers.
Improves AWS runner management for recording tests.
Adds artifact cleanup to prevent storage bloat.

Sets up Node.js and pnpm

Adds Node.js and pnpm setup steps to the integration test workflow.

This enables the use of pnpm for managing dependencies during integration tests.

Refactors test commands to use pnpm exec

Updates the test commands in package.json to use `pnpm exec`
for running Jest.

This ensures that the Jest CLI is executed within the pnpm
managed environment, resolving potential path and dependency
issues.

Refactors imports to use the new typings package

Updates imports to use the new `@openvidu-meet/typings` package.
Removes now-unnecessary module name mappings.

This change is part of the pnpm migration, ensuring correct
resolution of shared types.

Enhances backend integration tests and updates Node.js setup

Simplifies integration tests execution

Updates integration test scripts to streamline execution.

- Uses a single, parameterized script to run all backend integration tests.
- Removes redundant prefixes from test script names.

Refactors jest configuration to include moduleNameMapper for improved module resolution

Updates Jest integration test commands to use experimental VM modules and adjusts TypeScript root directory settings for better output structure

Ensures OpenVidu Meet logs are uploaded

Guarantees OpenVidu Meet logs are uploaded as artifacts, regardless of test outcome.

Moves log upload to ensure consistent capture, and does so for all test scenarios.

Commented backend integration tests

Fix build script to specify TypeScript configuration file

Refactor integration test command to use pnpm bin for jest execution

Update integration test commands to use relative paths for Jest execution

Revert "Commented backend integration tests"

This reverts commit 1da8cddb55e29036c2a816244f4bc8b665ede581.

Change log upload condition to trigger on failure for OpenVidu Meet logs

Add caching step for OpenVidu local deployment images in backend integration tests

Revert "Add caching step for OpenVidu local deployment images in backend integration tests"

This reverts commit bf4692d168c671100a88c09853a460ec5417979d.

Enhance AWS runner setup with storage provider matrix and update job names for clarity

Refactor AWS runner setup to separate jobs for S3, ABS, and GCS, enhancing clarity and maintainability

Update README.md to enhance structure and clarity, including detailed sections on prerequisites, getting started, development, and documentation.

Refactor Dockerfile and entrypoint script, remove deprecated image creation scripts, and enhance meet.sh with Docker build functionality and base href support

Update README.md to reflect changes in Docker image build commands using meet.sh

Update package.json to correct versioning and remove redundant entries

Added browser sync for live reloading

chore: update @typescript-eslint packages to version 8.46.1 in frontend and pnpm-lock.yaml

fix: correct argument skipping logic and ensure typings are built in install_dependencies function

Adapt project structure

backend: add TypeScript type annotations for Router instances in route files

fix: update path for nodemon configuration in dev:rest-api-docs script

fix: update paths in webcomponent documentation generation scripts

fix: update Dockerfile and entrypoint script for correct directory structure and improve error handling

fix: update .dockerignore and Dockerfile for improved directory handling and permissions; add backend type checker script

Added all tests files

Updates OpenVidu Meet action refs to main

Updates the OpenVidu Meet GitHub Action references
in the CI workflows to point to the `main` branch.

This ensures that the workflows use the latest version
of the action.
2025-10-15 17:42:04 +02:00

281 lines
10 KiB
TypeScript

import { afterEach, beforeAll, describe, expect, it } from '@jest/globals';
import ms from 'ms';
import { container, registerDependencies } from '../../../../src/config/index.js';
import { ParticipantNameService } from '../../../../src/services/participant-name.service.js';
import { RedisService } from '../../../../src/services/redis.service.js';
describe('ParticipantNameService', () => {
let participantNameService: ParticipantNameService;
let redisService: RedisService;
const testRoomId = 'test-room-unique-names';
beforeAll(async () => {
registerDependencies();
participantNameService = container.get(ParticipantNameService);
redisService = container.get(RedisService);
await cleanupTestData();
});
afterEach(async () => {
// Clean up test data after each test
await cleanupTestData();
});
async function cleanupTestData() {
try {
const pattern = `ov_meet:room_participants:${testRoomId}:*`;
const keys = await redisService.getKeys(pattern);
if (keys.length > 0) {
await redisService.delete(keys);
}
const counterPattern = `ov_meet:participant_counter:${testRoomId}:*`;
const counterKeys = await redisService.getKeys(counterPattern);
if (counterKeys.length > 0) {
await redisService.delete(counterKeys);
}
} catch (error) {
// Ignore cleanup errors
}
}
describe('Reserve unique participant name', () => {
it('should reserve the original name when available', async () => {
const requestedName = 'Participant';
const reservedName = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(reservedName).toBe(requestedName);
// Verify the name is actually reserved
const isReserved = await participantNameService.isNameReserved(testRoomId, requestedName);
expect(isReserved).toBe(true);
});
it('should treat names as case-insensitive if required', async () => {
await participantNameService.reserveUniqueName(testRoomId, 'Participant');
const reserved2 = await participantNameService.reserveUniqueName(testRoomId, 'participant');
expect(reserved2).toBe('participant_1');
});
it('should generate alternative names when original is taken', async () => {
const requestedName = 'Participant';
// Reserve the original name
const firstReservation = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(firstReservation).toBe(requestedName);
// Try to reserve the same name again - should get alternative
const secondReservation = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(secondReservation).toBe(`${requestedName}_1`);
// Try again - should get next alternative
const thirdReservation = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(thirdReservation).toBe(`${requestedName}_2`);
});
it('should handle concurrent reservations properly', async () => {
const requestedName = 'Participant';
const concurrentRequests = 5;
// Simulate concurrent requests for the same name
const reservationPromises = Array.from({ length: concurrentRequests }, () =>
participantNameService.reserveUniqueName(testRoomId, requestedName)
);
const reservedNames = await Promise.all(reservationPromises);
// All names should be unique
const uniqueNames = new Set(reservedNames);
expect(uniqueNames.size).toBe(concurrentRequests);
// First name should be the original
expect(reservedNames).toContain(requestedName);
// Others should be alternatives
for (let i = 1; i < concurrentRequests; i++) {
expect(reservedNames).toContain(`${requestedName}_${i}`);
}
});
it('should reuse numbers when participants disconnect', async () => {
const requestedName = 'Participant';
// Reserve multiple names
const name1 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
const name2 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
const name3 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(name1).toBe('Participant');
expect(name2).toBe('Participant_1');
expect(name3).toBe('Participant_2');
// Release the middle one
await participantNameService.releaseName(testRoomId, name2);
// Next reservation should reuse the released number
const name4 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(name4).toBe('Participant_1'); // Should reuse the released number
});
it('should maintain optimal numbering after multiple releases', async () => {
const requestedName = 'Optimized';
// Create several names
const names: string[] = [];
for (let i = 0; i < 5; i++) {
names.push(await participantNameService.reserveUniqueName(testRoomId, requestedName));
}
expect(names).toEqual(['Optimized', 'Optimized_1', 'Optimized_2', 'Optimized_3', 'Optimized_4']);
// Release some names (simulate participants leaving)
await participantNameService.releaseName(testRoomId, 'Optimized_1');
await participantNameService.releaseName(testRoomId, 'Optimized_3');
// New participants should get the lowest available numbers
const newName1 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
const newName2 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(newName1).toBe('Optimized_1'); // Lowest available
expect(newName2).toBe('Optimized_3'); // Next lowest available
});
});
describe('releaseName', () => {
it('should release a reserved name', async () => {
const participantName = 'Participant';
// Reserve a name
await participantNameService.reserveUniqueName(testRoomId, participantName);
expect(await participantNameService.isNameReserved(testRoomId, participantName)).toBe(true);
// Release the name
await participantNameService.releaseName(testRoomId, participantName);
expect(await participantNameService.isNameReserved(testRoomId, participantName)).toBe(false);
});
it('should allow reusing a released name', async () => {
const participantName = 'Frank';
// Reserve, release, and reserve again
await participantNameService.reserveUniqueName(testRoomId, participantName);
await participantNameService.releaseName(testRoomId, participantName);
const newReservation = await participantNameService.reserveUniqueName(testRoomId, participantName);
expect(newReservation).toBe(participantName);
});
});
describe('getReservedNames', () => {
it('should return all reserved names in a room in lowercase', async () => {
const names = ['Grace', 'Henry', 'Iris'];
// Reserve multiple names
for (const name of names) {
await participantNameService.reserveUniqueName(testRoomId, name);
}
const reservedNames = await participantNameService.getReservedNames(testRoomId);
for (const name of names) {
expect(reservedNames).toContain(name.toLowerCase());
}
});
it('should return empty array when no names are reserved', async () => {
const reservedNames = await participantNameService.getReservedNames(testRoomId);
expect(reservedNames).toEqual([]);
});
});
describe('Reserve unique participant name - edge cases', () => {
it('should be able to reserve same 20 names', async () => {
const requestedName = 'LimitTest';
const promises: Promise<string>[] = [];
const twentyNames = participantNameService['MAX_CONCURRENT_NAME_REQUESTS'];
for (let i = 0; i <= twentyNames; i++) {
promises.push(participantNameService.reserveUniqueName(testRoomId, requestedName));
}
// Los primeros MAX_RETRIES deben resolverse bien
const results = await Promise.allSettled(promises);
const fulfilled = results.filter((r) => r.status === 'fulfilled') as PromiseFulfilledResult<string>[];
const rejected = results.filter((r) => r.status === 'rejected') as PromiseRejectedResult[];
console.log(fulfilled);
expect(fulfilled.length).toBe(twentyNames + 1); // +1 for the original name
expect(rejected.length).toBe(0);
});
it('should handle race condition when reusing released numbers', async () => {
const requestedName = 'RaceTest';
// Try to reserve two names
const n1 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
const n2 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect([n1, n2]).toEqual(['RaceTest', 'RaceTest_1']);
// Release _1
await participantNameService.releaseName(testRoomId, n2);
// Try to reserve again concurrently
const [c1, c2] = await Promise.all([
participantNameService.reserveUniqueName(testRoomId, requestedName),
participantNameService.reserveUniqueName(testRoomId, requestedName)
]);
// One of them should be _1 and the other should be _2
expect([c1, c2].sort()).toEqual(['RaceTest_1', 'RaceTest_2']);
});
it('should reuse expired names after TTL', async () => {
(participantNameService as any)['PARTICIPANT_NAME_TTL'] = ms('1ms');
const requestedName = 'TTLTest';
// Reserva con TTL muy corto (simulado)
const name = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(name).toBe('TTLTest');
// Wait for TTL to expire
await new Promise((resolve) =>
setTimeout(resolve, (participantNameService['PARTICIPANT_NAME_TTL'] + 1) * 1000)
);
// Try to reserve again
const newName = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(newName).toBe('TTLTest'); // Reuse original name
});
it('should keep names isolated per room', async () => {
const requestedName = 'Isolated';
// Reserve in two different rooms
const room1Name = await participantNameService.reserveUniqueName('room1', requestedName);
const room2Name = await participantNameService.reserveUniqueName('room2', requestedName);
// Both names should be isolated
expect(room1Name).toBe(requestedName);
expect(room2Name).toBe(requestedName);
});
it('should treat names case-insensitively if normalization is enabled', async () => {
const requestedName = 'CaseTest';
const n1 = await participantNameService.reserveUniqueName(testRoomId, requestedName);
expect(n1).toBe('CaseTest');
// Try to reserve with different casing
const n2 = await participantNameService.reserveUniqueName(testRoomId, 'casetest');
expect(n2).toBe('casetest_1'); // Should return alternative name with original case
});
});
});