File size: 3,518 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Inject, Injectable } from '@nestjs/common';
import { AppException } from '../common/exceptions/app.exception.js';
import { APP_CONFIG } from '../config/app-config.js';
import type { AppConfig } from '../config/app-config.interface.js';
import type { Prisma, User, UserRole } from '../generated/prisma/client.js';
import { PrismaService } from '../prisma/prisma.service.js';
import { activeSubscriptionWhere } from '../subscriptions/active-subscription.js';
import { allowanceFor } from './allowance.js';
import type { GenerationCreatedDto } from './dto/generation-created.dto.js';
import type { UsageDto } from './dto/usage.dto.js';
import type { Allowance } from './interfaces/allowance.interface.js';

type Db = Pick<PrismaService['db'], 'subscription' | 'generation'>;

@Injectable()
export class GenerationsService {
  constructor(
    private readonly prisma: PrismaService,
    @Inject(APP_CONFIG) private readonly config: AppConfig,
  ) {}

  async usage(user: Pick<User, 'id' | 'role'>): Promise<UsageDto> {
    const allowance = await this.allowance(this.prisma.db, user.id, user.role);
    return this.toUsage(allowance, await this.used(this.prisma.db, user.id, allowance));
  }

  /**
   * Records a job the renderer is about to accept, against the user's allowance.
   * The user row lock serializes concurrent jobs, so the limit can't be passed.
   */
  async create(userId: string, jobId: string): Promise<GenerationCreatedDto> {
    return this.prisma.db.$transaction(async (tx) => {
      const [user] = await tx.$queryRaw<{ role: UserRole }[]>`
        SELECT role FROM users WHERE id = ${userId}::uuid AND deleted_at IS NULL FOR UPDATE`;
      if (!user) throw new AppException(403, 'FORBIDDEN', 'This account cannot create visualizations.');
      const allowance = await this.allowance(tx, userId, user.role);
      const used = await this.used(tx, userId, allowance);
      if (allowance.limit !== null && used >= allowance.limit) throw limitReached(allowance);
      const generation = await tx.generation.create({ data: { userId, jobId } });
      return { generationId: generation.id, usage: this.toUsage(allowance, used + 1) };
    });
  }

  /** Gives the try back after a failed job. Repeating it changes nothing. */
  async refund(generationId: string): Promise<void> {
    await this.prisma.db.generation.updateMany({
      where: { id: generationId, refundedAt: null },
      data: { refundedAt: new Date() },
    });
  }

  private async allowance(db: Db, userId: string, role: UserRole): Promise<Allowance> {
    const subscription = await db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } });
    return allowanceFor(role, subscription, this.config);
  }

  private used(db: Db, userId: string, allowance: Allowance): Promise<number> {
    const where: Prisma.GenerationWhereInput = { userId, refundedAt: null };
    if (allowance.countFrom) where.createdAt = { gte: allowance.countFrom };
    return db.generation.count({ where });
  }

  private toUsage({ plan, limit, renewsAt }: Allowance, used: number): UsageDto {
    return { plan, limit, used, remaining: limit === null ? null : Math.max(0, limit - used), renewsAt };
  }
}

const limitReached = (allowance: Allowance) =>
  allowance.plan === 'free'
    ? new AppException(402, 'NO_FREE_TRIES', "You've used all your free visualizations.")
    : new AppException(402, 'PLAN_LIMIT_REACHED', "You've used this month's visualizations. They renew with your plan.");