Skip to content

Commit

Permalink
added daily delta on file size change
Browse files Browse the repository at this point in the history
  • Loading branch information
apsantiso committed Dec 3, 2024
1 parent 24cdf62 commit 0a03f0c
Show file tree
Hide file tree
Showing 6 changed files with 138 additions and 13 deletions.
2 changes: 2 additions & 0 deletions src/modules/file/file.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { SharingModule } from '../sharing/sharing.module';
import { WorkspacesModule } from '../workspaces/workspaces.module';
import { UserModule } from '../user/user.module';
import { NotificationModule } from '../../externals/notifications/notifications.module';
import { UsageModule } from '../usage/usage.module';

@Module({
imports: [
Expand All @@ -28,6 +29,7 @@ import { NotificationModule } from '../../externals/notifications/notifications.
CryptoModule,
UserModule,
NotificationModule,
UsageModule,
],
controllers: [FileController],
providers: [SequelizeFileRepository, FileUseCases],
Expand Down
15 changes: 9 additions & 6 deletions src/modules/file/file.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,13 @@ export class SequelizeFileRepository implements FileRepository {
async sumFileSizesSinceDate(
userId: FileAttributes['userId'],
sinceDate: Date,
untilDate?: Date,
): Promise<number> {
const timeCondition = {
[Op.gte]: sinceDate,
...(untilDate ? { [Op.lte]: untilDate } : null),
};

const result = await this.fileModel.findAll({
attributes: [
[
Expand All @@ -620,19 +626,16 @@ export class SequelizeFileRepository implements FileRepository {
status: {
[Op.ne]: 'DELETED',
},
createdAt: {
[Op.gte]: sinceDate,
},
createdAt: timeCondition,
},
{
status: 'DELETED',
updatedAt: {
[Op.gte]: sinceDate,
},
updatedAt: timeCondition,
},
],
},
raw: true,
logging: console.log,
});

return Number(result[0]['total']) as unknown as number;
Expand Down
16 changes: 14 additions & 2 deletions src/modules/file/file.usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { WorkspaceAttributes } from '../workspaces/attributes/workspace.attribut
import { Folder } from '../folder/folder.domain';
import { getPathFileData } from '../../lib/path';
import { isStringEmpty } from '../../lib/validators';
import { UsageUseCases } from '../usage/usage.usecase';

export type SortParamsFile = Array<[SortableFileAttributes, 'ASC' | 'DESC']>;

Expand All @@ -49,6 +50,7 @@ export class FileUseCases {
private sharingUsecases: SharingService,
private network: BridgeService,
private cryptoService: CryptoService,
private usageUsecases: UsageUseCases,
) {}

getByUuid(uuid: FileAttributes['uuid']): Promise<File> {
Expand Down Expand Up @@ -540,7 +542,7 @@ export class FileUseCases {
): Promise<FileDto> {
const file = await this.fileRepository.findByUuid(fileUuid, user.id);

if (!file) {
if (!file || file?.status != FileStatus.EXISTS) {
throw new NotFoundException(`File ${fileUuid} not found`);
}

Expand All @@ -551,7 +553,17 @@ export class FileUseCases {
fileId,
size,
});
await this.network.deleteFile(user, bucket, oldFileId);

const newFile = File.build({ ...file, size, fileId });

await Promise.all([
this.network.deleteFile(user, bucket, oldFileId),
this.usageUsecases.addDailyUsageChangeOnFileSizeChange(
user,
file,
newFile,
),
]);

return {
...file.toJSON(),
Expand Down
19 changes: 14 additions & 5 deletions src/modules/usage/usage.domain.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
export enum UsageType {
Daily = 'daily',
Monthly = 'monthly',
Yearly = 'yearly',
}
export interface UsageAttributes {
id: string;
userId: string;
delta: number;
period: Date;
type: string;
type: UsageType;
createdAt: Date;
updatedAt: Date;
}
Expand All @@ -13,7 +18,7 @@ export class Usage implements UsageAttributes {
userId: string;
delta: number;
period: Date;
type: string;
type: UsageType;
createdAt: Date;
updatedAt: Date;

Expand All @@ -29,7 +34,7 @@ export class Usage implements UsageAttributes {
this.id = id;
this.userId = userId;
this.delta = delta;
this.period = period;
this.period = new Date(period);
this.type = type;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
Expand All @@ -40,11 +45,15 @@ export class Usage implements UsageAttributes {
}

isYearly(): boolean {
return this.type === 'yearly';
return this.type === UsageType.Yearly;
}

isMonthly(): boolean {
return this.type === 'monthly';
return this.type === UsageType.Monthly;
}

isDaily(): boolean {
return this.type === UsageType.Daily;
}

toJSON(): Partial<UsageAttributes> {
Expand Down
18 changes: 18 additions & 0 deletions src/modules/usage/usage.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export class SequelizeUsageRepository {
return usages.map((usage) => this.toDomain(usage));
}

public async create(usage: Omit<Usage, 'id'>) {
const newUsage = await this.usageModel.create(usage);

return this.toDomain(newUsage);
}

public async getMostRecentUsage(userUuid: string): Promise<Usage | null> {
const mostRecentUsage = await this.usageModel.findOne({
where: { userId: userUuid },
Expand All @@ -27,6 +33,18 @@ export class SequelizeUsageRepository {
return mostRecentUsage ? this.toDomain(mostRecentUsage) : null;
}

public async getUsage(
where: Partial<Usage>,
order?: Array<[keyof Usage, 'ASC' | 'DESC']>,
): Promise<Usage | null> {
const mostRecentUsage = await this.usageModel.findOne({
where: { ...where },
order: order,
});

return mostRecentUsage ? this.toDomain(mostRecentUsage) : null;
}

public async addFirstDailyUsage(userUuid: string): Promise<Usage> {
const query = `
INSERT INTO public.usages (id, user_id, delta, period, type, created_at, updated_at)
Expand Down
81 changes: 81 additions & 0 deletions src/modules/usage/usage.usecase.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { Injectable } from '@nestjs/common';
import { SequelizeUsageRepository } from './usage.repository';
import { File } from '../file/file.domain';
import { SequelizeFileRepository } from '../file/file.repository';
import { User } from '../user/user.domain';
import { Usage, UsageType } from './usage.domain';
import { v4 } from 'uuid';
import { Time } from '../../lib/time';

@Injectable()
export class UsageUseCases {
Expand Down Expand Up @@ -38,4 +42,81 @@ export class UsageUseCases {
id: user.email,
};
}

async createDailyUsage(userUuid: User['uuid'], period: Date, delta: number) {
const dailyUsage = Usage.build({
id: v4(),
userId: userUuid,
period,
delta,
type: UsageType.Daily,
createdAt: new Date(),
updatedAt: new Date(),
});

const createdDailyUsage = await this.usageRepository.create(dailyUsage);

return createdDailyUsage;
}

/* async addDailyUsageChangeOnFileSizeChange(
user: User,
oldFileData: File,
newFileData: File,
) {
const mostRecentDailyUsage = await this.usageRepository.getUsage(
{
type: UsageType.Daily,
userId: user.uuid,
},
[['createdAt', 'DESC']],
);
let calculateChangesSince: Date = mostRecentDailyUsage?.createdAt;
const now = new Date();
if (
!calculateChangesSince ||
new Date(calculateChangesSince).toDateString() !== now.toDateString()
) {
calculateChangesSince = new Date(now);
calculateChangesSince.setUTCHours(0, 0, 0, 0);
}
const totalStorageChanged = await this.fileRepository.sumFileSizesSinceDate(
user.id,
calculateChangesSince,
);
if (newFileData.createdAt.toDateString() !== now.toDateString()) {
const delta =
Number(newFileData.size) -
Number(oldFileData.size) +
totalStorageChanged;
return this.createDailyUsage(user.uuid, new Date(), delta);
}
const delta = totalStorageChanged;
console.log({ totalStorageChanged, delta });
return this.createDailyUsage(user.uuid, new Date(), delta);
} */

async addDailyUsageChangeOnFileSizeChange(
user: User,
oldFileData: File,
newFileData: File,
) {
const isFileCreatedToday = Time.isToday(newFileData.createdAt);

if (isFileCreatedToday) {
return;
}

const delta = Number(newFileData.size) - Number(oldFileData.size);

return this.createDailyUsage(user.uuid, new Date(), delta);
}
}

0 comments on commit 0a03f0c

Please sign in to comment.