1
0
Fork 0
mirror of https://github.com/immich-app/immich.git synced 2025-01-28 06:32:44 +01:00

refactor(server): event names ()

This commit is contained in:
Jason Rasmussen 2024-08-27 18:06:50 -04:00 committed by GitHub
parent aac6a4b052
commit 0be3c4472f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 55 additions and 54 deletions

View file

@ -62,7 +62,7 @@ export class ApiModule implements OnModuleInit, OnModuleDestroy {
async onModuleInit() { async onModuleInit() {
const items = setupEventHandlers(this.moduleRef); const items = setupEventHandlers(this.moduleRef);
await this.eventRepository.emit('onBootstrap', 'api'); await this.eventRepository.emit('app.bootstrap', 'api');
this.logger.setContext('EventLoader'); this.logger.setContext('EventLoader');
const eventMap = _.groupBy(items, 'event'); const eventMap = _.groupBy(items, 'event');
@ -74,7 +74,7 @@ export class ApiModule implements OnModuleInit, OnModuleDestroy {
} }
async onModuleDestroy() { async onModuleDestroy() {
await this.eventRepository.emit('onShutdown'); await this.eventRepository.emit('app.shutdown');
} }
} }
@ -90,11 +90,11 @@ export class MicroservicesModule implements OnModuleInit, OnModuleDestroy {
async onModuleInit() { async onModuleInit() {
setupEventHandlers(this.moduleRef); setupEventHandlers(this.moduleRef);
await this.eventRepository.emit('onBootstrap', 'microservices'); await this.eventRepository.emit('app.bootstrap', 'microservices');
} }
async onModuleDestroy() { async onModuleDestroy() {
await this.eventRepository.emit('onShutdown'); await this.eventRepository.emit('app.shutdown');
} }
} }

View file

@ -6,19 +6,19 @@ export const IEventRepository = 'IEventRepository';
type EmitEventMap = { type EmitEventMap = {
// app events // app events
onBootstrap: ['api' | 'microservices']; 'app.bootstrap': ['api' | 'microservices'];
onShutdown: []; 'app.shutdown': [];
// config events // config events
onConfigUpdate: [{ newConfig: SystemConfig; oldConfig: SystemConfig }]; 'config.update': [{ newConfig: SystemConfig; oldConfig: SystemConfig }];
onConfigValidate: [{ newConfig: SystemConfig; oldConfig: SystemConfig }]; 'config.validate': [{ newConfig: SystemConfig; oldConfig: SystemConfig }];
// album events // album events
onAlbumUpdate: [{ id: string; updatedBy: string }]; 'album.update': [{ id: string; updatedBy: string }];
onAlbumInvite: [{ id: string; userId: string }]; 'album.invite': [{ id: string; userId: string }];
// user events // user events
onUserSignup: [{ notify: boolean; id: string; tempPassword?: string }]; 'user.signup': [{ notify: boolean; id: string; tempPassword?: string }];
}; };
export type EmitEvent = keyof EmitEventMap; export type EmitEvent = keyof EmitEventMap;

View file

