Skip to content

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

2.6 KB
Raw Blame
import { randomUUID } from 'node:crypto'
import { DataSource, type QueryRunner } from 'typeorm'
import { Store } from '../src/cloud-app/engine/db'
import { EncryptionService } from '../src/encryption/encryption.service'
import { AddCloudAppPlatform1793780100000 } from '../src/migrations/pre-deploy/1793780100000-add-cloud-app-platform-migration'
import { AddAppBoxOwnership1794500000000 } from '../src/migrations/pre-deploy/1794500000000-add-app-box-ownership-migration'
import { DropAppBoxPointer1794500001000 } from '../src/migrations/post-deploy/1794500001000-drop-app-box-pointer-migration'

/** One migrated App Hosting schema per suite, including its organization and Box foreign keys. */
export async function createCloudAppStore(organizationId: string = randomUUID(), otherOrganization?: string) {
  const schema = 'cloud_app_' + randomUUID().replaceAll('-', '')
  const source = await new DataSource({
    type: 'postgres',
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT || 5432),
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
  }).initialize()
  const close = async () => {
    try {
      await source.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`)
    } finally {
      await source.destroy()
    }
  }
  try {
    await source.query(`CREATE SCHEMA ${schema}`)
    await source.query(`CREATE TABLE ${schema}.organization (id UUID PRIMARY KEY)`)
    for (const id of [organizationId, otherOrganization].filter(Boolean))
      await source.query(`INSERT INTO ${schema}.organization VALUES ($1)`, [id])
    await source.query(`CREATE TABLE ${schema}.box (id text PRIMARY KEY, "organizationId" uuid)`)
    await new AddCloudAppPlatform1793780100000().up({
      query: (sql: string) =>
        source.query(
          sql
            .replace('CREATE SCHEMA cloud_app;', '')
            .replaceAll('cloud_app.', schema + '.')
            .replaceAll('public.organization', schema + '.organization'),
        ),
    } as QueryRunner)
    const scoped = {
      query: (sql: string) =>
        source.query(sql.replaceAll('cloud_app.', schema + '.').replace(/\bbox\b/g, schema + '.box')),
    } as QueryRunner
    await new AddAppBoxOwnership1794500000000().up(scoped)
    await new DropAppBoxPointer1794500001000().up(scoped)
    const encryption = new EncryptionService({ getOrThrow: () => randomUUID() } as never)
    const store = new Store(source, organizationId, encryption, schema)
    return { store, source, schema, organizationId, encryption, close }
  } catch (error) {
    await close()
    throw error
  }
}