Skip to content

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

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

import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger } from '@nestjs/common'
import { Observable } from 'rxjs'
import { observeCloudApiOperation } from './cloud-api-operation'
import { tap } from 'rxjs/operators'
import { AnalyticsService } from '../analytics/services/analytics.service'
import { Request } from 'express'
import { CreateOrganizationDto } from '../organization/dto/create-organization.dto'
import { OrganizationDto } from '../organization/dto/organization.dto'
import { UpdateOrganizationMemberAccessDto } from '../organization/dto/update-organization-member-access.dto'
import { CreateOrganizationRoleDto } from '../organization/dto/create-organization-role.dto'
import { UpdateOrganizationRoleDto } from '../organization/dto/update-organization-role.dto'
import { CreateOrganizationInvitationDto } from '../organization/dto/create-organization-invitation.dto'
import { UpdateOrganizationInvitationDto } from '../organization/dto/update-organization-invitation.dto'
import { CustomHeaders } from '../common/constants/header.constants'
import { CreateVolumeDto } from '../box/dto/create-volume.dto'
import { VolumeDto } from '../box/dto/volume.dto'
import { CreateBoxDto as RestCreateBoxDto } from '../boxlite-rest/dto/create-box.dto'
import { BoxResponseDto } from '../boxlite-rest/dto/box-response.dto'
import { TypedConfigService } from '../config/typed-config.service'
import { UpdateOrganizationDefaultRegionDto } from '../organization/dto/update-organization-default-region.dto'

type RequestWithUser = Request & {
  user?: { userId: string; organizationId: string }
  params: Record<string, string>
}
type CommonCaptureProps = {
  organizationId?: string
  distinctId: string
  durationMs: number
  statusCode: number
  userAgent: string
  error?: string
  source: string
  sdkVersion?: string
}

@Injectable()
export class MetricsInterceptor implements NestInterceptor {
  private readonly version: string
  private readonly logger = new Logger(MetricsInterceptor.name)

  constructor(
    private readonly configService: TypedConfigService,
    private readonly analytics: AnalyticsService,
  ) {
    this.version = this.configService.getOrThrow('version')
  }

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    if (!this.analytics.enabled) {
      return next.handle()
    }

    const request = context.switchToHttp().getRequest()
    const startTime = Date.now()
    observeCloudApiOperation(request, context.switchToHttp().getResponse(), this.analytics, startTime)

