Skip to content

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

8.7 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, In } from 'typeorm'
import { isFilestoreVolume, Volume } from '../entities/volume.entity'
import { VolumeState } from '../enums/volume-state.enum'
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule'
import { InjectRedis } from '@nestjs-modules/ioredis'
import { Redis } from 'ioredis'
import { RedisLockProvider } from '../common/redis-lock.provider'
import { TypedConfigService } from '../../config/typed-config.service'
import { createVolumeBucketStore, VolumeBucketNotEmptyError, VolumeBucketStore } from '../stores/volume-bucket.store'

import { TrackableJobExecutions } from '../../common/interfaces/trackable-job-executions'
import { TrackJobExecution } from '../../common/decorators/track-job-execution.decorator'
import { setTimeout } from 'timers/promises'
import { LogExecution } from '../../common/decorators/log-execution.decorator'
import { WithInstrumentation } from '../../common/decorators/otel.decorator'

const VOLUME_STATE_LOCK_KEY = 'volume-state-'

@Injectable()
export class VolumeManager
  implements OnModuleInit, TrackableJobExecutions, OnApplicationShutdown, OnApplicationBootstrap
{
  activeJobs = new Set<string>()

  private readonly logger = new Logger(VolumeManager.name)
  private processingVolumes: Set<string> = new Set()
  private skipTestConnection = false
  private bucketStore: VolumeBucketStore | null = null

  constructor(
    @InjectRepository(Volume)
    private readonly volumeRepository: Repository<Volume>,
    private readonly configService: TypedConfigService,
    @InjectRedis() private readonly redis: Redis,
    private readonly redisLockProvider: RedisLockProvider,
    private readonly schedulerRegistry: SchedulerRegistry,
  ) {
    this.skipTestConnection = this.configService.get('skipConnections')
    this.bucketStore = createVolumeBucketStore(this.configService)
  }

  async onModuleInit() {
    if (!this.bucketStore) {
      return
    }

    if (this.skipTestConnection) {
      this.logger.debug('Skipping volume bucket store connection test')
      return
    }

    await this.testConnection()
  }

  onApplicationBootstrap() {
    // The cron runs even without a bucket store: filestore volumes ride the
    // same state machine and have no object storage to connect to, so an API
    // serving filestore-only orgs must still process their pending states.
    this.schedulerRegistry.getCronJob('process-pending-volumes').start()
  }

  async onApplicationShutdown() {
    //  wait for all active jobs to finish
    while (this.activeJobs.size > 0) {
      this.logger.log(`Waiting for ${this.activeJobs.size} active jobs to finish`)
      await setTimeout(1000)
    }
  }

  private async testConnection() {
    try {
      await this.bucketStore.probe()
      this.logger.debug('Successfully connected to the volume bucket store')
    } catch (error) {
      this.logger.error('Failed to connect to the volume bucket store:', error)
      throw error
    }
  }

  @Cron(CronExpression.EVERY_5_SECONDS, { name: 'process-pending-volumes', waitForCompletion: true, disabled: true })
  @TrackJobExecution()
  @LogExecution('process-pending-volumes')
  @WithInstrumentation()
  async processPendingVolumes() {
    try {
      // Lock the entire process
      const lockKey = 'process-pending-volumes'
      if (!(await this.redisLockProvider.lock(lockKey, 30))) {
        return
      }

      const pendingVolumes = (
        await this.volumeRepository.find({
          where: {
            state: In([VolumeState.PENDING_CREATE, VolumeState.PENDING_DELETE]),
          },
        })
      ).filter((volume) => this.bucketStore !== null || isFilestoreVolume(volume))

      await Promise.all(
        pendingVolumes.map(async (volume) => {
          if (this.processingVolumes.has(volume.id)) {
            return
          }

          // Get lock for this specific volume
          const volumeLockKey = `${VOLUME_STATE_LOCK_KEY}${volume.id}`
          const acquired = await this.redisLockProvider.lock(volumeLockKey, 30)
          if (!acquired) {
            return
          }

          try {
            this.processingVolumes.add(volume.id)
            await this.processVolumeState(volume)
          } finally {
            this.processingVolumes.delete(volume.id)
            await this.redisLockProvider.unlock(volumeLockKey)
          }
        }),
      )

      await this.redisLockProvider.unlock(lockKey)
    } catch (error) {
      this.logger.error('Error processing pending volumes:', error)
    }
  }

  private async processVolumeState(volume: Volume): Promise<void> {
    const volumeLockKey = `${VOLUME_STATE_LOCK_KEY}${volume.id}`

    try {
      switch (volume.state) {
        case VolumeState.PENDING_CREATE:
          await this.handlePendingCreate(volume, volumeLockKey)
          break
        case VolumeState.PENDING_DELETE:
          await this.handlePendingDelete(volume, volumeLockKey)
          break
      }
    } catch (error) {
      this.logger.error(`Error processing volume ${volume.id}:`, error)
      await this.volumeRepository.update(volume.id, {
        state: VolumeState.ERROR,
        errorReason: error.message,
      })
    }
  }

  private async handlePendingCreate(volume: Volume, lockKey: string): Promise<void> {
    try {
      // Refresh lock before state change
      await this.redis.setex(lockKey, 30, '1')

      // Update state to CREATING
      await this.volumeRepository.save({
        ...volume,
        state: VolumeState.CREATING,
      })

      // Refresh lock before the object-store operation
      await this.redis.setex(lockKey, 30, '1')

      await this.bucketStore.create(volume.getBucketName(), {
        VolumeId: volume.id,
        OrganizationId: volume.organizationId,
        Environment: this.configService.get('environment'),
      })

      // Refresh lock before final state update
      await this.redis.setex(lockKey, 30, '1')

      // Update volume state to READY
      await this.volumeRepository.save({
        ...volume,
        state: VolumeState.READY,
      })
      this.logger.debug(`Volume ${volume.id} created successfully`)
    } catch (error) {
      this.logger.error(`Error creating volume ${volume.id}:`, error)
      await this.volumeRepository.save({
        ...volume,
        state: VolumeState.ERROR,
        errorReason: error.message,
      })
    }
  }

  private async handlePendingDelete(volume: Volume, lockKey: string): Promise<void> {
    try {
      // Refresh lock before state change
      await this.redis.setex(lockKey, 30, '1')

      // Update state to DELETING
      await this.volumeRepository.save({
        ...volume,
        state: VolumeState.DELETING,
      })

      // Refresh lock before the object-store operation
      await this.redis.setex(lockKey, 30, '1')

      // TODO: real deletion dispatches a runner-side delete — the NFS data
      // directory is only reachable on runner hosts. Until that lands, a
      // filestore volume has no storage operation here: the data directory is
      // left in place for ops cleanup, and only the row lands DELETED below.
      // The landing is shared with the bucket path, including the
      // `name-deleted` rename that frees the name for reuse.
      if (!isFilestoreVolume(volume)) {
        // A bucket that is already gone is absorbed by the store as success.
        try {
          await this.bucketStore.destroy(volume.getBucketName())
        } catch (error) {
          if (error instanceof VolumeBucketNotEmptyError) {
            throw new Error('Volume deletion failed because the bucket is not empty. You may retry deletion.')
          }
          throw error
        }
      }

      // Refresh lock before final state update
      await this.redis.setex(lockKey, 30, '1')

      // Delete any existing volume record with the deleted state and the same name in the same organization
      await this.volumeRepository.delete({
        organizationId: volume.organizationId,
        name: `${volume.name}-deleted`,
        state: VolumeState.DELETED,
      })

      // Update volume state to DELETED and rename
      await this.volumeRepository.save({
        ...volume,
        state: VolumeState.DELETED,
        name: `${volume.name}-deleted`,
      })
      this.logger.debug(`Volume ${volume.id} deleted successfully`)
    } catch (error) {
      this.logger.error(`Error deleting volume ${volume.id}:`, error)
      await this.volumeRepository.save({
        ...volume,
        state: VolumeState.ERROR,
        errorReason: error.message,
      })
    }
  }
}