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

feat: add clean suspended workspaces command #9808

Merged
merged 5 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
update after review
  • Loading branch information
etiennejou committed Jan 24, 2025
commit e2cc5675de60d2f00f1085ce2206c906f2490965
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,25 @@ export class BillingWebhookSubscriptionService {
},
);

const billingSubscription =
await this.billingSubscriptionRepository.findOneOrFail({
where: { stripeSubscriptionId: data.object.id },
});
const billingSubscriptions = await this.billingSubscriptionRepository.find({
where: { workspaceId },
});

const updatedBillingSubscription = billingSubscriptions.find(
(subscription) => subscription.stripeSubscriptionId === data.object.id,
);

if (!updatedBillingSubscription) {
throw new Error('Billing subscription not found');
}

const hasActiveSubscription = billingSubscriptions.some(
(subscription) => subscription.status === SubscriptionStatus.Active,
);

await this.billingSubscriptionItemRepository.upsert(
transformStripeSubscriptionEventToDatabaseSubscriptionItem(
billingSubscription.id,
updatedBillingSubscription.id,
data,
),
{
Expand All @@ -79,9 +90,10 @@ export class BillingWebhookSubscriptionService {
);

if (
data.object.status === SubscriptionStatus.Canceled ||
data.object.status === SubscriptionStatus.Unpaid ||
data.object.status === SubscriptionStatus.Paused
(data.object.status === SubscriptionStatus.Canceled ||
data.object.status === SubscriptionStatus.Unpaid ||
data.object.status === SubscriptionStatus.Paused) &&
!hasActiveSubscription
) {
await this.workspaceRepository.update(workspaceId, {
activationStatus: WorkspaceActivationStatus.SUSPENDED,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,13 +371,18 @@ export class EnvironmentVariables {
'"WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION" should be strictly lower that "WORKSPACE_INACTIVE_DAYS_BEFORE_DELETION"',
})
@ValidateIf((env) => env.WORKSPACE_INACTIVE_DAYS_BEFORE_DELETION > 0)
WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION = 12;
WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION = 7;

@CastToPositiveNumber()
@IsNumber()
@ValidateIf((env) => env.WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION > 0)
WORKSPACE_INACTIVE_DAYS_BEFORE_DELETION = 14;

@CastToPositiveNumber()
@IsNumber()
@ValidateIf((env) => env.MAX_NUMBER_OF_WORKSPACES_DELETED_PER_EXECUTION > 0)
MAX_NUMBER_OF_WORKSPACES_DELETED_PER_EXECUTION = 5;

@IsEnum(CaptchaDriverType)
@IsOptional()
CAPTCHA_DRIVER?: CaptchaDriverType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.modu
import { EmailSenderJob } from 'src/engine/core-modules/email/email-sender.job';
import { EmailModule } from 'src/engine/core-modules/email/email.module';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { UserVarsModule } from 'src/engine/core-modules/user/user-vars/user-vars.module';
import { UserModule } from 'src/engine/core-modules/user/user.module';
import { HandleWorkspaceMemberDeletedJob } from 'src/engine/core-modules/workspace/handle-workspace-member-deleted.job';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
Expand All @@ -38,6 +39,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
ObjectMetadataModule,
TypeORMModule,
UserModule,
UserVarsModule,
EmailModule,
DataSeedDemoWorkspaceModule,
BillingModule,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import { cleanSuspendedWorkspaceCronPattern } from 'src/engine/workspace-manager
import { CleanSuspendedWorkspacesJob } from 'src/engine/workspace-manager/workspace-cleaner/crons/clean-suspended-workspaces.job';

@Command({
name: 'cron:clean-suspended-workspaces:start',
name: 'cron:clean-suspended-workspaces',
description: 'Starts a cron job to clean suspended workspaces',
})
export class StartCleanSuspendedWorkspacesCronCommand extends CommandRunner {
export class CleanSuspendedWorkspacesCronCommand extends CommandRunner {
constructor(
@InjectMessageQueue(MessageQueue.cronQueue)
private readonly messageQueueService: MessageQueueService,
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,29 @@ import { EnvironmentService } from 'src/engine/core-modules/environment/environm
import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { UserVarsService } from 'src/engine/core-modules/user/user-vars/services/user-vars.service';
import { WorkspaceService } from 'src/engine/core-modules/workspace/services/workspace.service';
import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';

const MILLISECONDS_IN_ONE_DAY = 1000 * 3600 * 24;

export const USER_WORKSPACE_DELETION_WARNING_SENT_KEY =
'USER_WORKSPACE_DELETION_WARNING_SENT';

@Processor(MessageQueue.cronQueue)
export class CleanSuspendedWorkspacesJob {
private readonly logger = new Logger(CleanSuspendedWorkspacesJob.name);
private readonly inactiveDaysBeforeDelete: number;
private readonly inactiveDaysBeforeWarn: number;
private readonly maxNumberOfWorkspacesDeletedPerExecution: number;

constructor(
private readonly workspaceService: WorkspaceService,
private readonly environmentService: EnvironmentService,
private readonly userService: UserService,
private readonly userVarsService: UserVarsService,
@InjectRepository(BillingSubscription, 'core')
private readonly billingSubscriptionRepository: Repository<BillingSubscription>,
@InjectRepository(Workspace, 'core')
Expand All @@ -34,6 +43,9 @@ export class CleanSuspendedWorkspacesJob {
this.inactiveDaysBeforeWarn = this.environmentService.get(
'WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION',
);
this.maxNumberOfWorkspacesDeletedPerExecution = this.environmentService.get(
'MAX_NUMBER_OF_WORKSPACES_DELETED_PER_EXECUTION',
);
}

async computeWorkspaceBillingInactivity(
Expand Down Expand Up @@ -61,21 +73,102 @@ export class CleanSuspendedWorkspacesJob {
}
}

warnWorkspaceMembers(workspace: Workspace) {
// TODO: issue #284
// fetch workspace members
// send email warning for deletion in (this.inactiveDaysBeforeDelete - this.inactiveDaysBeforeWarn) days (cci @twenty.com)
chunkArray<T>(array: T[], chunkSize = 5): T[][] {
const chunkedArray: T[][] = [];
let index = 0;

this.logger.log(
`Warning Workspace ${workspace.id} ${workspace.displayName}`,
while (index < array.length) {
chunkedArray.push(array.slice(index, index + chunkSize));
index += chunkSize;
}

return chunkedArray;
}

async checkIfWorkspaceMembersWarned(
workspaceMembers: WorkspaceMemberWorkspaceEntity[],
workspaceId: string,
) {
for (const workspaceMember of workspaceMembers) {
const workspaceMemberWarned =
(await this.userVarsService.get({
userId: workspaceMember.userId,
workspaceId: workspaceId,
key: USER_WORKSPACE_DELETION_WARNING_SENT_KEY,
})) === true;

if (workspaceMemberWarned) {
return true;
}
}

return false;
}

async warnWorkspaceMembers(workspace: Workspace) {
const workspaceMembers =
await this.userService.loadWorkspaceMembers(workspace);

const workspaceMembersWarned = await this.checkIfWorkspaceMembersWarned(
workspaceMembers,
workspace.id,
);

if (workspaceMembersWarned) {
this.logger.log(
`Workspace ${workspace.id} ${workspace.displayName} already warned`,
);

return;
} else {
const workspaceMembersChunks = this.chunkArray(workspaceMembers);

for (const workspaceMembersChunk of workspaceMembersChunks) {
await Promise.all(
workspaceMembersChunk.map(async (workspaceMember) => {
await this.userVarsService.set({
userId: workspaceMember.userId,
workspaceId: workspace.id,
key: USER_WORKSPACE_DELETION_WARNING_SENT_KEY,
value: true,
});
}),
);
}

// TODO: issue #284
// send email warning for deletion in (this.inactiveDaysBeforeDelete - this.inactiveDaysBeforeWarn) days (cci @twenty.com)

this.logger.log(
`Warning Workspace ${workspace.id} ${workspace.displayName}`,
);

return;
}
}

async informWorkspaceMembersAndDeleteWorkspace(workspace: Workspace) {
// TODO: issue #285
// fetch workspace members
// send email informing about deletion (cci @twenty.com)
// remove clean-inactive-workspace.job.ts and .. files
const workspaceMembers =
await this.userService.loadWorkspaceMembers(workspace);

const workspaceMembersChunks = this.chunkArray(workspaceMembers);

for (const workspaceMembersChunk of workspaceMembersChunks) {
await Promise.all(
workspaceMembersChunk.map(async (workspaceMember) => {
await this.userVarsService.delete({
userId: workspaceMember.userId,
workspaceId: workspace.id,
key: USER_WORKSPACE_DELETION_WARNING_SENT_KEY,
});
}),

// TODO: issue #285
// send email informing about deletion (cci @twenty.com)
// remove clean-inactive-workspace.job.ts and .. files
// add new env var in infra
);
}

await this.workspaceService.deleteWorkspace(workspace.id);
this.logger.log(
Expand All @@ -91,21 +184,39 @@ export class CleanSuspendedWorkspacesJob {
where: { activationStatus: WorkspaceActivationStatus.SUSPENDED },
});

await Promise.all(
suspendedWorkspaces.map(async (workspace) => {
const workspaceInactivity =
await this.computeWorkspaceBillingInactivity(workspace);

if (
workspaceInactivity &&
workspaceInactivity > this.inactiveDaysBeforeDelete
) {
await this.informWorkspaceMembersAndDeleteWorkspace(workspace);
} else if (workspaceInactivity === this.inactiveDaysBeforeWarn) {
this.warnWorkspaceMembers(workspace);
}
}),
);
const suspendedWorkspacesChunks = this.chunkArray(suspendedWorkspaces);

let deletedWorkspacesCount = 0;

for (const suspendedWorkspacesChunk of suspendedWorkspacesChunks) {
await Promise.all(
suspendedWorkspacesChunk.map(async (workspace) => {
const workspaceInactivity =
await this.computeWorkspaceBillingInactivity(workspace);

if (
workspaceInactivity &&
workspaceInactivity > this.inactiveDaysBeforeDelete &&
deletedWorkspacesCount <=
this.maxNumberOfWorkspacesDeletedPerExecution
) {
await this.informWorkspaceMembersAndDeleteWorkspace(workspace);
deletedWorkspacesCount++;

return;
}
if (
workspaceInactivity &&
workspaceInactivity > this.inactiveDaysBeforeWarn &&
workspaceInactivity <= this.inactiveDaysBeforeDelete
) {
await this.warnWorkspaceMembers(workspace);

return;
}
}),
);
}

this.logger.log(`Job done!`);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import { Workspace } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';
import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-source.module';
import { CleanInactiveWorkspacesCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/clean-inactive-workspaces.command';
import { CleanSuspendedWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/clean-suspended-workspaces.cron.command';
import { DeleteWorkspacesCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/delete-workspaces.command';
import { StartCleanInactiveWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/start-clean-inactive-workspaces.cron.command';
import { StartCleanSuspendedWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/start-clean-suspended-workspaces.cron.command';
import { StopCleanInactiveWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/stop-clean-inactive-workspaces.cron.command';
import { StopCleanSuspendedWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/stop-clean-suspended-workspaces.cron.command';

@Module({
imports: [
Expand All @@ -22,8 +21,7 @@ import { StopCleanSuspendedWorkspacesCronCommand } from 'src/engine/workspace-ma
CleanInactiveWorkspacesCommand,
StartCleanInactiveWorkspacesCronCommand,
StopCleanInactiveWorkspacesCronCommand,
StartCleanSuspendedWorkspacesCronCommand,
StopCleanSuspendedWorkspacesCronCommand,
CleanSuspendedWorkspacesCronCommand,
],
})
export class WorkspaceCleanerModule {}