@ -205,7 +205,7 @@ describe(AlbumService.name, () => {
expect(userMock.get).toHaveBeenCalledWith('user-id', {}); expect(userMock.get).toHaveBeenCalledWith('user-id', {});
expect(accessMock.asset.checkOwnerAccess).toHaveBeenCalledWith(authStub.admin.user.id, new Set(['123'])); expect(accessMock.asset.checkOwnerAccess).toHaveBeenCalledWith(authStub.admin.user.id, new Set(['123']));
expect(eventMock.emit).toHaveBeenCalledWith('onAlbumInvite', { expect(eventMock.emit).toHaveBeenCalledWith('album.invite', {
id: albumStub.empty.id, id: albumStub.empty.id,
userId: 'user-id', userId: 'user-id',
}); });
@ -384,7 +384,7 @@ describe(AlbumService.name, () => {
userId: authStub.user2.user.id, userId: authStub.user2.user.id,
albumId: albumStub.sharedWithAdmin.id, albumId: albumStub.sharedWithAdmin.id,
}); });
expect(eventMock.emit).toHaveBeenCalledWith('onAlbumInvite', { expect(eventMock.emit).toHaveBeenCalledWith('album.invite', {
id: albumStub.sharedWithAdmin.id, id: albumStub.sharedWithAdmin.id,
userId: userStub.user2.id, userId: userStub.user2.id,
}); });
@ -572,7 +572,7 @@ describe(AlbumService.name, () => {
albumThumbnailAssetId: 'asset-1', albumThumbnailAssetId: 'asset-1',
}); });
expect(albumMock.addAssetIds).toHaveBeenCalledWith('album-123', ['asset-1', 'asset-2', 'asset-3']); expect(albumMock.addAssetIds).toHaveBeenCalledWith('album-123', ['asset-1', 'asset-2', 'asset-3']);
expect(eventMock.emit).toHaveBeenCalledWith('onAlbumUpdate', { expect(eventMock.emit).toHaveBeenCalledWith('album.update', {
id: 'album-123', id: 'album-123',
updatedBy: authStub.admin.user.id, updatedBy: authStub.admin.user.id,
}); });
@ -616,7 +616,7 @@ describe(AlbumService.name, () => {
albumThumbnailAssetId: 'asset-1', albumThumbnailAssetId: 'asset-1',
}); });
expect(albumMock.addAssetIds).toHaveBeenCalledWith('album-123', ['asset-1', 'asset-2', 'asset-3']); expect(albumMock.addAssetIds).toHaveBeenCalledWith('album-123', ['asset-1', 'asset-2', 'asset-3']);
expect(eventMock.emit).toHaveBeenCalledWith('onAlbumUpdate', { expect(eventMock.emit).toHaveBeenCalledWith('album.update', {
id: 'album-123', id: 'album-123',
updatedBy: authStub.user1.user.id, updatedBy: authStub.user1.user.id,
}); });

View file

@ -140,7 +140,7 @@ export class AlbumService {
}); });
for (const { userId } of albumUsers) { for (const { userId } of albumUsers) {
await this.eventRepository.emit('onAlbumInvite', { id: album.id, userId }); await this.eventRepository.emit('album.invite', { id: album.id, userId });
} }
return mapAlbumWithAssets(album); return mapAlbumWithAssets(album);
@ -192,7 +192,7 @@ export class AlbumService {
albumThumbnailAssetId: album.albumThumbnailAssetId ?? firstNewAssetId, albumThumbnailAssetId: album.albumThumbnailAssetId ?? firstNewAssetId,
}); });
await this.eventRepository.emit('onAlbumUpdate', { id, updatedBy: auth.user.id }); await this.eventRepository.emit('album.update', { id, updatedBy: auth.user.id });
} }
return results; return results;
@ -240,7 +240,7 @@ export class AlbumService {
} }
await this.albumUserRepository.create({ userId: userId, albumId: id, role }); await this.albumUserRepository.create({ userId: userId, albumId: id, role });
await this.eventRepository.emit('onAlbumInvite', { id, userId }); await this.eventRepository.emit('album.invite', { id, userId });
} }
return this.findOrFail(id, { withAssets: true }).then(mapAlbumWithoutAssets); return this.findOrFail(id, { withAssets: true }).then(mapAlbumWithoutAssets);

View file

