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

EW-998 created a new sync Module #5222

Merged
merged 17 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from 16 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
2 changes: 2 additions & 0 deletions apps/server/src/console/console.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Configuration } from '@hpi-schul-cloud/commons/lib';
import { ConsoleWriterModule } from '@infra/console/console-writer/console-writer.module';

Check warning on line 2 in apps/server/src/console/console.module.ts

View workflow job for this annotation

GitHub Actions / nest_lint

'@infra/console/console-writer/console-writer.module' import is restricted from being used by a pattern. Do not deep import from a module
import { KeycloakModule } from '@infra/identity-management/keycloak/keycloak.module';

Check warning on line 3 in apps/server/src/console/console.module.ts

View workflow job for this annotation

GitHub Actions / nest_lint

'@infra/identity-management/keycloak/keycloak.module' import is restricted from being used by a pattern. Do not deep import from a module
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { FilesModule } from '@modules/files';
import { ManagementModule } from '@modules/management/management.module';
Expand All @@ -9,6 +9,7 @@
import { ConfigModule } from '@nestjs/config';
import { createConfigModuleOptions } from '@src/config';
import { ConsoleModule } from 'nestjs-console';
import { SyncModule } from '@infra/sync/sync.module';
import { ServerConsole } from './server.console';
import { mikroOrmCliConfig } from '../config/mikro-orm-cli.config';

Expand All @@ -21,6 +22,7 @@
ConfigModule.forRoot(createConfigModuleOptions(serverConfig)),
...((Configuration.get('FEATURE_IDENTITY_MANAGEMENT_ENABLED') as boolean) ? [KeycloakModule] : []),
MikroOrmModule.forRoot(mikroOrmCliConfig),
SyncModule,
],
providers: [
/** add console services as providers */
Expand Down
49 changes: 49 additions & 0 deletions apps/server/src/infra/sync/console/sync.console.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { createMock } from '@golevelup/ts-jest';
import { Test } from '@nestjs/testing';
import { Logger } from '@src/core/logger';
import { SyncUc } from '../uc/sync.uc';
import { SyncConsole } from './sync.console';

describe(SyncConsole.name, () => {
let syncConsole: SyncConsole;
let syncUc: SyncUc;

beforeAll(async () => {
const module = await Test.createTestingModule({
providers: [
SyncConsole,
{
provide: SyncUc,
useValue: createMock<SyncUc>(),
},
{
provide: Logger,
useValue: createMock<Logger>(),
},
],
}).compile();

syncConsole = module.get(SyncConsole);
syncUc = module.get(SyncUc);
});

describe('when sync console is initialized', () => {
it('should be defined', () => {
expect(syncConsole).toBeDefined();
});
});

describe('startSync', () => {
const setup = () => {
const target = 'tsp';
return { target };
};

it('should call startSync method of syncUc', async () => {
const { target } = setup();
await syncConsole.startSync(target);

expect(syncUc.startSync).toHaveBeenCalledWith(target);
});
});
});
18 changes: 18 additions & 0 deletions apps/server/src/infra/sync/console/sync.console.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Logger } from '@src/core/logger';
import { Command, Console } from 'nestjs-console';
import { SyncUc } from '../uc/sync.uc';

@Console({ command: 'sync', description: 'Prefixes all synchronization related console commands.' })
export class SyncConsole {
constructor(private readonly syncUc: SyncUc, private readonly logger: Logger) {
this.logger.setContext(SyncConsole.name);
}

@Command({
command: 'run <target>',
description: 'Starts the synchronization process.',
})
public async startSync(target: string): Promise<void> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if target is empty?

Copy link
Contributor Author

@Fshmit Fshmit Sep 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is aborted with the error message "missing required argument "

await this.syncUc.startSync(target);
}
}
28 changes: 28 additions & 0 deletions apps/server/src/infra/sync/errors/invalid-target.loggable.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { SyncStrategyTarget } from '../sync-strategy.types';
import { InvalidTargetLoggable } from './invalid-target.loggable';

