Skip to content
Open
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
21 changes: 19 additions & 2 deletions ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,25 @@ SQB_UI_BASE=/demo VITE_SQB_DEMO=1 npm run build
node scripts/demo-pages.mjs build demo/recording.json.gz ../website/dist/demo
```

To record it again, run DuckShop under `sqb dev`, click through the pages with the
browser saving a HAR, then ask the server for every read the pages made:
To record it again, with `sqb` and `uv` on PATH:

```sh
node scripts/record-demo-duckshop.mjs
```

It builds a DuckDB copy of DuckShop with the demo's jobs, job group and sensor (`demo/project/`),
runs the nightly group twice on `sqb dev`, opens every page
and records what they read. Ids and dates are renumbered, so only run timings change between two
recordings. To review a re-record, compare it with the last one and put the output in the pull
request:

```sh
git show HEAD:ui/demo/recording.json.gz > /tmp/old.json.gz
node scripts/record-demo.mjs --compare /tmp/old.json.gz demo/recording.json.gz
```

To record from a click-through of your own, run DuckShop under `sqb dev`, click through the pages
with the browser saving a HAR, then ask the server for every read the pages made:

```sh
node scripts/record-demo.mjs demo/recording.json.gz --server http://127.0.0.1:<port> \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
name = "nightly_job_group"
description = "Staging, then intermediate, then the marts"
jobs = ["staging_job", "intermediate_job", "marts_job"]
schedule = { cron = "0 2 * * *", timezone = "Europe/London" }

[dependencies]
wait_for = "job"
on_failure = "partial"
4 changes: 4 additions & 0 deletions ui/demo/project/orchestration/jobs/intermediate_job.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
name = "intermediate_job"
description = "Rebuild the intermediate models"
select = "tag:intermediate sql/models/snapshots"
owner = "Data platform"
4 changes: 4 additions & 0 deletions ui/demo/project/orchestration/jobs/marts_job.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
name = "marts_job"
description = "Rebuild the marts the dashboards read"
select = "tag:marts"
owner = "Analytics"
5 changes: 5 additions & 0 deletions ui/demo/project/orchestration/jobs/staging_job.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name = "staging_job"
description = "Load the shop's sources and rebuild the staging layer"
select = "tag:staging kind:seed"
owner = "Data platform"
schedule = { cron = "0 5 * * *", timezone = "Europe/London" }
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from sqlbuild.orchestration import (
RunEvent,
RunEventKind,
RunRequest,
SensorContext,
run_event,
sensor,
)


@sensor(
description="Rebuild the marts whenever staging finishes on its own",
when=run_event(job="staging_job", kinds=[RunEventKind.SUCCESS]),
minimum_interval_seconds=60,
)
def marts_after_staging_sensor(ctx: SensorContext[RunEvent]):
return RunRequest(job="marts_job")
Binary file modified ui/demo/recording.json.gz
Binary file not shown.
42 changes: 42 additions & 0 deletions ui/scripts/demo-plan.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Opens everything a visitor can open on a plan page of the demo: each section, every "Show more"
// page and each model's diff, and for a job group's plan, each member job's plan. The recorder does
// it so the recording holds those reads, and the demo check does it so a read the recording lacks
// shows up as a broken page.

/** Whatever a finished plan shows first: its sections, or a job group's member jobs. */
export const PLAN_SHOWN = 'button.entry[data-section], [data-testid="group-plan"]';

/** @param {import('@playwright/test').Page} page A plan page whose plan has finished. */
export async function openEveryPlanSection(page) {
const members = page.locator('[data-testid="plan-member"]');
if (!(await members.count())) return openSections(page);
for (let i = 0; i < (await members.count()); i++) {
await members.nth(i).click();
// A member that couldn't be planned says so in place of its sections.
await page.locator('button.entry[data-section], [data-testid="group-plan"] .err').first().waitFor();
await page.waitForLoadState('networkidle');
await openSections(page);
}
}

async function openSections(page) {
const sections = page.locator('button.entry[data-section]');
for (let i = 0; i < (await sections.count()); i++) {
await sections.nth(i).click();
await page.waitForLoadState('networkidle');
// An opened diff's button reads "hide diff", so the first unopened one is always next.
const unopened = page.locator('.plan-row').getByRole('button', { name: 'diff', exact: true });
for (let opened = 0; opened < 100 && (await unopened.count()); opened++) {
await unopened.first().click();
await page.waitForLoadState('networkidle');
}
// Each click shows 50 more rows, so a section of a few thousand stops well before this.
for (let more = 0; more < 200; more++) {
// The button is disabled, reading "Loading…", until the last page it asked for arrives.
await page.waitForFunction(() => !document.querySelector('.show-more[disabled]'));
const button = page.locator('.show-more');
if (!(await button.count()) || (await page.getByText("Couldn't load more rows").count())) break;
await button.first().click();
}
}
}
128 changes: 128 additions & 0 deletions ui/scripts/record-demo-duckshop.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Records the click-through demo from DuckShop on `sqb dev`, in one command:
//
// node scripts/record-demo-duckshop.mjs [demo/recording.json.gz]
//
// Needs `sqb` on PATH (its Python with numpy, for DuckShop's Luhn check) and `uv`. The script writes
// a DuckDB copy of DuckShop with the demo's jobs, job group and sensor (demo/project/), serves it with
// `sqb dev`, runs the nightly group twice, opens every page in a browser and records what the pages
// read with record-demo.mjs.

