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
9 changes: 9 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ jobs:
KV_NAMESPACE_ID: ${{ secrets.KV_NAMESPACE_ID }}
ALLOW_APP_DB_AS_TARGET: ${{ vars.ALLOW_APP_DB_AS_TARGET }}
LIVY_JARS_DIR: ${{ vars.LIVY_JARS_DIR }}
CRON_SCHEDULE: ${{ vars.CRON_SCHEDULE }}
WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }}
run: node scripts/patch-wrangler.mjs wrangler.toml

- name: Write secrets file
Expand All @@ -58,6 +60,7 @@ jobs:
SETUP_SECRET: ${{ secrets.SETUP_SECRET }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
ENCRYPTION_KEY: ${{ secrets.ENCRYPTION_KEY }}
WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }}
run: |
set -euo pipefail
umask 077
Expand All @@ -76,6 +79,12 @@ jobs:
--arg ENCRYPTION_KEY "${ENCRYPTION_KEY}" \
'{JWT_SECRET: $JWT_SECRET, SETUP_SECRET: $SETUP_SECRET, CLOUDFLARE_API_TOKEN: $CLOUDFLARE_API_TOKEN, ENCRYPTION_KEY: $ENCRYPTION_KEY}' \
> "$RUNNER_TEMP/secrets.json"
# Optional: include only when configured (tech-scheme §7 red line 6 — empty means off).
if [ -n "${WAKER_SIGNING_KEY:-}" ]; then
jq --arg WAKER_SIGNING_KEY "${WAKER_SIGNING_KEY}" \
'. + {WAKER_SIGNING_KEY: $WAKER_SIGNING_KEY}' "$RUNNER_TEMP/secrets.json" > "$RUNNER_TEMP/secrets.json.tmp"
mv "$RUNNER_TEMP/secrets.json.tmp" "$RUNNER_TEMP/secrets.json"
fi
chmod 0600 "$RUNNER_TEMP/secrets.json"

- name: Deploy Worker
Expand Down
2 changes: 2 additions & 0 deletions web/src/lib/translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,7 @@ export const translations: Record<Locale, Record<string, string>> = {
'livy.no_logs': 'No log output available.',
'livy.close_logs': 'Close Log',
'livy.loading': 'Loading…',
'livy.log_truncated': 'Log truncated — showing the tail only.',
},
zh: {
// App
Expand Down Expand Up @@ -1171,6 +1172,7 @@ export const translations: Record<Locale, Record<string, string>> = {
'livy.no_logs': '暂无日志输出。',
'livy.close_logs': '收起日志',
'livy.loading': '加载中…',
'livy.log_truncated': '日志已截断,仅保留尾部。',
},
}

