Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions web/src/lib/__tests__/jar-upload.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest'
import { fileSha256, MAX_JAR_BYTES } from '../jar-upload'

describe('MAX_JAR_BYTES', () => {
it('caps a single upload at 100MB', () => {
expect(MAX_JAR_BYTES).toBe(100 * 1024 * 1024)
})
})

describe('fileSha256', () => {
it('hashes an empty file', async () => {
const file = new File([], 'empty.jar')
expect(await fileSha256(file)).toBe('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
})

it('hashes bytes into lowercase hex', async () => {
const file = new File([new TextEncoder().encode('abc')], 'a.jar')
expect(await fileSha256(file)).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')
})
})
242 changes: 242 additions & 0 deletions web/src/lib/__tests__/sparkJobSubmitUpload.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
// @vitest-environment jsdom

import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import SparkJobSubmitPage from '../../pages/SparkJobSubmit'
import { jarsApi, livyApi } from '../api'
import { fileSha256, putToUploadUrl } from '../jar-upload'

const mockNavigate = vi.fn()
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom')
return { ...actual, useNavigate: () => mockNavigate }
})

vi.mock('../api', async () => {
const actual = await vi.importActual('../api')
return {
...actual,
livyApi: { listBatches: vi.fn(), submitBatch: vi.fn() },
jarsApi: { listUploads: vi.fn(), createUpload: vi.fn(), completeUpload: vi.fn(), signUpload: vi.fn() },
}
})

vi.mock('../jar-upload', () => ({
MAX_JAR_BYTES: 100,
fileSha256: vi.fn(),
putToUploadUrl: vi.fn(),
}))

const renderSubmit = () =>
render(
<MemoryRouter initialEntries={['/datasources/db-1/spark-jobs/new']}>
<Routes>
<Route path="/datasources/:id/spark-jobs/new" element={<SparkJobSubmitPage />} />
</Routes>
</MemoryRouter>
)

const future = () => Math.floor(Date.now() / 1000) + 3600

beforeEach(() => {
vi.clearAllMocks()
mockNavigate.mockReset()
vi.mocked(livyApi.listBatches).mockResolvedValue({ results: [] })
vi.mocked(livyApi.submitBatch).mockResolvedValue({
id: '2',
batch_id: 2,
file: 'x',
class_name: null,
created_at: 0,
state: 'starting',
appId: null,
})
vi.mocked(jarsApi.listUploads).mockResolvedValue({ results: [] })
vi.mocked(fileSha256).mockResolvedValue('a'.repeat(64))
vi.mocked(putToUploadUrl).mockResolvedValue(undefined)
})

afterEach(() => {
cleanup()
})

