Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BC-6459 Replace passing error handling in tldraw #5053

Merged
merged 18 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { TextEncoder } from 'util';
import { INestApplication, NotAcceptableException } from '@nestjs/common';
import { MongoMemoryDatabaseModule } from '@infra/database';
import { createConfigModuleOptions } from '@src/config';
import { Logger } from '@src/core/logger';
import { of, throwError } from 'rxjs';
import { createMock, DeepMocked } from '@golevelup/ts-jest';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios';
import { AxiosError, AxiosHeaders, AxiosResponse } from 'axios';
import { axiosResponseFactory } from '@shared/testing';
import { CoreModule } from '@src/core';
import { TldrawRedisFactory, TldrawRedisService } from '../../redis';
import { TldrawDrawing } from '../../entities';
import { TldrawWsService } from '../../service';
Expand All @@ -22,6 +22,7 @@ import { TldrawWs } from '..';
import { WsCloseCode, WsCloseMessage } from '../../types';
import { TldrawConfig } from '../../config';

// This is a unit test, no api test...need to be refactored
describe('WebSocketController (WsAdapter)', () => {
let app: INestApplication;
let gateway: TldrawWs;
Expand All @@ -41,6 +42,7 @@ describe('WebSocketController (WsAdapter)', () => {
imports: [
MongoMemoryDatabaseModule.forRoot({ entities: [TldrawDrawing] }),
ConfigModule.forRoot(createConfigModuleOptions(tldrawTestConfig)),
CoreModule,
],
providers: [
TldrawWs,
Expand All @@ -54,10 +56,6 @@ describe('WebSocketController (WsAdapter)', () => {
provide: TldrawRepo,
useValue: createMock<TldrawRepo>(),
},
{
provide: Logger,
useValue: createMock<Logger>(),
},
{
provide: HttpService,
useValue: createMock<HttpService>(),
Expand All @@ -79,7 +77,7 @@ describe('WebSocketController (WsAdapter)', () => {
});

afterEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});

describe('when tldraw connection is established', () => {
Expand Down
6 changes: 3 additions & 3 deletions apps/server/src/modules/tldraw/controller/tldraw.ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import {
NotFoundException,
NotAcceptableException,
} from '@nestjs/common';
import { Logger } from '@src/core/logger';
import { isAxiosError } from 'axios';
import { firstValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';
import { DomainErrorHandler } from '@src/core';
import { WebsocketInitErrorLoggable } from '../loggable';
import { TldrawConfig, TLDRAW_SOCKET_PORT } from '../config';
import { WsCloseCode, WsCloseMessage } from '../types';
Expand All @@ -27,7 +27,7 @@ export class TldrawWs implements OnGatewayInit, OnGatewayConnection {
private readonly configService: ConfigService<TldrawConfig, true>,
private readonly tldrawWsService: TldrawWsService,
private readonly httpService: HttpService,
private readonly logger: Logger
private readonly domainErrorHandler: DomainErrorHandler
) {}

public async handleConnection(client: WebSocket, request: Request): Promise<void> {
Expand Down Expand Up @@ -106,7 +106,7 @@ export class TldrawWs implements OnGatewayInit, OnGatewayConnection {
err?: unknown
): void {
client.close(code, message);
this.logger.warning(new WebsocketInitErrorLoggable(code, message, docName, err));
this.domainErrorHandler.exec(new WebsocketInitErrorLoggable(code, message, docName, err));
}

private handleError(err: unknown, client: WebSocket, docName: string): void {
Expand Down
16 changes: 3 additions & 13 deletions apps/server/src/modules/tldraw/redis/tldraw-redis.factory.spec.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Test } from '@nestjs/testing';
import { createConfigModuleOptions } from '@src/config';
import { INestApplication } from '@nestjs/common';
import { WsAdapter } from '@nestjs/platform-ws';
import { createMock } from '@golevelup/ts-jest';
import { Logger } from '@src/core/logger';
import { DomainErrorHandler } from '@src/core';
import { RedisConnectionTypeEnum } from '../types';
import { TldrawConfig } from '../config';
import { tldrawTestConfig } from '../testing';
import { TldrawRedisFactory } from './tldraw-redis.factory';

describe('TldrawRedisFactory', () => {
let app: INestApplication;
let configService: ConfigService<TldrawConfig, true>;
let redisFactory: TldrawRedisFactory;

Expand All @@ -21,21 +18,14 @@ describe('TldrawRedisFactory', () => {
providers: [
TldrawRedisFactory,
{
provide: Logger,
useValue: createMock<Logger>(),
provide: DomainErrorHandler,
useValue: createMock<DomainErrorHandler>(),
},
],
}).compile();

configService = testingModule.get(ConfigService);
redisFactory = testingModule.get(TldrawRedisFactory);
app = testingModule.createNestApplication();
app.useWebSocketAdapter(new WsAdapter(app));
await app.init();
});

afterAll(async () => {
await app.close();
});

it('should check if factory was created', () => {
Expand Down
11 changes: 6 additions & 5 deletions apps/server/src/modules/tldraw/redis/tldraw-redis.factory.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { Redis } from 'ioredis';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@src/core/logger';
import { DomainErrorHandler } from '@src/core';
import { TldrawConfig } from '../config';
import { RedisErrorLoggable } from '../loggable';
import { RedisConnectionTypeEnum } from '../types';

@Injectable()
export class TldrawRedisFactory {
constructor(private readonly configService: ConfigService<TldrawConfig, true>, private readonly logger: Logger) {
this.logger.setContext(TldrawRedisFactory.name);
}
constructor(
private readonly configService: ConfigService<TldrawConfig, true>,
private readonly domainErrorHandler: DomainErrorHandler
) {}

public build(connectionType: RedisConnectionTypeEnum) {
const redisUri = this.configService.get<string>('REDIS_URI');
Expand All @@ -22,7 +23,7 @@ export class TldrawRedisFactory {
maxRetriesPerRequest: null,
});

redis.on('error', (err) => this.logger.warning(new RedisErrorLoggable(connectionType, err)));
redis.on('error', (err) => this.domainErrorHandler.exec(new RedisErrorLoggable(connectionType, err)));

return redis;
}
Expand Down
47 changes: 4 additions & 43 deletions apps/server/src/modules/tldraw/redis/tldraw-redis.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import { INestApplication } from '@nestjs/common';
import { createMock } from '@golevelup/ts-jest';
import { Logger } from '@src/core/logger';
import { Test } from '@nestjs/testing';
import { ConfigModule } from '@nestjs/config';
import { createConfigModuleOptions } from '@src/config';
import * as Yjs from 'yjs';
import * as AwarenessProtocol from 'y-protocols/awareness';
import { HttpService } from '@nestjs/axios';
import { WsAdapter } from '@nestjs/platform-ws';
import { TldrawWs } from '../controller';
import { TldrawWsService } from '../service';
import { TldrawBoardRepo, TldrawRepo, YMongodb } from '../repo';
import { MetricsService } from '../metrics';
import { DomainErrorHandler } from '@src/core';
import { WsSharedDocDo } from '../domain';
import { TldrawRedisFactory, TldrawRedisService } from '.';
import { tldrawTestConfig } from '../testing';
Expand All @@ -30,60 +23,28 @@ jest.mock('y-protocols/awareness', () => {
};
return moduleMock;
});
jest.mock('y-protocols/sync', () => {
const moduleMock: unknown = {
__esModule: true,
...jest.requireActual('y-protocols/sync'),
};
return moduleMock;
});

describe('TldrawRedisService', () => {
let app: INestApplication;
let service: TldrawRedisService;

beforeAll(async () => {
const testingModule = await Test.createTestingModule({
imports: [ConfigModule.forRoot(createConfigModuleOptions(tldrawTestConfig))],
providers: [
TldrawWs,
TldrawWsService,
YMongodb,
MetricsService,
TldrawRedisFactory,
TldrawRedisService,
{
provide: TldrawBoardRepo,
useValue: createMock<TldrawBoardRepo>(),
},
{
provide: TldrawRepo,
useValue: createMock<TldrawRepo>(),
},
{
provide: Logger,
useValue: createMock<Logger>(),
},
{
provide: HttpService,
useValue: createMock<HttpService>(),
provide: DomainErrorHandler,
useValue: createMock<DomainErrorHandler>(),
},
],
}).compile();

service = testingModule.get(TldrawRedisService);
app = testingModule.createNestApplication();
app.useWebSocketAdapter(new WsAdapter(app));
await app.init();
});

afterAll(async () => {
await app.close();
});

afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
jest.resetAllMocks();
});

describe('redisMessageHandler', () => {
Expand Down
19 changes: 12 additions & 7 deletions apps/server/src/modules/tldraw/redis/tldraw-redis.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { Logger } from '@src/core/logger';
import { Buffer } from 'node:buffer';
import { applyAwarenessUpdate } from 'y-protocols/awareness';
import { applyUpdate } from 'yjs';
import { DomainErrorHandler } from '@src/core';
import { WsSharedDocDo } from '../domain';
import { RedisConnectionTypeEnum, UpdateOrigin, UpdateType } from '../types';
import { RedisPublishErrorLoggable, WsSharedDocErrorLoggable } from '../loggable';
Expand All @@ -15,9 +15,10 @@ export class TldrawRedisService {

private readonly pub: Redis;

constructor(private readonly logger: Logger, private readonly tldrawRedisFactory: TldrawRedisFactory) {
this.logger.setContext(TldrawRedisService.name);

constructor(
private readonly domainErrorHandler: DomainErrorHandler,
private readonly tldrawRedisFactory: TldrawRedisFactory
) {
this.sub = this.tldrawRedisFactory.build(RedisConnectionTypeEnum.SUBSCRIBE);
this.pub = this.tldrawRedisFactory.build(RedisConnectionTypeEnum.PUBLISH);
}
Expand All @@ -32,20 +33,24 @@ export class TldrawRedisService {

public subscribeToRedisChannels(doc: WsSharedDocDo) {
this.sub.subscribe(doc.name, doc.awarenessChannel).catch((err) => {
this.logger.warning(new WsSharedDocErrorLoggable(doc.name, 'Error while subscribing to Redis channels', err));
this.domainErrorHandler.exec(
new WsSharedDocErrorLoggable(doc.name, 'Error while subscribing to Redis channels', err)
);
});
}

public unsubscribeFromRedisChannels(doc: WsSharedDocDo) {
this.sub.unsubscribe(doc.name, doc.awarenessChannel).catch((err) => {
this.logger.warning(new WsSharedDocErrorLoggable(doc.name, 'Error while unsubscribing from Redis channels', err));
this.domainErrorHandler.exec(
new WsSharedDocErrorLoggable(doc.name, 'Error while unsubscribing from Redis channels', err)
);
});
}

public publishUpdateToRedis(doc: WsSharedDocDo, update: Uint8Array, type: UpdateType) {
const channel = type === UpdateType.AWARENESS ? doc.awarenessChannel : doc.name;
this.pub.publish(channel, Buffer.from(update)).catch((err) => {
this.logger.warning(new RedisPublishErrorLoggable(type, err));
this.domainErrorHandler.exec(new RedisPublishErrorLoggable(type, err));
});
}
}
30 changes: 2 additions & 28 deletions apps/server/src/modules/tldraw/repo/tldraw-board.repo.spec.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,17 @@
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { WsAdapter } from '@nestjs/platform-ws';
import { Doc } from 'yjs';
import { createMock } from '@golevelup/ts-jest';
import { HttpService } from '@nestjs/axios';
import { Logger } from '@src/core/logger';
import { ConfigModule } from '@nestjs/config';
import { MongoMemoryDatabaseModule } from '@infra/database';
import { createConfigModuleOptions } from '@src/config';
import { TldrawBoardRepo } from './tldraw-board.repo';
import { WsSharedDocDo } from '../domain';
import { TldrawWsService } from '../service';
import { tldrawTestConfig } from '../testing';
import { TldrawDrawing } from '../entities';
import { TldrawWs } from '../controller';
import { MetricsService } from '../metrics';
import { TldrawRepo } from './tldraw.repo';
import { YMongodb } from './y-mongodb';
import { TldrawRedisFactory, TldrawRedisService } from '../redis';

describe('TldrawBoardRepo', () => {
let app: INestApplication;
let repo: TldrawBoardRepo;

beforeAll(async () => {
Expand All @@ -30,32 +21,19 @@ describe('TldrawBoardRepo', () => {
ConfigModule.forRoot(createConfigModuleOptions(tldrawTestConfig)),
],
providers: [
TldrawWs,
TldrawWsService,
TldrawBoardRepo,
YMongodb,
MetricsService,
TldrawRedisFactory,
TldrawRedisService,
{
provide: TldrawRepo,
useValue: createMock<TldrawRepo>(),
provide: YMongodb,
useValue: createMock<YMongodb>(),
},
{
provide: Logger,
useValue: createMock<Logger>(),
},
{
provide: HttpService,
useValue: createMock<HttpService>(),
},
],
}).compile();

repo = testingModule.get(TldrawBoardRepo);
app = testingModule.createNestApplication();
app.useWebSocketAdapter(new WsAdapter(app));
await app.init();

jest.useFakeTimers();
});
Expand All @@ -64,10 +42,6 @@ describe('TldrawBoardRepo', () => {
jest.resetAllMocks();
});

afterAll(async () => {
await app.close();
});

it('should check if repo and its properties are set correctly', () => {
expect(repo).toBeDefined();
expect(repo.mdb).toBeDefined();
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/modules/tldraw/repo/tldraw-board.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export class TldrawBoardRepo {
}

public async getDocumentFromDb(docName: string): Promise<WsSharedDocDo> {
// can be return null, return type of functions need to be improve
const yDoc = await this.mdb.getDocument(docName);
return yDoc;
}
Expand Down
9 changes: 4 additions & 5 deletions apps/server/src/modules/tldraw/repo/tldraw.repo.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb';
import { Test, TestingModule } from '@nestjs/testing';
import { cleanupCollections } from '@shared/testing';
import { MikroORM } from '@mikro-orm/core';
import { ConfigModule } from '@nestjs/config';
import { createConfigModuleOptions } from '@src/config';
import { tldrawEntityFactory, tldrawTestConfig } from '../testing';
import { MongoMemoryDatabaseModule } from '@src/infra/database';
import { tldrawEntityFactory } from '../testing';
import { TldrawDrawing } from '../entities';
import { TldrawRepo } from './tldraw.repo';
import { TldrawWsTestModule } from '../tldraw-ws-test.module';

describe('TldrawRepo', () => {
let testingModule: TestingModule;
Expand All @@ -17,7 +15,8 @@ describe('TldrawRepo', () => {

beforeAll(async () => {
testingModule = await Test.createTestingModule({
imports: [TldrawWsTestModule, ConfigModule.forRoot(createConfigModuleOptions(tldrawTestConfig))],
imports: [MongoMemoryDatabaseModule.forRoot({ entities: [TldrawDrawing] })],
providers: [TldrawRepo],
}).compile();

repo = testingModule.get(TldrawRepo);
Expand Down
Loading
Loading