Skip to content

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

2.4 KB
Raw Blame
import { Readable, Writable } from 'node:stream'
import { text } from 'node:stream/consumers'
import type pg from 'pg'
import { csvHeader, exportCsv, importCsv, MAX_IMPORT_BYTES } from './dbtransfer'

it('preserves multibyte CSV header names split across network buffers', async () => {
  const bytes = Buffer.from('営業,city\n1,Tokyo\n')
  const { columns, stream } = await csvHeader(
    Readable.from([bytes.subarray(0, 2), bytes.subarray(2, 4), bytes.subarray(4)]),
  )
  expect(columns).toEqual(['営業', 'city'])
  expect(await text(stream)).toBe(bytes.toString())
})

it.each([
  { parts: [], columns: [] },
  { parts: ['col1,col2'], columns: ['col1', 'col2'] },
  { parts: ['"a""b","a,', 'c","two\nlines"', '\r\n1,2,3\r\n', '4,5,6\n'], columns: ['a"b', 'a,c', 'two\nlines'] },
])('reads the header and replays every byte for $columns', async ({ parts, columns }) => {
  const result = await csvHeader(Readable.from(parts))
  expect(result.columns).toEqual(columns)
  expect(await text(result.stream)).toBe(parts.join(''))
})

it('aborts a streaming import when the next chunk would exceed the transfer limit', async () => {
  let bytes = 0
  const sink = new Writable({
    write(chunk, _encoding, done) {
      bytes += chunk.length
      done()
    },
  })
  const client = {
    query: jest.fn((sql: unknown) => (typeof sql === 'string' ? Promise.resolve({}) : sink)),
    end: jest.fn(async () => undefined),
  }
  const chunk = Buffer.alloc(1024 * 1024)
  const input = Readable.from(
    (function* () {
      for (let remaining = MAX_IMPORT_BYTES; remaining > 0; remaining -= chunk.length) yield chunk
      yield Buffer.from('!')
    })(),
  )
  await expect(
    importCsv(async () => client as unknown as pg.Client, 'files', ['content'], input),
  ).rejects.toMatchObject({ code: 'invalid_request', message: expect.stringContaining('512 MiB') })
  expect(bytes).toBe(MAX_IMPORT_BYTES)
  expect(client.query).toHaveBeenCalledWith('ROLLBACK')
  expect(client.query).not.toHaveBeenCalledWith('COMMIT')
  expect(client.end).toHaveBeenCalledTimes(1)
})

it('closes the dedicated export connection when the transaction cannot start', async () => {
  const failure = new Error('upstream unavailable')
  const client = { query: jest.fn().mockRejectedValue(failure), end: jest.fn(async () => undefined) }
  await expect(exportCsv(async () => client as unknown as pg.Client, 'orders')).rejects.toBe(failure)
  expect(client.end).toHaveBeenCalledTimes(1)
})