Skip to content

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

6.4 KB
Raw Blame
import { createHash } from 'node:crypto'
import { Readable } from 'node:stream'
import {
  S3Client,
  HeadObjectCommand,
  GetObjectCommand,
  PutObjectCommand,
  ListObjectsV2Command,
  DeleteObjectsCommand,
} from '@aws-sdk/client-s3'
import { buffer } from 'node:stream/consumers'
import { Storage } from '@google-cloud/storage'
import { CloudAppSourceStore } from './cloud-app-source-store'
import { TypedConfigService } from '../config/typed-config.service'

jest.mock('@google-cloud/storage', () => ({ Storage: jest.fn() }))

describe('Cloud App shared source storage', () => {
  const settings = { sourceBackend: 'gcs', sourceBucket: 'test-bucket', sourcePrefix: 'cloud-apps' }
  const configuration = {
    get: (name: string) => (name === 'cloudApps' ? settings : name === 's3' ? { region: 'test' } : undefined),
  }
  const objects = new Map<string, Buffer>()
  const save = jest.fn()
  beforeEach(() => {
    objects.clear()
    save.mockReset()
    ;(Storage as unknown as jest.Mock).mockImplementation(() => ({
      bucket: () => ({
        file: (key: string) => ({
          exists: async () => [objects.has(key)],
          save: async (bytes: Buffer) => {
            save(key)
            objects.set(key, bytes)
          },
          createReadStream: () => Readable.from([objects.get(key)!]),
        }),
        deleteFiles: async ({ prefix }: { prefix: string }) => {
          for (const key of objects.keys()) if (key.startsWith(prefix)) objects.delete(key)
        },
      }),
    }))
  })
  const store = () => new CloudAppSourceStore(configuration as unknown as TypedConfigService)

  it('reads source uploaded by another API replica and scopes cleanup to its App', async () => {
    const bytes = Buffer.from('export default "deployed"')
    const sha = createHash('sha256').update(bytes).digest('hex')
    const first = store(),
      second = store()
    await first.put('app_one', sha, Readable.from([bytes]), 1000)
    await first.put('app_two', sha, Readable.from([bytes]), 1000)
    const chunks: Buffer[] = []
    for await (const chunk of second.read('app_one', sha)) chunks.push(chunk)
    expect(Buffer.concat(chunks)).toEqual(bytes)
    await expect(second.put('app_one', sha, Readable.from([bytes]), 1000)).resolves.toEqual({ bytes: 0, deduped: true })
    expect(save).toHaveBeenCalledTimes(2)
    await second.deleteApp('app_one')
    expect(await first.has('app_one', sha)).toBe(false)
    expect(await first.has('app_two', sha)).toBe(true)
  })

  it('does not persist oversized or mismatched source content', async () => {
    const bytes = Buffer.from('unexpected')
    const source = store()
    await expect(source.put('app_one', '0'.repeat(64), Readable.from([bytes]), 1000)).rejects.toThrow('manifest')
    await expect(source.put('app_one', '0'.repeat(64), Readable.from([bytes]), 2)).rejects.toThrow('exceeds')
    expect(save).not.toHaveBeenCalled()
  })
})

describe('S3 App source storage', () => {
  const bucket = 'app-source-test'
  const bytes = Buffer.from('start')
  const sha = createHash('sha256').update(bytes).digest('hex')
  const key = `sources/app_1/${sha}`
  function store(sourceBucket = bucket) {
    return new CloudAppSourceStore({
      get: (name: string) =>
        name === 'cloudApps'
          ? { sourceBackend: 's3', sourceBucket, sourcePrefix: 'sources' }
          : { region: 'test', accessKey: 'test-key', secretKey: 'test-secret' },
    } as unknown as TypedConfigService)
  }
  afterEach(() => jest.restoreAllMocks())

  it('distinguishes missing objects from service failures and transfers bytes with App-scoped keys', async () => {
    const send = jest.spyOn(S3Client.prototype, 'send')
    const client = store()
    send
      .mockImplementationOnce(async () => {
        throw { $metadata: { httpStatusCode: 404 } }
      })
      .mockResolvedValueOnce({} as never)
    expect(await client.put('app_1', sha, Readable.from(['sta', 'rt']), 5)).toEqual({ bytes: 5, deduped: false })
    expect(send.mock.calls[0][0]).toBeInstanceOf(HeadObjectCommand)
    expect(send.mock.calls[1][0]).toBeInstanceOf(PutObjectCommand)
    expect(send.mock.calls[1][0].input).toEqual({ Bucket: bucket, Key: key, Body: bytes })
    send.mockResolvedValueOnce({ Body: Readable.from([bytes]) } as never)
    expect(await buffer(client.read('app_1', sha))).toEqual(bytes)
    expect(send.mock.calls[2][0]).toBeInstanceOf(GetObjectCommand)
    expect(send.mock.calls[2][0].input).toEqual({ Bucket: bucket, Key: key })
    send.mockResolvedValueOnce({} as never)
    await expect(buffer(client.read('app_1', sha))).rejects.toMatchObject({ code: 'not_found' })
    send.mockResolvedValueOnce({} as never)
    expect(await client.has('app_1', sha)).toBe(true)
    const unavailable = new Error('storage unavailable')
    send.mockImplementationOnce(async () => {
      throw unavailable
    })
    await expect(client.has('app_1', sha)).rejects.toBe(unavailable)
  })

  it('follows cleanup continuation tokens and propagates partial delete errors', async () => {
    const send = jest.spyOn(S3Client.prototype, 'send')
    send
      .mockResolvedValueOnce({ Contents: [{ Key: key }], NextContinuationToken: 'next' } as never)
      .mockResolvedValueOnce({} as never)
      .mockResolvedValueOnce({ Contents: [] } as never)
    await store().deleteApp('app_1')
    expect(send.mock.calls.map(([cmd]) => cmd.constructor)).toEqual([
      ListObjectsV2Command,
      DeleteObjectsCommand,
      ListObjectsV2Command,
    ])
    expect(send.mock.calls.map(([cmd]) => cmd.input)).toEqual([
      { Bucket: bucket, Prefix: 'sources/app_1/', ContinuationToken: undefined },
      { Bucket: bucket, Delete: { Objects: [{ Key: key }] } },
      { Bucket: bucket, Prefix: 'sources/app_1/', ContinuationToken: 'next' },
    ])
    send
      .mockResolvedValueOnce({ Contents: [{ Key: key }] } as never)
      .mockResolvedValueOnce({ Errors: [{ Key: key, Code: 'AccessDenied' }] } as never)
    await expect(store().deleteApp('app_1')).rejects.toThrow('did not delete every object')
  })

  it('requires a bucket and valid App and object identifiers before contacting storage', async () => {
    const send = jest.spyOn(S3Client.prototype, 'send')
    await expect(store('').has('app_1', sha)).rejects.toMatchObject({ code: 'unavailable' })
    await expect(store().has('invalid app', sha)).rejects.toMatchObject({ code: 'invalid_request' })
    await expect(store().has('app_1', 'missing')).rejects.toMatchObject({ code: 'invalid_request' })
    expect(send).not.toHaveBeenCalled()
  })
})