Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

12.5 KB
Raw Blame
import { describe, it, expect, afterAll, afterEach, beforeAll } from 'vitest'
import { http, HttpResponse } from 'msw'

import {
  Volume,
  VolumeError,
  VolumeNotFoundError,
  VolumePathNotFoundError,
} from '../../src'
import { VolumeConnectionConfig } from '../../src/volume/client'
import { runtime } from '../../src/utils'
import { apiUrl } from '../setup'
import { setupMockApi } from '../mockApi'

// In-memory store for mock volumes
const volumes = new Map<
  string,
  { volumeID: string; name: string; token: string }
>()

// In-memory store for mock volume file contents, keyed by path
const volumeFiles = new Map<string, string>()

const restHandlers = [
  // POST /volumes - create (returns VolumeAndToken)
  http.post(apiUrl('/volumes'), async ({ request }) => {
    const { name } = (await request.clone().json()) as { name: string }
    const volumeID = crypto.randomUUID()
    const token = `vol-token-${crypto.randomUUID()}`
    volumes.set(volumeID, { volumeID, name, token })
    return HttpResponse.json({ volumeID, name, token }, { status: 201 })
  }),

  // GET /volumes - list (returns Volume[] without tokens)
  http.get(apiUrl('/volumes'), () => {
    const list = Array.from(volumes.values()).map(({ volumeID, name }) => ({
      volumeID,
      name,
    }))
    return HttpResponse.json(list)
  }),

  // GET /volumes/:volumeID - get info (returns VolumeAndToken with token)
  http.get<{ volumeID: string }>(apiUrl('/volumes/:volumeID'), ({ params }) => {
    const vol = volumes.get(params.volumeID)
    if (!vol) {
      return HttpResponse.json(
        { code: 404, message: 'Not found' },
        { status: 404 }
      )
    }
    return HttpResponse.json(vol)
  }),

  // DELETE /volumes/:volumeID - destroy
  http.delete<{ volumeID: string }>(
    apiUrl('/volumes/:volumeID'),
    ({ params }) => {
      const existed = volumes.delete(params.volumeID)
      if (!existed) {
        return HttpResponse.json(
          { code: 404, message: 'Not found' },
          { status: 404 }
        )
      }
      return new HttpResponse(null, { status: 204 })
    }
  ),

  // GET /volumecontent/:volumeID/file - read file content
  http.get(apiUrl('/volumecontent/:volumeID/file'), ({ request }) => {
    const path = new URL(request.url).searchParams.get('path') ?? ''
    const content = volumeFiles.get(path)
    if (content === undefined) {
      return HttpResponse.json(
        { code: 404, message: 'Not found' },
        { status: 404 }
      )
    }
    return new HttpResponse(content.length > 0 ? content : null, {
      status: 200,
      headers: { 'Content-Length': String(content.length) },
    })
  }),
]

const server = setupMockApi(...restHandlers)

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterAll(() => server.close())
afterEach(() => {
  server.resetHandlers()
  volumes.clear()
  volumeFiles.clear()
})