import { chromium } from '@playwright/test';
import { execFileSync, spawn } from 'node:child_process';
import { cpSync, mkdtempSync, rmSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { openEveryPlanSection } from './demo-plan.mjs';

const ui = join(dirname(fileURLToPath(import.meta.url)), '..');
const out = process.argv[2] ?? join(ui, 'demo/recording.json.gz');
const PROJECT_PATH = '/home/demo/duckshop';
const RUNS = ['01a00000-0000-7000-8000-000000000001', '01a00000-0000-7000-8000-000000000002'];

const work = mkdtempSync(join(tmpdir(), 'sqb-demo-'));
const project = join(work, 'duckshop');
const run = (cmd, args, cwd = ui) => execFileSync(cmd, args, { cwd, stdio: ['ignore', 'inherit', 'inherit'] });

console.log('Writing the DuckDB copy of DuckShop...');
run('uv', ['run', '--script', join(ui, '../benchmarks/duckshop/scripts/duckdb_project.py'), project]);
cpSync(join(ui, 'demo/project'), project, { recursive: true });

const port = await new Promise((resolve) => {
const probe = createServer().listen(0, '127.0.0.1', () => {
const { port } = probe.address();
probe.close(() => resolve(port));
});
});
const server = `http://127.0.0.1:${port}`;
const dev = spawn('sqb', ['dev', '--port', String(port), '--plain'], { cwd: project, stdio: ['ignore', 'pipe', 'pipe'] });
let devLog = '';
dev.stdout.on('data', (d) => (devLog += d));
dev.stderr.on('data', (d) => (devLog += d));
const stop = () => {
dev.kill('SIGINT');
rmSync(work, { recursive: true, force: true });
};

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function api(path, body) {
const response = await fetch(server + path, body && {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-sqb-csrf': 'trusted-proxy', origin: server },
body: JSON.stringify(body)
});
if (!response.ok) throw new Error(`${path} answered ${response.status}: ${await response.text()}`);
return response.json();
}
async function until(what, test, seconds = 600) {
for (let i = 0; i < seconds; i++) {
const value = await test().catch(() => null);
if (value) return value;
await sleep(1000);
}
throw new Error(`Timed out waiting for ${what}.\n${devLog.slice(-4000)}`);
}

try {
const location = await until('sqb dev', async () => (await api('/api/control/bootstrap')).access.locations[0]);
const base = `/api/control/locations/${location.location_id}/targets/${location.target}`;
async function runGroup(runId, expected) {
await api('/api/control/runs', { run_id: runId, location_id: location.location_id, target: location.target, job_key: 'nightly_job_group', priority: 0, reason: 'Started from the web UI' });
const status = await until(`run ${runId}`, async () => {
const found = (await api(`${base}/runs?limit=100`)).find((r) => r.run_id === runId);
return found && found.ended_at ? found.status : null;
});
if (status !== expected) throw new Error(`The nightly group ended ${status}, not ${expected}.\n${devLog.slice(-4000)}`);
}

console.log('Running the nightly group...');
await runGroup(RUNS[0], 'success');

console.log('Running the nightly group again...');
await runGroup(RUNS[1], 'success');

console.log('Opening every page...');
const har = join(work, 'session.har');
const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {});
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, recordHar: { path: har } });
const page = await context.newPage();
const jobs = (await api(`${base}/jobs`)).map((j) => `jobs/${j.job_key}`);
const triggers = (await api(`${base}/triggers`)).map((t) => `triggers/${t.trigger_id}`);
const runs = (await api(`${base}/runs?limit=100`)).map((r) => `runs/${r.run_id}`);
const nodes = ['stg_orders', 'int_orders_enriched', 'fct_orders', 'dim_customers'].map((n) => `catalog/${n}`);
const plans = ['sqb build', 'sqb build --select fct_orders+', 'sqb build --select tag:marts', ...jobs.map((j) => `sqb build --select job:${j.slice(5)}`)];
const pages = [
'', 'lineage', 'lineage?node=model:fct_orders', 'catalog', ...nodes, 'checks', 'changes', 'runs', ...runs, 'jobs', ...jobs,
'triggers', ...triggers, 'locations', 'connections', 'providers', 'maintenance', 'cost', 'status', 'settings',
'admin/people', 'admin/roles', 'admin/audit', ...plans.map((cmd) => `plan?cmd=${encodeURIComponent(cmd)}`)
];
// A plan is ready once its summary has an outcome; leaving sooner records half a plan.
const planned = () =>
page.waitForResponse(async (response) => /\/plans\/[^/]+\/summary$/.test(new URL(response.url()).pathname) && !!(await response.json().catch(() => ({}))).outcome, { timeout: 300_000 });
for (const path of pages) {
const plan = path.startsWith('plan?') ? planned() : null;
await page.goto(`${server}/${path}`, { waitUntil: 'networkidle' });
if (plan) {
await plan;
await page.waitForLoadState('networkidle');
await openEveryPlanSection(page);
}
// Each tab reads its own data, so every tab is opened once.
for (const tab of await page.getByRole('tab').all()) {
if (!(await tab.isVisible())) continue;
await tab.click();
await page.waitForLoadState('networkidle');
}
}
// Every check that didn't pass, so the Checks page has them to open.
for (const check of (await api(`${base}/checks`)).filter((c) => c.outcome !== 'pass')) {
await page.goto(`${server}/checks/${check.binding_key}`, { waitUntil: 'networkidle' });
}
await context.close();
await browser.close();

run('node', [join(ui, 'scripts/record-demo.mjs'), out, '--server', server, '--replace', `${project}=${PROJECT_PATH}`, har]);
} finally {
stop();
}
Loading
Loading