Expand Down
17 changes: 13 additions & 4 deletions web/src/pages/SparkJobs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default function SparkJobsPage() {
const [logLines, setLogLines] = useState<string[]>([])
const [logLoading, setLogLoading] = useState(false)
const [logError, setLogError] = useState('')
const [logTruncated, setLogTruncated] = useState(false)
const [terminatingBatchId, setTerminatingBatchId] = useState<string | number | null>(null)
const [actionError, setActionError] = useState('')
const [sparkUiError, setSparkUiError] = useState('')
Expand Down Expand Up @@ -45,17 +46,20 @@ export default function SparkJobsPage() {
setActiveBatchId(batchId)
setLogLoading(true)
setLogError('')
setLogTruncated(false)
try {
const res = await livyApi.getBatchLog(id, batchId, { size: 100 })
let lines = res.log || []
if (typeof res.total === 'number' && res.total > 100) {
// An archived body (terminal batch) is already the tail, so no second tail fetch is needed.
if (!res.archived && !res.truncated && typeof res.total === 'number' && res.total > 100) {
const tail = await livyApi.getBatchLog(id, batchId, {
from: Math.max(0, res.total - 100),
size: 100,
})
lines = tail.log || []
}
setLogLines(lines)
setLogTruncated(res.truncated === true)
} catch (err) {
setLogError(err instanceof Error ? err.message : t('errors.generic'))
} finally {
Expand Down Expand Up @@ -219,9 +223,14 @@ export default function SparkJobsPage() {
<tr>
<td colSpan={4} className="bg-ink-950 text-ink-100 px-0 py-0">
<div className="flex items-center justify-between px-3 py-1.5 border-b border-ink-800 text-caption">
<span className="font-mono text-micro text-ink-400">
{t('livy.batch_logs')} · #{batchId}
</span>
<div className="flex items-center gap-2">
<span className="font-mono text-micro text-ink-400">
{t('livy.batch_logs')} · #{batchId}
</span>
{logTruncated && (
<span className="badge badge-warning text-micro">{t('livy.log_truncated')}</span>
)}
</div>
<div className="flex items-center gap-2">
<button
type="button"
Expand Down
4 changes: 4 additions & 0 deletions web/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ export interface LivyBatchLog {
size: number
total: number
log: string[]
// True when the body was truncated to the storage cap (only the tail is kept).
truncated?: boolean
// True when served from Zeta's own archive rather than live Livy.
archived?: boolean
}

// A Cloudflare account D1 database as returned by GET /admin/d1/databases
Expand Down
34 changes: 33 additions & 1 deletion worker/scripts/patch-wrangler.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,38 @@ const OPTIONAL_PLACEHOLDERS = [
// JSON string escapes (\" \\ \n \uXXXX ...) are all valid in TOML basic strings.
export const tomlString = (value) => JSON.stringify(value)

// tech-scheme §8 three-state scheduling. The committed wrangler.toml always ships `crons = []`;
// at deploy the schedule is materialised from the CRON_SCHEDULE repo Variable depending on
// WAKER_SIGNING_KEY:
// * signing key unset/empty → official Cron Trigger with the CRON_SCHEDULE entries;
// * signing key 'false' → no scheduling (crons stays []);
// * signing key truthy → waker owns scheduling, crons stays [].
const CRON_LINE_RE = /^(\s*)crons\s*=\s*\[\s*\]\s*$/m

// Mirrors lib/waker.ts normalizeKey(): non-string / trim-empty / `*_PLACEHOLDER` → null
// (unconfigured). The reserved value `false` is kept verbatim and treated as "disabled".
function normalizeWakerSigningKey(raw) {
if (typeof raw !== 'string') return null
const key = raw.trim()
if (key.length === 0) return null
if (key.endsWith('_PLACEHOLDER')) return null
return key
}

export function materializeCrons(toml, env) {
const schedule = (env.CRON_SCHEDULE ?? '').trim()
const signingKey = normalizeWakerSigningKey(env.WAKER_SIGNING_KEY)
const useOfficialCron = signingKey === null && schedule !== ''
const entries = useOfficialCron
? schedule
.split(',')
.map((entry) => entry.trim())
.filter((entry) => entry !== '')
.map(tomlString)
: []
return toml.replace(CRON_LINE_RE, (_match, indent) => `${indent}crons = [${entries.join(', ')}]`)
}

function fillPlaceholder(toml, placeholder, value) {
const quoted = `"${placeholder}"`
const parts = toml.split(quoted)
Expand All @@ -53,7 +85,7 @@ export function patchWrangler(template, env) {
for (const [placeholder, name, fallback] of OPTIONAL_PLACEHOLDERS) {
toml = fillPlaceholder(toml, placeholder, env[name]?.trim() || fallback)
}
return { toml }
return { toml: materializeCrons(toml, env) }
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
Expand Down
36 changes: 36 additions & 0 deletions worker/scripts/patch-wrangler.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,39 @@ describe('LIVY_JARS_DIR injection', () => {
expect(patchWrangler(template, { ...base, LIVY_JARS_DIR: '/team/jars' }).toml).not.toContain('PLACEHOLDER')
})
})

describe('CRON_SCHEDULE / WAKER_SIGNING_KEY materialization', () => {
it('materialises the official Cron Trigger when no signing key is set', () => {
const { toml } = patchWrangler(template, { ...base, CRON_SCHEDULE: '0 0 * * *' })
expect(toml).toContain('crons = ["0 0 * * *"]')
})

it('keeps crons empty when WAKER_SIGNING_KEY is "false" (no scheduling)', () => {
const { toml } = patchWrangler(template, { ...base, CRON_SCHEDULE: '0 0 * * *', WAKER_SIGNING_KEY: 'false' })
expect(toml).toContain('crons = []')
})

it('treats a placeholder signing key as unconfigured (official Cron)', () => {
const { toml } = patchWrangler(template, {
...base,
CRON_SCHEDULE: '0 0 * * *',
WAKER_SIGNING_KEY: 'WAKER_SIGNING_KEY_PLACEHOLDER',
})
expect(toml).toContain('crons = ["0 0 * * *"]')
})

it('keeps crons empty when a signing key is set (waker owns scheduling)', () => {
const { toml } = patchWrangler(template, { ...base, CRON_SCHEDULE: '0 0 * * *', WAKER_SIGNING_KEY: 'secret' })
expect(toml).toContain('crons = []')
})

it('keeps crons empty when CRON_SCHEDULE is unset', () => {
const { toml } = patchWrangler(template, base)
expect(toml).toContain('crons = []')
})

it('supports multiple comma-separated schedules', () => {
const { toml } = patchWrangler(template, { ...base, CRON_SCHEDULE: '0 0 * * *, 30 * * * *' })
expect(toml).toContain('crons = ["0 0 * * *", "30 * * * *"]')
})
})
140 changes: 140 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@ import { bodyLimit } from 'hono/body-limit'
import type { Env, Variables } from './types'
import { securityHeaders } from './middleware/security'
import { resolveAppOrigin } from './lib/app-url'
import { pruneArchivedLogs } from './lib/log-archive'
import {
CALLBACK_HEADERS,
CALLBACK_PATH,
CALLBACK_PROTOCOL_VERSION,
WAKER_CLEANUP_JOB_NAME,
claimWakerExecution,
completeWakerExecution,
releaseWakerExecution,
verifyWakerSignature,
wakerGateState,
wakerSigningKey,
} from './lib/waker'
import auth from './routes/auth'
import profile from './routes/profile'
import databases from './routes/databases'
Expand Down Expand Up @@ -61,6 +74,124 @@ app.route('/api/setup', setup)
app.route('/api/spark-ui', sparkUiApi)
app.route('/api/spark-history', sparkHistoryApi)

// ── Waker callback (periodic log-archive cleanup, frozen contract v2) ──────────

// Error body mirrors the waker platform's own shape: { ok:false, error:{code,message} }.
const wakerErrorBody = (code: string, message: string) => ({ ok: false, error: { code, message } })

// POST /_waker/execute — the platform's callback. Synchronous: await the cleanup to completion and
// only then answer 2xx, so a failure is a 5xx the platform retries under the same executionId.
// Fail-closed per contract: no signing key (or the reserved `false`) → 500 signing_key_missing.
app.post(CALLBACK_PATH, async (c) => {
const rawBody = await c.req.text()

const timestamp = c.req.header(CALLBACK_HEADERS.timestamp) ?? ''
const executionId = c.req.header(CALLBACK_HEADERS.executionId) ?? ''
const jobId = c.req.header(CALLBACK_HEADERS.jobId) ?? ''
const signature = c.req.header(CALLBACK_HEADERS.signature) ?? ''

if (timestamp.length === 0 || executionId.length === 0 || jobId.length === 0 || signature.length === 0) {
return c.json(
wakerErrorBody(
'invalid_request',
'缺少签名头(X-Waker-Timestamp / X-Waker-Execution-Id / X-Waker-Job-Id / X-Waker-Signature)'
),
400
)
}

const secret = wakerSigningKey(c.env)
if (secret === null) {
return c.json(wakerErrorBody('signing_key_missing', '服务端未配置 WAKER_SIGNING_KEY,无法验签'), 500)
}

const verification = await verifyWakerSignature({
secret,
signature,
timestamp,
executionId,
jobId,
body: rawBody,
})
if (!verification.ok) {
const stale = verification.reason === 'stale_timestamp'
return c.json(
wakerErrorBody(
stale ? 'stale_timestamp' : 'invalid_signature',
stale ? '请求时间戳超出允许窗口(可能是重放)' : `签名校验失败(${verification.reason})`
),
401
)
}

let parsed: unknown
try {
parsed = JSON.parse(rawBody)
} catch {
return c.json(wakerErrorBody('invalid_request', '请求体不是合法 JSON'), 400)
}
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
return c.json(wakerErrorBody('invalid_request', '请求体必须是 JSON 对象'), 400)
}
const body = parsed as {
protocolVersion?: unknown
executionId?: unknown
jobId?: unknown
jobName?: unknown
scheduledFor?: unknown
}
if (body.protocolVersion !== CALLBACK_PROTOCOL_VERSION) {
return c.json(
wakerErrorBody(
'unsupported_protocol',
`不支持的协议版本:${String(body.protocolVersion)}(期望 ${CALLBACK_PROTOCOL_VERSION})`
),
400
)
}
if (
typeof body.executionId !== 'string' ||
body.executionId.length === 0 ||
typeof body.jobId !== 'string' ||
body.jobId.length === 0 ||
typeof body.jobName !== 'string' ||
body.jobName.length === 0 ||
typeof body.scheduledFor !== 'number'
) {
return c.json(wakerErrorBody('invalid_request', '请求体缺少 executionId / jobId / jobName / scheduledFor'), 400)
}
if (body.executionId !== executionId || body.jobId !== jobId) {
return c.json(wakerErrorBody('invalid_request', '请求体 id 与签名头不一致'), 400)
}
if (body.jobName !== WAKER_CLEANUP_JOB_NAME) {
return c.json(
wakerErrorBody('unknown_job', `未声明的任务名:${body.jobName}(期望 ${WAKER_CLEANUP_JOB_NAME})`),
404
)
}

const claim = await claimWakerExecution(c.env, {
executionId: body.executionId,
jobId: body.jobId,
jobName: body.jobName,
scheduledFor: body.scheduledFor,
})
if (!claim.claimed) {
return c.json({ ...(claim.existing?.response ?? {}), ok: true, duplicate: true })
}

try {
await pruneArchivedLogs(c.env)
const response = { ok: true }
await completeWakerExecution(c.env, body.executionId, response)
return c.json(response)
} catch (error) {
await releaseWakerExecution(c.env, body.executionId)
console.error('waker cleanup failed:', error instanceof Error ? error.message : String(error))
return c.json(wakerErrorBody('job_failed', '任务执行失败,平台将按策略重试'), 500)
}
})

// ── Health check ──────────────────────────────────────────────────────────────

app.get('/api/health', (c) => c.json({ ok: true }))
Expand All @@ -82,6 +213,15 @@ app.all('*', async (c) => {
return new Response(res.body, res) // copy so security headers can be added
})

// Periodic log-archive cleanup (tech-scheme §8 three-state). Only the unconfigured state runs here
// (official Cron Trigger); 'false' skips, and a configured signing key yields to the waker callback
// (POST /_waker/execute).
export async function scheduled(_controller: ScheduledController, env: Env, _ctx: ExecutionContext): Promise<void> {
if (wakerGateState(env) !== 'unconfigured') return
await pruneArchivedLogs(env)
}

export default {
fetch: app.fetch,
scheduled,
} satisfies ExportedHandler<Env>
1 change: 1 addition & 0 deletions worker/src/lib/__tests__/app-db-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ describe('appInternalTables', () => {
'zeta_spark_config_profiles',
'zeta_spark_instance_configs',
'zeta_livy_batches',
'zeta_waker_executions',
// The schema-migration ledger is internal too (ONE-352)
'_zeta_schema_migrations',
].sort()
Expand Down
8 changes: 4 additions & 4 deletions worker/src/lib/__tests__/db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ describe('detectExistingTableFamily', () => {
it('finds a complete family under a custom prefix', async () => {
expect(await detectExistingTableFamily(names(...family('ZETA')))).toEqual({
prefix: 'ZETA_',
tableCount: 15,
tableCount: 16,
})
})

it('finds an unprefixed family (prefix is the empty string)', async () => {
expect(await detectExistingTableFamily(names(...family('')))).toEqual({ prefix: '', tableCount: 15 })
expect(await detectExistingTableFamily(names(...family('')))).toEqual({ prefix: '', tableCount: 16 })
})

it('still detects a family that predates the newest four tables (9 of 15)', async () => {
it('still detects a family that predates the newest four tables (9 of 16)', async () => {
expect(await detectExistingTableFamily(names(...family('kp').slice(0, 9)))).toEqual({
prefix: 'kp_',
tableCount: 9,
Expand All @@ -95,7 +95,7 @@ describe('detectExistingTableFamily', () => {
it('detects the real family even when other projects share the database', async () => {
expect(await detectExistingTableFamily(names('SL_perm', 'eNotify_users', ...family('ZETA')))).toEqual({
prefix: 'ZETA_',
tableCount: 15,
tableCount: 16,
})
})
})
Expand Down
Loading
Loading