describe('Volume CRUD', () => {
  it('should create a volume', async () => {
    const vol = await Volume.create('test-volume')

    expect(vol).toBeDefined()
    expect(vol.volumeId).toBeDefined()
    expect(vol.name).toBe('test-volume')
    expect(vol.token).toBeDefined()
    expect(vol.token).not.toBe('undefined')
  })

  it('should get volume info', async () => {
    const created = await Volume.create('info-volume')
    const info = await Volume.getInfo(created.volumeId)

    expect(info.volumeId).toBe(created.volumeId)
    expect(info.name).toBe('info-volume')
  })

  it('should list volumes', async () => {
    await Volume.create('vol-a')
    await Volume.create('vol-b')

    const list = await Volume.list()

    expect(list).toHaveLength(2)
    expect(list.map((v) => v.name).sort()).toEqual(['vol-a', 'vol-b'])
  })

  it('should return empty list when no volumes exist', async () => {
    const list = await Volume.list()
    expect(list).toHaveLength(0)
  })

  it('should destroy a volume', async () => {
    const vol = await Volume.create('to-delete')
    const result = await Volume.destroy(vol.volumeId)

    expect(result).toBe(true)

    // Verify it's gone
    const list = await Volume.list()
    expect(list).toHaveLength(0)
  })

  it('should return false when destroying a non-existent volume', async () => {
    const result = await Volume.destroy('non-existent-id')
    expect(result).toBe(false)
  })

  it('should throw VolumeNotFoundError when getting info of non-existent volume', async () => {
    const err = await Volume.getInfo('non-existent-id').catch((err) => err)
    expect(err).toBeInstanceOf(VolumeNotFoundError)
    expect(err).toBeInstanceOf(VolumeError)
  })

  it('should throw VolumeError for a non-2xx response without content', async () => {
    server.use(
      http.post(
        apiUrl('/volumes'),
        () =>
          new HttpResponse(null, {
            status: 500,
            headers: { 'Content-Length': '0' },
          })
      )
    )

    await expect(Volume.create('error-volume')).rejects.toThrow(VolumeError)
  })

  it('should keep the proxy on the instance so content calls reuse it', async () => {
    const proxy = 'http://user:[email protected]:8080'
    const vol = await Volume.create('proxy-volume', { proxy })

    // The proxy is stored on the instance...
    expect(vol.proxy).toBe(proxy)

    // ...and instance methods (which build a VolumeConnectionConfig with no
    // per-call proxy) pick it up rather than falling back to no proxy.
    const config = new VolumeConnectionConfig(vol)
    expect(config.proxy).toBe(proxy)
  })

  it('should let a per-call proxy override the instance proxy', async () => {
    const vol = await Volume.create('proxy-volume', {
      proxy: 'http://127.0.0.1:8080',
    })

    const config = new VolumeConnectionConfig(vol, {
      proxy: 'http://127.0.0.1:9090',
    })
    expect(config.proxy).toBe('http://127.0.0.1:9090')
  })

  it('should keep the httpVersion on the instance so content calls reuse it', async () => {
    const vol = await Volume.create('http1-volume', { httpVersion: '1.1' })
    expect(vol.httpVersion).toBe('1.1')
    expect(new VolumeConnectionConfig(vol).httpVersion).toBe('1.1')
    expect(
      new VolumeConnectionConfig(vol, { httpVersion: '2' }).httpVersion
    ).toBe('2')

    const connected = await Volume.connect(vol.volumeId, { httpVersion: '1.1' })
    expect(connected.httpVersion).toBe('1.1')
  })

  it('should handle full lifecycle: create, get, list, destroy', async () => {
    // Create
    const vol = await Volume.create('lifecycle-vol')
    expect(vol.name).toBe('lifecycle-vol')

    // Get info
    const info = await Volume.getInfo(vol.volumeId)
    expect(info.name).toBe('lifecycle-vol')

    // List - should contain the volume
    const list = await Volume.list()
    expect(list).toHaveLength(1)
    expect(list[0].volumeId).toBe(vol.volumeId)

    // Destroy
    const destroyed = await Volume.destroy(vol.volumeId)
    expect(destroyed).toBe(true)

    // List again - should be empty
    const listAfter = await Volume.list()
    expect(listAfter).toHaveLength(0)
  })
})

describe('Volume BYOC domain', () => {
  const byocDomain = 'cluster.example.com'
  const defaultDomain = process.env.E2B_DOMAIN || 'e2b.app'

  it('uses the domain returned by create for content requests', async () => {
    server.use(
      http.post(apiUrl('/volumes'), async ({ request }) => {
        const { name } = (await request.clone().json()) as { name: string }
        const volumeID = crypto.randomUUID()
        const token = `vol-token-${crypto.randomUUID()}`
        return HttpResponse.json(
          { volumeID, name, token, domain: byocDomain },
          { status: 201 }
        )
      })
    )

    const vol = await Volume.create('byoc-volume')

    // The BYOC domain is stored on the instance and drives the content API
    // destination (https://api.<domain>), replacing the default domain.
    expect(vol.domain).toBe(byocDomain)
    const config = new VolumeConnectionConfig(vol)
    expect(config.domain).toBe(byocDomain)
    expect(config.apiUrl).toBe(`https://api.${byocDomain}`)
  })

  it('falls back to the default domain when create returns no domain', async () => {
    const vol = await Volume.create('default-volume')

    expect(vol.domain).toBe(defaultDomain)
    expect(new VolumeConnectionConfig(vol).domain).toBe(defaultDomain)
  })

  it('propagates the domain through getInfo and connect', async () => {
    const created = await Volume.create('connect-volume')

    server.use(
      http.get<{ volumeID: string }>(
        apiUrl('/volumes/:volumeID'),
        ({ params }) => {
          const vol = volumes.get(params.volumeID)
          if (!vol) {
            return HttpResponse.json(
              { code: 404, message: 'Not found' },
              { status: 404 }
            )
          }
          return HttpResponse.json({ ...vol, domain: byocDomain })
        }
      )
    )

    const info = await Volume.getInfo(created.volumeId)
    expect(info.domain).toBe(byocDomain)

    const connected = await Volume.connect(created.volumeId)
    expect(connected.domain).toBe(byocDomain)
    expect(new VolumeConnectionConfig(connected).domain).toBe(byocDomain)
  })
})