describe('SparkJobSubmitPage upload source', () => {
it('reuses a recent upload and signs it at submit time', async () => {
vi.mocked(jarsApi.listUploads).mockResolvedValue({
results: [{ id: 'u1', filename: 'app.jar', size_bytes: 123, expires_at: future(), created_at: 1700000000 }],
})
vi.mocked(jarsApi.signUpload).mockResolvedValue({
download_url: 'https://r2.example/signed-get',
expires_at: future(),
})

renderSubmit()
await waitFor(() => expect(livyApi.listBatches).toHaveBeenCalledWith('db-1'))

fireEvent.click(screen.getByRole('button', { name: 'Upload' }))
await waitFor(() => expect(jarsApi.listUploads).toHaveBeenCalled())
fireEvent.click(await screen.findByRole('button', { name: /app\.jar/ }))
fireEvent.click(screen.getByRole('button', { name: 'Submit Job' }))

await waitFor(() => expect(jarsApi.signUpload).toHaveBeenCalledWith('u1'))
await waitFor(() =>
expect(livyApi.submitBatch).toHaveBeenCalledWith(
'db-1',
expect.objectContaining({ file: 'https://r2.example/signed-get' })
)
)
})

it('skips the transfer when the backend reuses the same hash', async () => {
vi.mocked(jarsApi.createUpload).mockResolvedValue({
reused: true,
record: { id: 'u2', filename: 'app.jar', size_bytes: 3, sha256: 'a'.repeat(64), expires_at: future() },
})
vi.mocked(jarsApi.signUpload).mockResolvedValue({
download_url: 'https://r2.example/signed-get',
expires_at: future(),
})

renderSubmit()
await waitFor(() => expect(livyApi.listBatches).toHaveBeenCalledWith('db-1'))

fireEvent.click(screen.getByRole('button', { name: 'Upload' }))
const input = screen.getByLabelText('Choose file') as HTMLInputElement
fireEvent.change(input, { target: { files: [new File(['abc'], 'app.jar')] } })

await waitFor(() =>
expect(jarsApi.createUpload).toHaveBeenCalledWith({
filename: 'app.jar',
size: 3,
sha256: 'a'.repeat(64),
})
)
expect(putToUploadUrl).not.toHaveBeenCalled()

fireEvent.click(screen.getByRole('button', { name: 'Submit Job' }))
await waitFor(() =>
expect(livyApi.submitBatch).toHaveBeenCalledWith(
'db-1',
expect.objectContaining({ file: 'https://r2.example/signed-get' })
)
)
})

it('blocks files over the size limit before any hashing or upload', async () => {
renderSubmit()
await waitFor(() => expect(livyApi.listBatches).toHaveBeenCalledWith('db-1'))

fireEvent.click(screen.getByRole('button', { name: 'Upload' }))
const input = screen.getByLabelText('Choose file') as HTMLInputElement
fireEvent.change(input, { target: { files: [new File([new Uint8Array(101)], 'big.jar')] } })

expect(await screen.findByText(/100MB limit/)).toBeDefined()
expect(fileSha256).not.toHaveBeenCalled()
expect(jarsApi.createUpload).not.toHaveBeenCalled()
})

it('drops a stale in-flight upload when the user re-picks a file', async () => {
const putResolvers = new Map<string, () => void>()
vi.mocked(jarsApi.createUpload).mockImplementation(async (body) => ({
reused: false,
upload_url: `https://r2.example/${body.filename}`,
key: `uploads/key-${body.filename}`,
}))
vi.mocked(putToUploadUrl).mockImplementation((_url, file) => {
return new Promise<void>((resolve) => {
putResolvers.set(file.name, resolve)
})
})
vi.mocked(jarsApi.completeUpload).mockImplementation(async (body) => ({
id: `id-${body.filename}`,
filename: body.filename,
size_bytes: body.size,
sha256: body.sha256,
expires_at: future(),
}))
vi.mocked(jarsApi.signUpload).mockResolvedValue({
download_url: 'https://r2.example/signed',
expires_at: future(),
})

renderSubmit()
await waitFor(() => expect(livyApi.listBatches).toHaveBeenCalledWith('db-1'))

fireEvent.click(screen.getByRole('button', { name: 'Upload' }))
const input = screen.getByLabelText('Choose file') as HTMLInputElement

fireEvent.change(input, { target: { files: [new File(['1'], 'first.jar')] } })
await waitFor(() => expect(putToUploadUrl).toHaveBeenCalledTimes(1))

fireEvent.change(input, { target: { files: [new File(['2'], 'second.jar')] } })
await waitFor(() => expect(putToUploadUrl).toHaveBeenCalledTimes(2))

// 最新选择(second)先完成上传并登记。
putResolvers.get('second.jar')!()
await waitFor(() => expect(jarsApi.completeUpload).toHaveBeenCalledTimes(1))
expect(jarsApi.completeUpload).toHaveBeenCalledWith(expect.objectContaining({ filename: 'second.jar' }))

// 旧选择(first)此刻才完成 PUT:token 已变,必须丢弃,不得再发 completeUpload 登记。
putResolvers.get('first.jar')!()
await waitFor(() => expect(jarsApi.completeUpload).toHaveBeenCalledTimes(1))

fireEvent.click(screen.getByRole('button', { name: 'Submit Job' }))
await waitFor(() => expect(jarsApi.signUpload).toHaveBeenCalledWith('id-second.jar'))
})

it('a recent-record click supersedes an in-flight upload', async () => {
const putResolvers = new Map<string, () => void>()
vi.mocked(jarsApi.listUploads).mockResolvedValue({
results: [
{ id: 'u-recent', filename: 'recent.jar', size_bytes: 10, expires_at: future(), created_at: 1700000000 },
],
})
vi.mocked(jarsApi.createUpload).mockResolvedValue({
reused: false,
upload_url: 'https://r2.example/inflight.jar',
key: 'uploads/key-inflight.jar',
})
vi.mocked(putToUploadUrl).mockImplementation((_url, file) => {
return new Promise<void>((resolve) => {
putResolvers.set(file.name, resolve)
})
})
vi.mocked(jarsApi.completeUpload).mockResolvedValue({
id: 'id-inflight',
filename: 'inflight.jar',
size_bytes: 1,
sha256: 'a'.repeat(64),
expires_at: future(),
})
vi.mocked(jarsApi.signUpload).mockResolvedValue({
download_url: 'https://r2.example/signed-recent',
expires_at: future(),
})

renderSubmit()
await waitFor(() => expect(livyApi.listBatches).toHaveBeenCalledWith('db-1'))

fireEvent.click(screen.getByRole('button', { name: 'Upload' }))
const input = screen.getByLabelText('Choose file') as HTMLInputElement

fireEvent.change(input, { target: { files: [new File(['x'], 'inflight.jar')] } })
await waitFor(() => expect(putToUploadUrl).toHaveBeenCalledTimes(1))

// 上传进行中,点选最近记录以复用:handleSelectRecent 递增 token,使在途 pick 失效。
fireEvent.click(await screen.findByRole('button', { name: /recent\.jar/ }))

// 在途 PUT 此刻完成:token 已变,必须丢弃,不得再发 completeUpload 登记。
putResolvers.get('inflight.jar')!()
await waitFor(() => expect(jarsApi.completeUpload).not.toHaveBeenCalled())

fireEvent.click(screen.getByRole('button', { name: 'Submit Job' }))
await waitFor(() => expect(jarsApi.signUpload).toHaveBeenCalledWith('u-recent'))
await waitFor(() =>
expect(livyApi.submitBatch).toHaveBeenCalledWith(
'db-1',
expect.objectContaining({ file: 'https://r2.example/signed-recent' })
)
)
})
})
26 changes: 26 additions & 0 deletions web/src/lib/__tests__/time.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { formatTtl } from '../time'

