Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

3.1 KB
Raw Blame
/*
 * Copyright 2026 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import { Injectable, Logger, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../../box/constants/box.constants'
import { isBoxId } from '../../box/utils/box-id.util'
import { BoxUsageDto, BoxUsagePeriodDto } from '../dto/box-usage.dto'
import { BoxUsagePeriodArchive } from '../entities/box-usage-period-archive.entity'
import { FinalizedUsagePeriod, InvalidUsagePeriodError, toUsageEventDto } from '../usage-event'

/** Exported so the integration suite EXPLAINs the query the read runs. */
export const ARCHIVED_PERIODS_SQL = `SELECT "organizationId", "boxId", region, "startAt", "endAt", cpu, gpu, mem, disk
  FROM box_usage_periods_archive
  WHERE "boxId" = $1 AND "organizationId" = $2 ORDER BY "startAt"`

/** Lists one Box's archived usage periods. A period counts once the archive job has moved it. */
@Injectable()
export class BoxUsageService {
  private readonly logger = new Logger(BoxUsageService.name)

  constructor(
    @InjectRepository(BoxUsagePeriodArchive)
    private readonly archiveRepository: Repository<BoxUsagePeriodArchive>,
  ) {}

  async getUsage(boxId: string, organizationId: string): Promise<BoxUsageDto> {
    if (!isBoxId(boxId) || organizationId === BOX_WARM_POOL_UNASSIGNED_ORGANIZATION) throw this.notFound(boxId)

    const periods: FinalizedUsagePeriod[] = await this.archiveRepository.query(ARCHIVED_PERIODS_SQL, [
      boxId,
      organizationId,
    ])
    // Archived periods outlive the Box row, so the row is only asked when there are none.
    if (periods.length === 0 && !(await this.ownsBox(boxId, organizationId))) throw this.notFound(boxId)

    return { periods: periods.flatMap((period) => this.toDto(period)) }
  }

  /** The period as the usage export sends it to billing; none when it lasted no time or the export would refuse it. */
  private toDto(period: FinalizedUsagePeriod): BoxUsagePeriodDto[] {
    if (!(period.endAt.getTime() > period.startAt.getTime())) return []
    try {
      const event = toUsageEventDto(period)
      return [
        {
          start_at: event.startAt,
          end_at: event.endAt,
          cpu: Number(event.cpu),
          memory_gib: Number(event.mem),
          disk_gib: Number(event.disk),
        },
      ]
    } catch (error) {
      if (!(error instanceof InvalidUsagePeriodError)) throw error
      // The export blocks the same period, so it is never billed either.
      this.logger.warn(`Skipping an unexportable usage period of box ${period.boxId}: ${error.message}`)
      return []
    }
  }

  private async ownsBox(boxId: string, organizationId: string): Promise<boolean> {
    const rows: unknown[] = await this.archiveRepository.query(
      `SELECT 1 FROM box WHERE id = $1 AND "organizationId"::text = $2`,
      [boxId, organizationId],
    )
    return rows.length > 0
  }

  private notFound(boxId: string): NotFoundException {
    return new NotFoundException(`Box with ID ${boxId} not found`)
  }
}