describe('Volume content readFile', () => {
  it('should return content for a non-empty file in every format', async () => {
    volumeFiles.set('hello.txt', 'hello world')
    const vol = await Volume.create('content-volume')

    const text = await vol.readFile('hello.txt')
    expect(text).toBe('hello world')

    const bytes = await vol.readFile('hello.txt', { format: 'bytes' })
    expect(bytes).toBeInstanceOf(Uint8Array)
    expect(new TextDecoder().decode(bytes)).toBe('hello world')

    const blob = await vol.readFile('hello.txt', { format: 'blob' })
    expect(blob).toBeInstanceOf(Blob)
    expect(await blob.text()).toBe('hello world')
  })

  // Skipped on Bun: reading `response.body` of an msw-intercepted fetch via a
  // reader yields an immediately-done stream there (msw/Bun incompatibility),
  // while `.text()`/`.blob()` work. Real (non-mocked) streams work on Bun —
  // covered by the sandbox files.read stream tests.
  it.skipIf(runtime === 'bun')(
    'should return content for a non-empty file as a stream',
    async () => {
      volumeFiles.set('hello.txt', 'hello world')
      const vol = await Volume.create('content-volume')

      const stream = await vol.readFile('hello.txt', { format: 'stream' })
      expect(stream).toBeInstanceOf(ReadableStream)
      expect(await new Response(stream).text()).toBe('hello world')
    }
  )

  it('should return empty values for an empty file in every format', async () => {
    volumeFiles.set('empty.txt', '')
    const vol = await Volume.create('content-volume')

    const text = await vol.readFile('empty.txt')
    expect(text).toBe('')

    const bytes = await vol.readFile('empty.txt', { format: 'bytes' })
    expect(bytes).toBeInstanceOf(Uint8Array)
    expect(bytes.length).toBe(0)

    const blob = await vol.readFile('empty.txt', { format: 'blob' })
    expect(blob).toBeInstanceOf(Blob)
    expect(blob.size).toBe(0)

    const stream = await vol.readFile('empty.txt', { format: 'stream' })
    expect(stream).toBeInstanceOf(ReadableStream)
    expect(await new Response(stream).text()).toBe('')
  })

  it('should throw VolumePathNotFoundError for a missing file', async () => {
    const vol = await Volume.create('content-volume')

    const err = await vol.readFile('missing.txt').catch((err) => err)
    expect(err).toBeInstanceOf(VolumePathNotFoundError)
    expect(err).toBeInstanceOf(VolumeError)
  })

  it('should reject at call time for a missing file with stream format', async () => {
    const vol = await Volume.create('content-volume')

    await expect(
      vol.readFile('missing.txt', { format: 'stream' })
    ).rejects.toThrow(VolumePathNotFoundError)
  })
})

describe('VolumeConnectionConfig request timeout', () => {
  it('should default the request timeout to 60 seconds', async () => {
    const vol = await Volume.create('timeout-volume')

    const config = new VolumeConnectionConfig(vol)
    expect(config.requestTimeoutMs).toBe(60_000)
    expect(config.getSignal()).toBeInstanceOf(AbortSignal)
  })

  it('should let a per-call timeout override the default', async () => {
    const vol = await Volume.create('timeout-volume')

    const config = new VolumeConnectionConfig(vol, { requestTimeoutMs: 1_000 })
    expect(config.requestTimeoutMs).toBe(1_000)
  })

  it('should disable the timeout when requestTimeoutMs is 0', async () => {
    const vol = await Volume.create('timeout-volume')

    const config = new VolumeConnectionConfig(vol, { requestTimeoutMs: 0 })
    expect(config.requestTimeoutMs).toBe(0)
    expect(config.getSignal()).toBeUndefined()
  })
})