    return next.handle().pipe(
      tap({
        next: (response) => {
          // For DELETE requests or empty responses, pass an empty object with statusCode
          const responseObj = response || { statusCode: 204 }
          this.recordMetrics(request, responseObj, startTime).catch((err) => this.logger.error(err))
        },
        error: (error) => {
          this.recordMetrics(
            request,
            { statusCode: error.status || 500 },
            startTime,
            error.message || JSON.stringify(error),
          ).catch((err) => this.logger.error(err))
        },
      }),
    )
  }

  private async recordMetrics(request: RequestWithUser, response: any, startTime: number, error?: string) {
    const durationMs = Date.now() - startTime
    const statusCode = error ? response.statusCode : response.statusCode || (request.method === 'DELETE' ? 204 : 200) // Default to 204 for DELETE requests
    const distinctId = request.user?.userId || 'anonymous'
    const userAgent = request.get('user-agent')
    const source = request.get(CustomHeaders.SOURCE.name)
    const sdkVersion = request.get(CustomHeaders.SDK_VERSION.name)

    const props: CommonCaptureProps = {
      distinctId,
      organizationId: request.user?.organizationId,
      durationMs,
      statusCode,
      userAgent,
      error,
      source: Array.isArray(source) ? source[0] : source,
      sdkVersion,
    }

    switch (request.method) {
      case 'POST':
        switch (request.route.path) {
          case '/api/api-keys':
            this.captureCreateApiKey(props)
            break
          case '/api/v1/boxes':
          case '/api/v1/:prefix/boxes':
            this.captureCreateBox(props, request.body, response)
            break
          case '/api/v1/boxes/:boxId/start':
          case '/api/v1/:prefix/boxes/:boxId/start':
            this.captureStartBox(props, request.params.boxIdOrName || request.params.boxId)
            break
          case '/api/v1/boxes/:boxId/stop':
          case '/api/v1/:prefix/boxes/:boxId/stop':
            this.captureStopBox(
              props,
              request.params.boxIdOrName || request.params.boxId,
              request.query?.force === 'true',
            )
            break
          case '/api/organizations/invitations/:invitationId/accept':
            if (response.organizationId)
              this.captureAcceptInvitation(
                { ...props, organizationId: response.organizationId },
                request.params.invitationId,
              )
            break
          case '/api/organizations':
            this.captureCreateOrganization(props, request.body, response)
            break
          case '/api/organizations/:organizationId/leave':
            this.captureLeaveOrganization(props, request.params.organizationId)
            break
          case '/api/organizations/:organizationId/users/:userId/access':
            this.captureUpdateOrganizationUserAccess(
              props,
              request.params.organizationId,
              request.params.userId,
              request.body,
            )
            break
          case '/api/organizations/:organizationId/roles':
            this.captureCreateOrganizationRole(props, request.params.organizationId, request.body)
            break
          case '/api/organizations/:organizationId/invitations':
            this.captureCreateOrganizationInvitation(props, request.params.organizationId, request.body)
            break
          case '/api/organizations/:organizationId/invitations/:invitationId/cancel':
            this.captureCancelOrganizationInvitation(props, request.params.organizationId, request.params.invitationId)
            break
          case '/api/volumes':
            this.captureCreateVolume(props, request.body, response)
            break
        }
        break
      case 'DELETE':
        switch (request.route.path) {
          case '/api/v1/boxes/:boxId':
          case '/api/v1/:prefix/boxes/:boxId':
            this.captureDeleteBox(props, request.params.boxIdOrName || request.params.boxId)
            break
          case '/api/organizations/:organizationId':
            this.captureDeleteOrganization(props, request.params.organizationId)
            break
          case '/api/organizations/:organizationId/users/:userId':
            this.captureDeleteOrganizationUser(props, request.params.organizationId, request.params.userId)
            break
          case '/api/organizations/:organizationId/roles/:roleId':
            this.captureDeleteOrganizationRole(props, request.params.organizationId, request.params.roleId)
            break
          case '/api/volumes/:volumeId':
            this.captureDeleteVolume(props, request.params.volumeId)
            break
          case '/api/images/:idOrRef':
            this.captureDeleteImage(props, request.params.idOrRef)
            break
        }
        break
      case 'PUT':
        switch (request.route.path) {
          case '/api/v1/boxes/:boxId/network/inbound':
          case '/api/v1/:prefix/boxes/:boxId/network/inbound':
            this.captureUpdateInboundMode(props, request.params.boxId, request.body?.mode)
            break
          case '/api/organizations/:organizationId/roles/:roleId':
            this.captureUpdateOrganizationRole(
              props,
              request.params.organizationId,
              request.params.roleId,
              request.body,
            )
            break
          case '/api/organizations/:organizationId/invitations/:invitationId':
            this.captureUpdateOrganizationInvitation(
              props,
              request.params.organizationId,
              request.params.invitationId,
              request.body,
            )
            break
          case '/api/organizations/:organizationId/experimental-config':
            this.captureUpdateOrganizationExperimentalConfig(props, request.body)
            break
        }
        break
      case 'PATCH':
        switch (request.route.path) {
          case '/api/organizations/:organizationId/default-region':
            this.captureSetOrganizationDefaultRegion(props, request.params.organizationId, request.body)
            break
        }
        break
    }
  }

  private captureCreateApiKey(props: CommonCaptureProps) {
    this.capture('api_api_key_created', props, 'api_api_key_creation_failed')
  }

  private captureCreateBox(props: CommonCaptureProps, request: RestCreateBoxDto, response: BoxResponseDto) {
    const envVarsLength = request.env ? Object.keys(request.env).length : 0

    const records = {
      box_id: response.box_id,
      box_name_request: request.name,
      box_name: response.name,
      box_user_request: request.user,
      box_cpu_request: request.cpus,
      box_cpu: response.cpus,
      box_memory_mb_request: request.memory_mib,
      box_memory_mb: response.memory_mib,
      box_disk_gb_request: request.disk_size_gb,
      box_env_vars_length_request: envVarsLength,
    }

    this.capture('api_box_created', props, 'api_box_creation_failed', records)
  }

  private captureDeleteBox(props: CommonCaptureProps, boxId: string) {
    this.capture('api_box_deleted', props, 'api_box_deletion_failed', {
      box_id: boxId,
    })
  }

  private captureStartBox(props: CommonCaptureProps, boxId: string) {
    this.capture('api_box_started', props, 'api_box_start_failed', {
      box_id: boxId,
    })
  }

  private captureStopBox(props: CommonCaptureProps, boxId: string, force: boolean) {
    this.capture('api_box_stopped', props, 'api_box_stop_failed', {
      box_id: boxId,
      force,
    })
  }

  private captureUpdateInboundMode(props: CommonCaptureProps, boxId: string, mode: string | undefined) {
    this.capture('api_box_inbound_mode_updated', props, 'api_box_inbound_mode_update_failed', {
      box_id: boxId,
      box_inbound_mode: mode,
    })
  }

  private captureAcceptInvitation(props: CommonCaptureProps, invitationId: string) {
    this.capture('api_invitation_accepted', props, 'api_invitation_accept_failed', {
      invitation_id: invitationId,
    })
  }

  private captureCreateOrganization(
    props: CommonCaptureProps,
    request: CreateOrganizationDto,
    response: OrganizationDto,
  ) {
    this.analytics.groupIdentify(
      {
        groupType: 'organization',
        groupKey: response.id,
        properties: {
          name: request.name,
          created_at: response.createdAt,
          is_default_for_authenticated_user: response.isDefaultForAuthenticatedUser,
          environment: this.configService.get('posthog.environment'),
        },
      },
      props.distinctId === 'anonymous' ? [] : [props.distinctId],
    )

    this.capture('api_organization_created', props, 'api_organization_creation_failed', {
      organization_id: response.id,
      organization_name: request.name,
      organization_default_region_id: request.defaultRegionId,
    })
  }

  private captureLeaveOrganization(props: CommonCaptureProps, organizationId: string) {
    this.capture('api_organization_left', props, 'api_organization_leave_failed', {
      organization_id: organizationId,
    })
  }

  private captureSetOrganizationDefaultRegion(
    props: CommonCaptureProps,
    organizationId: string,
    request: UpdateOrganizationDefaultRegionDto,
  ) {
    this.capture('api_organization_default_region_set', props, 'api_organization_default_region_set_failed', {
      organization_id: organizationId,
      organization_default_region_id: request.defaultRegionId,
    })
  }

  private captureDeleteOrganization(props: CommonCaptureProps, organizationId: string) {
    this.capture('api_organization_deleted', props, 'api_organization_deletion_failed', {
      organization_id: organizationId,
    })
  }

  private captureUpdateOrganizationUserAccess(
    props: CommonCaptureProps,
    organizationId: string,
    userId: string,
    request: UpdateOrganizationMemberAccessDto,
  ) {
    this.capture('api_organization_user_access_updated', props, 'api_organization_user_access_update_failed', {
      organization_id: organizationId,
      organization_user_id: userId,
      organization_user_role: request.role,
      organization_user_assigned_role_ids: request.assignedRoleIds,
    })
  }

  private captureDeleteOrganizationUser(props: CommonCaptureProps, organizationId: string, userId: string) {
    this.capture('api_organization_user_deleted', props, 'api_organization_user_deletion_failed', {
      organization_id: organizationId,
      organization_user_id: userId,
    })
  }

  private captureCreateOrganizationRole(
    props: CommonCaptureProps,
    organizationId: string,
    request: CreateOrganizationRoleDto,
  ) {
    this.capture('api_organization_role_created', props, 'api_organization_role_creation_failed', {
      organization_id: organizationId,
      organization_role_name: request.name,
      organization_role_description: request.description,
      organization_role_permissions: request.permissions,
    })
  }

  private captureDeleteOrganizationRole(props: CommonCaptureProps, organizationId: string, roleId: string) {
    this.capture('api_organization_role_deleted', props, 'api_organization_role_deletion_failed', {
      organization_id: organizationId,
      organization_role_id: roleId,
    })
  }

  private captureUpdateOrganizationRole(
    props: CommonCaptureProps,
    organizationId: string,
    roleId: string,
    request: UpdateOrganizationRoleDto,
  ) {
    this.capture('api_organization_role_updated', props, 'api_organization_role_update_failed', {
      organization_id: organizationId,
      organization_role_id: roleId,
      organization_role_name: request.name,
      organization_role_description: request.description,
      organization_role_permissions: request.permissions,
    })
  }

  private captureCreateOrganizationInvitation(
    props: CommonCaptureProps,
    organizationId: string,
    request: CreateOrganizationInvitationDto,
  ) {
    this.capture('api_organization_invitation_created', props, 'api_organization_invitation_creation_failed', {
      organization_id: organizationId,
      organization_invitation_role: request.role,
      organization_invitation_assigned_role_ids: request.assignedRoleIds,
      organization_invitation_expires_at: request.expiresAt,
    })
  }

  private captureUpdateOrganizationInvitation(
    props: CommonCaptureProps,
    organizationId: string,
    invitationId: string,
    request: UpdateOrganizationInvitationDto,
  ) {
    this.capture('api_organization_invitation_updated', props, 'api_organization_invitation_update_failed', {
      organization_id: organizationId,
      organization_invitation_id: invitationId,
      organization_invitation_expires_at: request.expiresAt,
      organization_invitation_role: request.role,
      organization_invitation_assigned_role_ids: request.assignedRoleIds,
    })
  }

  private captureCancelOrganizationInvitation(props: CommonCaptureProps, organizationId: string, invitationId: string) {
    this.capture('api_organization_invitation_canceled', props, 'api_organization_invitation_cancel_failed', {
      organization_id: organizationId,
      organization_invitation_id: invitationId,
    })
  }

  private captureCreateVolume(props: CommonCaptureProps, request: CreateVolumeDto, response: VolumeDto) {
    this.capture('api_volume_created', props, 'api_volume_creation_failed', {
      volume_id: response.id,
      volume_name_request_set: !!request.name,
    })
  }

  private captureDeleteVolume(props: CommonCaptureProps, volumeId: string) {
    this.capture('api_volume_deleted', props, 'api_volume_deletion_failed', {
      volume_id: volumeId,
    })
  }

  private captureDeleteImage(props: CommonCaptureProps, idOrRef: string) {
    this.capture('api_image_deleted', props, 'api_image_deletion_failed', {
      image_id_or_ref: idOrRef,
    })
  }

  private captureUpdateOrganizationExperimentalConfig(
    props: CommonCaptureProps,
    experimentalConfig: Record<string, any> | null,
  ) {
    this.capture(
      'api_organization_experimental_config_updated',
      props,
      'api_organization_experimental_config_update_failed',
      {
        experimental_config_empty: !experimentalConfig,
        experimental_config_otel_set: !!experimentalConfig?.otel,
      },
    )
  }

  private capture(event: string, props: CommonCaptureProps, errorEvent?: string, extraProps?: Record<string, any>) {
    if (props.distinctId === 'anonymous') return
    const users = [props.distinctId]
    if (extraProps?.organization_user_id) users.push(extraProps.organization_user_id)
    const organizations = [props.organizationId, extraProps?.organization_id].filter((id): id is string => !!id)
    if (!organizations.length) return
    this.analytics.capture(
      {
        distinctId: props.distinctId,
        event: props.error ? errorEvent || event : event,
        groups: this.captureCommonGroups(props),
        properties: { ...this.captureCommonProperties(props), ...extraProps },
      },
      { users, organizations },
    )
  }

  private captureCommonProperties(props: CommonCaptureProps) {
    return {
      duration_ms: props.durationMs,
      status_code: props.statusCode,
      user_agent: props.userAgent,
      source: props.source,
      sdk_version: props.sdkVersion,
      boxlite_version: this.version,
    }
  }

  private captureCommonGroups(props: CommonCaptureProps) {
    return props.organizationId ? { organization: props.organizationId } : undefined
  }
}