describe(InvalidTargetLoggable.name, () => {
let loggable: InvalidTargetLoggable;

beforeAll(() => {
loggable = new InvalidTargetLoggable('invalid-target');
});

describe('when loggable is initialized', () => {
it('should be defined', () => {
expect(loggable).toBeDefined();
});
});

describe('getLogMessage', () => {
it('should return a log message with the entered target and available targets', () => {
expect(loggable.getLogMessage()).toEqual({
message: 'Either synchronization is not activated or the target entered is invalid',
data: {
enteredTarget: 'invalid-target',
avaliableTargets: SyncStrategyTarget,
},
});
});
});
});
16 changes: 16 additions & 0 deletions apps/server/src/infra/sync/errors/invalid-target.loggable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ErrorLogMessage, LogMessage, Loggable, ValidationErrorLogMessage } from '@src/core/logger';
import { SyncStrategyTarget } from '../sync-strategy.types';

export class InvalidTargetLoggable implements Loggable {
constructor(private readonly target: string) {}

getLogMessage(): LogMessage | ErrorLogMessage | ValidationErrorLogMessage {
return {
message: 'Either synchronization is not activated or the target entered is invalid',
data: {
enteredTarget: this.target,
avaliableTargets: SyncStrategyTarget,
},
};
}
}
86 changes: 86 additions & 0 deletions apps/server/src/infra/sync/service/sync.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { Test, TestingModule } from '@nestjs/testing';
import { createMock } from '@golevelup/ts-jest';
import { faker } from '@faker-js/faker';
import { Logger } from '@src/core/logger';
import { SyncService } from './sync.service';
import { TspSyncStrategy } from '../tsp/tsp-sync.strategy';
import { SyncStrategyTarget } from '../sync-strategy.types';
import { InvalidTargetLoggable } from '../errors/invalid-target.loggable';

describe(SyncService.name, () => {
let module: TestingModule;
let service: SyncService;
let tspSyncStrategy: TspSyncStrategy;
let logger: Logger;

beforeAll(async () => {
module = await Test.createTestingModule({
providers: [
SyncService,
{
provide: TspSyncStrategy,
useValue: createMock<TspSyncStrategy>({
getType(): SyncStrategyTarget {
return SyncStrategyTarget.TSP;
},
sync(): Promise<void> {
return Promise.resolve();
},
}),
},
{
provide: Logger,
useValue: createMock<Logger>(),
},
],
}).compile();

service = module.get(SyncService);
tspSyncStrategy = module.get(TspSyncStrategy);
logger = module.get(Logger);
});

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

describe('when sync service is initialized', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});
});

describe('startSync', () => {
describe('when provided target is invalid or the sync is deactivated', () => {
const setup = () => {
const invalidTarget = faker.lorem.word();
const output = new InvalidTargetLoggable(invalidTarget);

return { output, invalidTarget };
};

it('should throw an invalid provided target error', async () => {
const { output, invalidTarget } = setup();
await service.startSync(invalidTarget);

expect(logger.info).toHaveBeenCalledWith(output);
});
});

describe('when provided target is valid and synchronization is activated', () => {
const setup = () => {
const validSystem = 'tsp';
Reflect.set(service, 'strategies', new Map([[SyncStrategyTarget.TSP, tspSyncStrategy]]));

return { validSystem };
};

it('should call sync method of the provided target', async () => {
const { validSystem } = setup();
await service.startSync(validSystem);

expect(tspSyncStrategy.sync).toHaveBeenCalled();
});
});
});
});
30 changes: 30 additions & 0 deletions apps/server/src/infra/sync/service/sync.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Injectable, Optional } from '@nestjs/common';
import { Logger } from '@src/core/logger';
import { TspSyncStrategy } from '../tsp/tsp-sync.strategy';
import { SyncStrategy } from '../strategy/sync-strategy';
import { SyncStrategyTarget } from '../sync-strategy.types';
import { InvalidTargetLoggable } from '../errors/invalid-target.loggable';

@Injectable()
export class SyncService {
private strategies: Map<SyncStrategyTarget, SyncStrategy> = new Map<SyncStrategyTarget, SyncStrategy>();

constructor(private readonly logger: Logger, @Optional() private readonly tspSyncStrategy?: TspSyncStrategy) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this works alright wit hone strategy, but we need to find a better way if there is ever a second one

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

noticed ✅

this.logger.setContext(SyncService.name);
this.registerStrategy(tspSyncStrategy);
}

protected registerStrategy(strategy?: SyncStrategy) {
if (strategy) {
this.strategies.set(strategy.getType(), strategy);
}
}