@ -68,7 +68,7 @@ export class DatabaseService {
this.logger.setContext(DatabaseService.name); this.logger.setContext(DatabaseService.name);
} }
@OnEmit({ event: 'onBootstrap', priority: -200 }) @OnEmit({ event: 'app.bootstrap', priority: -200 })
async onBootstrap() { async onBootstrap() {
const version = await this.databaseRepository.getPostgresVersion(); const version = await this.databaseRepository.getPostgresVersion();
const current = semver.coerce(version); const current = semver.coerce(version);

View file

@ -66,7 +66,7 @@ export class LibraryService {
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger); this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
} }
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
async onBootstrap() { async onBootstrap() {
const config = await this.configCore.getConfig({ withCache: false }); const config = await this.configCore.getConfig({ withCache: false });
@ -104,7 +104,8 @@ export class LibraryService {
}); });
} }
onConfigValidate({ newConfig }: ArgOf<'onConfigValidate'>) { @OnEmit({ event: 'config.validate' })
onConfigValidate({ newConfig }: ArgOf<'config.validate'>) {
const { scan } = newConfig.library; const { scan } = newConfig.library;
if (!validateCronExpression(scan.cronExpression)) { if (!validateCronExpression(scan.cronExpression)) {
throw new Error(`Invalid cron expression ${scan.cronExpression}`); throw new Error(`Invalid cron expression ${scan.cronExpression}`);
@ -189,7 +190,7 @@ export class LibraryService {
} }
} }
@OnEmit({ event: 'onShutdown' }) @OnEmit({ event: 'app.shutdown' })
async onShutdown() { async onShutdown() {
await this.unwatchAll(); await this.unwatchAll();
} }

View file

@ -121,8 +121,8 @@ export class MetadataService {
); );
} }
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
async onBootstrap(app: ArgOf<'onBootstrap'>) { async onBootstrap(app: ArgOf<'app.bootstrap'>) {
if (app !== 'microservices') { if (app !== 'microservices') {
return; return;
} }
@ -130,8 +130,8 @@ export class MetadataService {
await this.init(config); await this.init(config);
} }
@OnEmit({ event: 'onConfigUpdate' }) @OnEmit({ event: 'config.update' })
async onConfigUpdate({ newConfig }: ArgOf<'onConfigUpdate'>) { async onConfigUpdate({ newConfig }: ArgOf<'config.update'>) {
await this.init(newConfig); await this.init(newConfig);
} }
@ -153,7 +153,7 @@ export class MetadataService {
} }
} }
@OnEmit({ event: 'onShutdown' }) @OnEmit({ event: 'app.shutdown' })
async onShutdown() { async onShutdown() {
await this.repository.teardown(); await this.repository.teardown();
} }

View file

