Skip to content

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

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

import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
import { DataSource, EntityManager } from 'typeorm'
import { SecretServerClient } from './secret-server-client'

// The reservation commits before a remote write. Removing it inside the Box insert
// transaction locks it through publication. A rollback makes it claimable again.
export async function reserveBoxSecretTransfer(manager: EntityManager, org: string, box: string) {
  const owner = [org, box]
  await manager.query(
    `INSERT INTO box_secret_cleanup (organization_id, box_id, creating, available_at)
     VALUES ($1, $2, true, now() + interval '10 minutes')`,
    owner,
  )
  return async (transaction: EntityManager) => {
    const [rows] = await transaction.query(
      'DELETE FROM box_secret_cleanup WHERE organization_id=$1 AND box_id=$2 AND creating RETURNING box_id',
      owner,
    )
    if (!rows.length) throw new ServiceUnavailableException('Box secret creation attempt has expired')
  }
}

@Injectable()
export class BoxSecretCleanupService {
  private readonly logger = new Logger(BoxSecretCleanupService.name)
  constructor(
    private readonly db: DataSource,
    private readonly store: SecretServerClient,
  ) {}

  @Cron(CronExpression.EVERY_30_SECONDS, { waitForCompletion: true })
  async deliver(): Promise<void> {
    if (!this.store.enabled) return
    await this.db.transaction(async (manager) => {
      const [task] = await manager.query(
        `SELECT organization_id, box_id, creating FROM box_secret_cleanup
         WHERE available_at <= now() ORDER BY available_at LIMIT 1 FOR UPDATE SKIP LOCKED`,
      )
      if (!task) return
      const owner = [task.organization_id, task.box_id]
      // A successful creator removed its reservation atomically with insertion.
      // Expiring this reservation fences any creator resuming after this claim.
      try {
        await this.store.retireBoxSecrets(task.organization_id, task.box_id)
      } catch {
        await manager.query(
          `UPDATE box_secret_cleanup SET creating=false, attempts=attempts+1,
           available_at=now() + make_interval(secs => LEAST(3600, 5 * (1 << LEAST(attempts,10))))
           WHERE organization_id=$1 AND box_id=$2`,
          owner,
        )
        this.logger.warn(`Secret cleanup pending retry for Box ${task.box_id}`)
        return
      }
      if (!task.creating) {
        await manager.query(
          `UPDATE box SET secrets='[]' WHERE "organizationId"=$1 AND id=$2 AND state='destroyed'`,
          owner,
        )
      }
      await manager.query('DELETE FROM box_secret_cleanup WHERE organization_id=$1 AND box_id=$2', owner)
    })
  }
}