describe('formatTtl', () => {
it('formats Chinese with the largest whole unit', () => {
expect(formatTtl(59, 'zh')).toBe('不足1分钟')
expect(formatTtl(60, 'zh')).toBe('1分钟')
expect(formatTtl(3599, 'zh')).toBe('59分钟')
expect(formatTtl(3600, 'zh')).toBe('1小时')
expect(formatTtl(86399, 'zh')).toBe('23小时')
expect(formatTtl(86400, 'zh')).toBe('1天')
expect(formatTtl(2 * 86400, 'zh')).toBe('2天')
})

it('formats English with the largest whole unit', () => {
expect(formatTtl(59, 'en')).toBe('<1m')
expect(formatTtl(60, 'en')).toBe('1m')
expect(formatTtl(3600, 'en')).toBe('1h')
expect(formatTtl(86400, 'en')).toBe('1d')
})

it('clamps negative input to zero', () => {
expect(formatTtl(-5, 'en')).toBe('<1m')
expect(formatTtl(-5, 'zh')).toBe('不足1分钟')
})
})
27 changes: 27 additions & 0 deletions web/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import type {
DatabaseGrant,
DbKind,
JarRef,
JarUploadCreateResponse,
JarUploadRecord,
JarUploadSummary,
LivyBatch,
LivyBatchLog,
Notebook,
Expand Down Expand Up @@ -620,3 +623,27 @@ export const livyApi = {
{ method: 'DELETE' }
),
}

// ── Spark 作业 jar 本地上传(#58/#66 冻结契约 /api/jars/*) ──────────────────────────
// 账号级(不绑定具体 Spark 数据库)。上传直传 R2 由调用方用 putToUploadUrl 完成,这里只
// 消费预检、登记与现签下载链接三个端点。
export const jarsApi = {
listUploads: () => apiFetch<{ results: JarUploadSummary[] }>('/jars/uploads'),

createUpload: (body: { filename: string; size: number; sha256: string }) =>
apiFetch<JarUploadCreateResponse>('/jars/uploads', {
method: 'POST',
body: JSON.stringify(body),
}),

completeUpload: (body: { key: string; filename: string; size: number; sha256: string }) =>
apiFetch<JarUploadRecord>('/jars/uploads/complete', {
method: 'POST',
body: JSON.stringify(body),
}),

signUpload: (id: string) =>
apiFetch<{ download_url: string; expires_at: number }>(`/jars/uploads/${encodeURIComponent(id)}/sign`, {
method: 'POST',
}),
}
32 changes: 32 additions & 0 deletions web/src/lib/jar-upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// ── Spark 作业 jar 本地上传:浏览器侧直传 R2 的纯逻辑 ──────────────────────────────
// 与 worker 的 /api/jars/* 契约配套:前端先算 SHA-256 做复用预检,未命中则对预签名
// PUT URL 直传(fetch 无上传进度,故用 XMLHttpRequest),完成后由 /uploads/complete 登记。

/** 单文件上限 100MB;前端拦截,文案与后端 413 一致。 */
export const MAX_JAR_BYTES = 100 * 1024 * 1024

/** 计算文件 SHA-256,返回 64 位小写 hex(匹配后端 validateSha256 的 /^[0-9a-f]{64}$/)。 */
export async function fileSha256(file: File): Promise<string> {
const buf = await file.arrayBuffer()
const digest = await crypto.subtle.digest('SHA-256', buf)
return Array.from(new Uint8Array(digest))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}

/** 对预签名 upload_url 发 PUT 直传;onProgress 回传 0-100 整数百分比。 */
export function putToUploadUrl(url: string, file: File, onProgress: (percent: number) => void): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('PUT', url)
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100))
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) resolve()
else reject(new Error(`Upload failed (${xhr.status})`))
}
xhr.onerror = () => reject(new Error('Upload failed'))
xhr.send(file)
})
}
15 changes: 15 additions & 0 deletions web/src/lib/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,18 @@ export function timeAgo(ts: number, locale: Locale): string {
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
return `${Math.floor(diff / 86400)}d ago`
}

// Short remaining time ("6d" / "23h" / "58m" / "<1m") for a countdown in seconds.
export function formatTtl(seconds: number, locale: Locale): string {
const clamped = Math.max(0, seconds)
if (locale === 'zh') {
if (clamped < 60) return '不足1分钟'
if (clamped < 3600) return `${Math.floor(clamped / 60)}分钟`
if (clamped < 86400) return `${Math.floor(clamped / 3600)}小时`
return `${Math.floor(clamped / 86400)}天`
}
if (clamped < 60) return '<1m'
if (clamped < 3600) return `${Math.floor(clamped / 60)}m`
if (clamped < 86400) return `${Math.floor(clamped / 3600)}h`
return `${Math.floor(clamped / 86400)}d`
}
Loading