@ -39,8 +39,8 @@ export class MicroservicesService {
private versionService: VersionService, private versionService: VersionService,
) {} ) {}
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
async onBootstrap(app: ArgOf<'onBootstrap'>) { async onBootstrap(app: ArgOf<'app.bootstrap'>) {
if (app !== 'microservices') { if (app !== 'microservices') {
return; return;
} }

View file

@ -42,8 +42,8 @@ export class NotificationService {
this.configCore = SystemConfigCore.create(systemMetadataRepository, logger); this.configCore = SystemConfigCore.create(systemMetadataRepository, logger);
} }
@OnEmit({ event: 'onConfigValidate', priority: -100 }) @OnEmit({ event: 'config.validate', priority: -100 })
async onConfigValidate({ oldConfig, newConfig }: ArgOf<'onConfigValidate'>) { async onConfigValidate({ oldConfig, newConfig }: ArgOf<'config.validate'>) {
try { try {
if ( if (
newConfig.notifications.smtp.enabled && newConfig.notifications.smtp.enabled &&
@ -57,20 +57,20 @@ export class NotificationService {
} }
} }
@OnEmit({ event: 'onUserSignup' }) @OnEmit({ event: 'user.signup' })
async onUserSignup({ notify, id, tempPassword }: ArgOf<'onUserSignup'>) { async onUserSignup({ notify, id, tempPassword }: ArgOf<'user.signup'>) {
if (notify) { if (notify) {
await this.jobRepository.queue({ name: JobName.NOTIFY_SIGNUP, data: { id, tempPassword } }); await this.jobRepository.queue({ name: JobName.NOTIFY_SIGNUP, data: { id, tempPassword } });
} }
} }
@OnEmit({ event: 'onAlbumUpdate' }) @OnEmit({ event: 'album.update' })
async onAlbumUpdate({ id, updatedBy }: ArgOf<'onAlbumUpdate'>) { async onAlbumUpdate({ id, updatedBy }: ArgOf<'album.update'>) {
await this.jobRepository.queue({ name: JobName.NOTIFY_ALBUM_UPDATE, data: { id, senderId: updatedBy } }); await this.jobRepository.queue({ name: JobName.NOTIFY_ALBUM_UPDATE, data: { id, senderId: updatedBy } });
} }
@OnEmit({ event: 'onAlbumInvite' }) @OnEmit({ event: 'album.invite' })
async onAlbumInvite({ id, userId }: ArgOf<'onAlbumInvite'>) { async onAlbumInvite({ id, userId }: ArgOf<'album.invite'>) {
await this.jobRepository.queue({ name: JobName.NOTIFY_ALBUM_INVITE, data: { id, recipientId: userId } }); await this.jobRepository.queue({ name: JobName.NOTIFY_ALBUM_INVITE, data: { id, recipientId: userId } });
} }

View file

@ -42,7 +42,7 @@ export class ServerService {
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger); this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
} }
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
async onBootstrap(): Promise<void> { async onBootstrap(): Promise<void> {
const featureFlags = await this.getFeatures(); const featureFlags = await this.getFeatures();
if (featureFlags.configFile) { if (featureFlags.configFile) {

View file

@ -39,8 +39,8 @@ export class SmartInfoService {
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger); this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
} }
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
async onBootstrap(app: ArgOf<'onBootstrap'>) { async onBootstrap(app: ArgOf<'app.bootstrap'>) {
if (app !== 'microservices') { if (app !== 'microservices') {
return; return;
} }
@ -49,8 +49,8 @@ export class SmartInfoService {
await this.init(config); await this.init(config);
} }
@OnEmit({ event: 'onConfigValidate' }) @OnEmit({ event: 'config.validate' })
onConfigValidate({ newConfig }: ArgOf<'onConfigValidate'>) { onConfigValidate({ newConfig }: ArgOf<'config.validate'>) {
try { try {
getCLIPModelInfo(newConfig.machineLearning.clip.modelName); getCLIPModelInfo(newConfig.machineLearning.clip.modelName);
} catch { } catch {
@ -60,8 +60,8 @@ export class SmartInfoService {
} }
} }
@OnEmit({ event: 'onConfigUpdate' }) @OnEmit({ event: 'config.update' })
async onConfigUpdate({ oldConfig, newConfig }: ArgOf<'onConfigUpdate'>) { async onConfigUpdate({ oldConfig, newConfig }: ArgOf<'config.update'>) {
await this.init(newConfig, oldConfig); await this.init(newConfig, oldConfig);
} }

View file

@ -89,8 +89,8 @@ export class StorageTemplateService {
); );
} }
@OnEmit({ event: 'onConfigValidate' }) @OnEmit({ event: 'config.validate' })
onConfigValidate({ newConfig }: ArgOf<'onConfigValidate'>) { onConfigValidate({ newConfig }: ArgOf<'config.validate'>) {
try { try {
const { compiled } = this.compile(newConfig.storageTemplate.template); const { compiled } = this.compile(newConfig.storageTemplate.template);
this.render(compiled, { this.render(compiled, {

View file

@ -14,7 +14,7 @@ export class StorageService {
this.logger.setContext(StorageService.name); this.logger.setContext(StorageService.name);
} }
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
onBootstrap() { onBootstrap() {
const libraryBase = StorageCore.getBaseFolder(StorageFolder.LIBRARY); const libraryBase = StorageCore.getBaseFolder(StorageFolder.LIBRARY);
this.storageRepository.mkdirSync(libraryBase); this.storageRepository.mkdirSync(libraryBase);

View file

@ -33,7 +33,7 @@ export class SystemConfigService {
this.core.config$.subscribe((config) => this.setLogLevel(config)); this.core.config$.subscribe((config) => this.setLogLevel(config));
} }
@OnEmit({ event: 'onBootstrap', priority: -100 }) @OnEmit({ event: 'app.bootstrap', priority: -100 })
async onBootstrap() { async onBootstrap() {
const config = await this.core.getConfig({ withCache: false }); const config = await this.core.getConfig({ withCache: false });
this.core.config$.next(config); this.core.config$.next(config);
@ -48,8 +48,8 @@ export class SystemConfigService {
return mapConfig(defaults); return mapConfig(defaults);
} }
@OnEmit({ event: 'onConfigValidate' }) @OnEmit({ event: 'config.validate' })
onConfigValidate({ newConfig, oldConfig }: ArgOf<'onConfigValidate'>) { onConfigValidate({ newConfig, oldConfig }: ArgOf<'config.validate'>) {
if (!_.isEqual(instanceToPlain(newConfig.logging), oldConfig.logging) && this.getEnvLogLevel()) { if (!_.isEqual(instanceToPlain(newConfig.logging), oldConfig.logging) && this.getEnvLogLevel()) {
throw new Error('Logging cannot be changed while the environment variable IMMICH_LOG_LEVEL is set.'); throw new Error('Logging cannot be changed while the environment variable IMMICH_LOG_LEVEL is set.');
} }
@ -63,7 +63,7 @@ export class SystemConfigService {
const oldConfig = await this.core.getConfig({ withCache: false }); const oldConfig = await this.core.getConfig({ withCache: false });
try { try {
await this.eventRepository.emit('onConfigValidate', { newConfig: dto, oldConfig }); await this.eventRepository.emit('config.validate', { newConfig: dto, oldConfig });
} catch (error) { } catch (error) {
this.logger.warn(`Unable to save system config due to a validation error: ${error}`); this.logger.warn(`Unable to save system config due to a validation error: ${error}`);
throw new BadRequestException(error instanceof Error ? error.message : error); throw new BadRequestException(error instanceof Error ? error.message : error);
@ -74,7 +74,7 @@ export class SystemConfigService {
// TODO probably move web socket emits to a separate service // TODO probably move web socket emits to a separate service
this.eventRepository.clientBroadcast(ClientEvent.CONFIG_UPDATE, {}); this.eventRepository.clientBroadcast(ClientEvent.CONFIG_UPDATE, {});
this.eventRepository.serverSend(ServerEvent.CONFIG_UPDATE, null); this.eventRepository.serverSend(ServerEvent.CONFIG_UPDATE, null);
await this.eventRepository.emit('onConfigUpdate', { newConfig, oldConfig }); await this.eventRepository.emit('config.update', { newConfig, oldConfig });
return mapConfig(newConfig); return mapConfig(newConfig);
} }

View file

@ -45,7 +45,7 @@ export class UserAdminService {
const { notify, ...rest } = dto; const { notify, ...rest } = dto;
const user = await this.userCore.createUser(rest); const user = await this.userCore.createUser(rest);
await this.eventRepository.emit('onUserSignup', { await this.eventRepository.emit('user.signup', {
notify: !!notify, notify: !!notify,
id: user.id, id: user.id,
tempPassword: user.shouldChangePassword ? rest.password : undefined, tempPassword: user.shouldChangePassword ? rest.password : undefined,

View file

@ -37,7 +37,7 @@ export class VersionService {
this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger); this.configCore = SystemConfigCore.create(systemMetadataRepository, this.logger);
} }
@OnEmit({ event: 'onBootstrap' }) @OnEmit({ event: 'app.bootstrap' })
async onBootstrap(): Promise<void> { async onBootstrap(): Promise<void> {
await this.handleVersionCheck(); await this.handleVersionCheck();
} }