public async startSync(target: string): Promise<void> {
const targetStrategy = target as SyncStrategyTarget;
mkreuzkam-cap marked this conversation as resolved.
Show resolved Hide resolved
if (!this.strategies.has(targetStrategy)) {
this.logger.info(new InvalidTargetLoggable(target));
}
await this.strategies.get(targetStrategy)?.sync();
}
}
7 changes: 7 additions & 0 deletions apps/server/src/infra/sync/strategy/sync-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { SyncStrategyTarget } from '../sync-strategy.types';

export abstract class SyncStrategy {
abstract getType(): SyncStrategyTarget;

abstract sync(): Promise<void>;
}
3 changes: 3 additions & 0 deletions apps/server/src/infra/sync/sync-strategy.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export enum SyncStrategyTarget {
TSP = 'tsp',
}
20 changes: 20 additions & 0 deletions apps/server/src/infra/sync/sync.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { LoggerModule } from '@src/core/logger';
import { ConsoleWriterModule } from '@infra/console';
import { Configuration } from '@hpi-schul-cloud/commons/lib';
import { SyncConsole } from './console/sync.console';
import { SyncUc } from './uc/sync.uc';
import { SyncService } from './service/sync.service';
import { TspSyncStrategy } from './tsp/tsp-sync.strategy';

@Module({
imports: [LoggerModule, ConsoleWriterModule],
providers: [
SyncConsole,
SyncUc,
SyncService,
...((Configuration.get('FEATURE_TSP_SYNC_ENABLED') as boolean) ? [TspSyncStrategy] : []),
],
exports: [SyncConsole],
})
export class SyncModule {}
42 changes: 42 additions & 0 deletions apps/server/src/infra/sync/tsp/tsp-sync.strategy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { TestingModule, Test } from '@nestjs/testing';
import { SyncStrategyTarget } from '../sync-strategy.types';
import { TspSyncStrategy } from './tsp-sync.strategy';

describe(TspSyncStrategy.name, () => {
let module: TestingModule;
let strategy: TspSyncStrategy;

beforeAll(async () => {
module = await Test.createTestingModule({
providers: [TspSyncStrategy],
}).compile();

strategy = module.get(TspSyncStrategy);
});

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

describe('when tsp sync strategy is initialized', () => {
it('should be defined', () => {
expect(strategy).toBeDefined();
});
});

describe('getType', () => {
describe('when tsp sync strategy is initialized', () => {
it('should return tsp', () => {
expect(strategy.getType()).toBe(SyncStrategyTarget.TSP);
});
});
});

describe('sync', () => {
it('should return a promise', () => {
const result = strategy.sync();

expect(result).toBeInstanceOf(Promise);
});
});
});
15 changes: 15 additions & 0 deletions apps/server/src/infra/sync/tsp/tsp-sync.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Injectable } from '@nestjs/common';
import { SyncStrategy } from '../strategy/sync-strategy';
import { SyncStrategyTarget } from '../sync-strategy.types';

@Injectable()
export class TspSyncStrategy extends SyncStrategy {
getType(): SyncStrategyTarget {
return SyncStrategyTarget.TSP;
}

sync(): Promise<void> {
// implementation
return Promise.resolve();
}
}
47 changes: 47 additions & 0 deletions apps/server/src/infra/sync/uc/sync.uc.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Test, TestingModule } from '@nestjs/testing';
import { createMock } from '@golevelup/ts-jest';
import { SyncUc } from './sync.uc';
import { SyncService } from '../service/sync.service';

describe(SyncUc.name, () => {
let module: TestingModule;
let uc: SyncUc;
let service: SyncService;

beforeAll(async () => {
module = await Test.createTestingModule({
providers: [
SyncUc,
{
provide: SyncService,
useValue: createMock<SyncService>({}),
},
],
}).compile();
uc = module.get(SyncUc);
service = module.get(SyncService);
});

describe('when sync uc is initialized', () => {
it('should be defined', () => {
expect(uc).toBeDefined();
});
});

describe('startSync', () => {
describe('when calling startSync', () => {
const setup = () => {
const validTarget = 'tsp';

return { validTarget };
};

it('should call sync method', async () => {
const { validTarget } = setup();
await uc.startSync(validTarget);

expect(service.startSync).toHaveBeenCalledWith(validTarget);
});
});
});
});
Loading
Loading