Skip to content

An open source alternative to Tableau. Embeddable visual analytic

chore: cache demo datasets in dev

Elwynn Chena28e41304426
diff --git a/package.json b/package.json
index 3bf2ddad..3e944653 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,8 @@
"devDependencies": {},
"scripts": {
"build": "yarn workspace @kanaries/graphic-walker build",
- "deploy": "yarn workspace playground deploy"
+ "deploy": "yarn workspace playground deploy",
+ "sync:datasets": "node scripts/demo-datasets.mjs"
},
"workspaces": {
"packages": [
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.json
index bac19808..70bdaef3 100644
--- a/packages/graphic-walker/package.json
+++ b/packages/graphic-walker/package.json
@@ -4,6 +4,7 @@
"scripts": {
"dev:front_end": "vite --host",
"dev": "npm run dev:front_end",
+ "sync:datasets": "node ../../scripts/demo-datasets.mjs ./public/datasets",
"gen-schema": "node scripts/create-json-schema.js",
"build": "vite build && tspc --build && yarn gen-schema",
"build:app": "vite build --config vite-app.config.ts",
diff --git a/packages/graphic-walker/src/dataSource/config.ts b/packages/graphic-walker/src/dataSource/config.ts
index 7018caf0..f271bc43 100644
--- a/packages/graphic-walker/src/dataSource/config.ts
+++ b/packages/graphic-walker/src/dataSource/config.ts
@@ -13,7 +13,7 @@ export const DemoDataAssets = process.env.NODE_ENV === 'production' ? {
CARS: "/datasets/ds-cars-service.json",
// STUDENTS: "https://chspace.oss-cn-hongkong.aliyuncs.com/datasets/ds-students-service.json",
STUDENTS: "/datasets/ds-students-service.json",
- BTC_GOLD: "/datasets/ds_btc_gold_service.json",
+ BTC_GOLD: "/datasets/ds-btcgold-service.json",
BIKE_SHARING: '/datasets/ds-bikesharing-service.json',
CAR_SALES: '/datasets/ds-carsales-service.json',
COLLAGE: '/datasets/ds-collage-service.json',
@@ -65,4 +65,4 @@ export const PUBLIC_DATA_LIST: IPublicData[] = [
key: "TITANIC",
title: "Titanic"
}
-]
\ No newline at end of file
+]
diff --git a/packages/graphic-walker/vite.config.ts b/packages/graphic-walker/vite.config.ts
index 944197c4..f378638b 100644
--- a/packages/graphic-walker/vite.config.ts
+++ b/packages/graphic-walker/vite.config.ts
@@ -1,12 +1,58 @@
import { defineConfig } from 'vite'
+import fs from 'node:fs/promises';
import path from 'path';
import react from '@vitejs/plugin-react'
import typescript from '@rollup/plugin-typescript'
import { peerDependencies } from './package.json'
+import { DEMO_DATASETS, downloadDemoDataset } from '../../scripts/demo-datasets.mjs';
// @see https://styled-components.com/docs/faqs#marking-styledcomponents-as-external-in-your-package-dependencies
const modulesNotToBundle = Object.keys(peerDependencies).concat(["react-dom/client", "react-dom/server"]);
+const demoDatasetDownloads = new Map<string, Promise<Buffer>>();
+
+function demoDatasetFallbackPlugin() {
+ const datasetDir = path.resolve(__dirname, 'public/datasets');
+
+ return {
+ name: 'demo-dataset-fallback',
+ apply: 'serve' as const,
+ configureServer(server) {
+ server.middlewares.use(async (req, res, next) => {
+ const pathname = new URL(req.url || '/', 'http://localhost').pathname;
+ const filename = path.basename(pathname);
+
+ if (!pathname.startsWith('/datasets/') || !DEMO_DATASETS.includes(filename)) {
+ next();
+ return;
+ }
+
+ try {
+ let buffer = await fs.readFile(path.join(datasetDir, filename)).catch(() => undefined);
+
+ if (!buffer) {
+ let download = demoDatasetDownloads.get(filename);
+
+ if (!download) {
+ download = downloadDemoDataset(filename, datasetDir);
+ demoDatasetDownloads.set(filename, download);
+ }
+
+ buffer = await download;
+ demoDatasetDownloads.delete(filename);
+ server.config.logger.info(`Cached demo dataset: /datasets/${filename}`);
+ }
+
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.end(buffer);
+ } catch (error) {
+ demoDatasetDownloads.delete(filename);
+ next(error);
+ }
+ });
+ },
+ };
+}
// https://vitejs.dev/config/
export default defineConfig({
@@ -14,6 +60,7 @@ export default defineConfig({
port: 2002,
},
plugins: [
+ demoDatasetFallbackPlugin(),
react(),
// @ts-ignore
{
diff --git a/packages/playground/package.json b/packages/playground/package.json
index 94413c64..0ecfad30 100644
--- a/packages/playground/package.json
+++ b/packages/playground/package.json
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite",
+ "sync:datasets": "node ../../scripts/demo-datasets.mjs ./public/datasets",
"build:gw": "yarn workspace @kanaries/graphic-walker build",
"build:db": "yarn workspace @kanaries/duckdb-computation build",
"build": "npm run build:gw && npm run build:db && tsc && cp ../graphic-walker/public/* ./public && vite build",
diff --git a/packages/playground/src/gallery/components/Example.tsx b/packages/playground/src/gallery/components/Example.tsx
index 08121d26..cd8e4eb1 100644
--- a/packages/playground/src/gallery/components/Example.tsx
+++ b/packages/playground/src/gallery/components/Example.tsx
@@ -11,11 +11,13 @@ import { GalleryItemOption } from './GalleryGroup';
import { specDict } from '../resources';
import { IDataSource, useFetch } from '../util';
+const DEMO_DATASET_BASE_URL = import.meta.env.DEV ? '/datasets' : 'https://pub-2422ed4100b443659f588f2382cfc7b1.r2.dev/datasets';
+
function getResourceURL(type: 'datasets' | 'specs', name: string): string {
if (type === 'specs') {
return specDict[name];
} else if (type === 'datasets') {
- return `https://pub-2422ed4100b443659f588f2382cfc7b1.r2.dev/datasets/${name}.json`;
+ return `${DEMO_DATASET_BASE_URL}/${name}.json`;
} else {
throw new Error(`Unknown fetch type: "${type}".`);
}
diff --git a/packages/playground/vite.config.ts b/packages/playground/vite.config.ts
index 12f5b0d2..7544eddd 100644
--- a/packages/playground/vite.config.ts
+++ b/packages/playground/vite.config.ts
@@ -1,9 +1,60 @@
import { defineConfig } from "vite";
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
import react from "@vitejs/plugin-react";
+import { DEMO_DATASETS, downloadDemoDataset } from '../../scripts/demo-datasets.mjs';
+
+const __dirname = fileURLToPath(new URL('.', import.meta.url));
+const demoDatasetDownloads = new Map<string, Promise<Buffer>>();
+
+function demoDatasetFallbackPlugin() {
+ const datasetDir = path.resolve(__dirname, 'public/datasets');
+
+ return {
+ name: 'demo-dataset-fallback',
+ apply: 'serve' as const,
+ configureServer(server) {
+ server.middlewares.use(async (req, res, next) => {
+ const pathname = new URL(req.url || '/', 'http://localhost').pathname;
+ const filename = path.basename(pathname);
+
+ if (!pathname.startsWith('/datasets/') || !DEMO_DATASETS.includes(filename)) {
+ next();
+ return;
+ }
+
+ try {
+ let buffer = await fs.readFile(path.join(datasetDir, filename)).catch(() => undefined);
+
+ if (!buffer) {
+ let download = demoDatasetDownloads.get(filename);
+
+ if (!download) {
+ download = downloadDemoDataset(filename, datasetDir);
+ demoDatasetDownloads.set(filename, download);
+ }
+
+ buffer = await download;
+ demoDatasetDownloads.delete(filename);
+ server.config.logger.info(`Cached demo dataset: /datasets/${filename}`);
+ }
+
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.end(buffer);
+ } catch (error) {
+ demoDatasetDownloads.delete(filename);
+ next(error);
+ }
+ });
+ },
+ };
+}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
+ demoDatasetFallbackPlugin(),
react(),
{
name: "middleware",
diff --git a/scripts/demo-datasets.d.mts b/scripts/demo-datasets.d.mts
new file mode 100644
index 00000000..7a968b3c
--- /dev/null
+++ b/scripts/demo-datasets.d.mts
@@ -0,0 +1,19 @@
+export const DEMO_DATASET_BASE_URL: string;
+
+export const DEMO_DATASETS: string[];
+
+export function getDemoDatasetRemoteUrl(filename: string): string | undefined;
+
+export function downloadDemoDataset(filename: string, outputDir: string): Promise<Buffer>;
+
+export function syncDemoDatasets(
+ outputDir: string,
+ options?: {
+ force?: boolean;
+ }
+): Promise<
+ Array<{
+ filename: string;
+ status: 'exists' | 'downloaded';
+ }>
+>;
diff --git a/scripts/demo-datasets.mjs b/scripts/demo-datasets.mjs
new file mode 100644
index 00000000..a862cbd2
--- /dev/null
+++ b/scripts/demo-datasets.mjs
@@ -0,0 +1,95 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+export const DEMO_DATASET_BASE_URL = 'https://pub-2422ed4100b443659f588f2382cfc7b1.r2.dev/datasets';
+
+export const DEMO_DATASETS = [
+ 'ds-cars-service.json',
+ 'ds-students-service.json',
+ 'ds-btcgold-service.json',
+ 'ds-bikesharing-service.json',
+ 'ds-carsales-service.json',
+ 'ds-collage-service.json',
+ 'ds-titanic-service.json',
+ 'ds-kelper-service.json',
+ 'ds-earthquake-service.json',
+];
+
+export function getDemoDatasetRemoteUrl(filename) {
+ if (!DEMO_DATASETS.includes(filename)) {
+ return undefined;
+ }
+
+ return `${DEMO_DATASET_BASE_URL}/${filename}`;
+}
+
+export async function downloadDemoDataset(filename, outputDir) {
+ const remoteUrl = getDemoDatasetRemoteUrl(filename);
+
+ if (!remoteUrl) {
+ throw new Error(`Unknown demo dataset: ${filename}`);
+ }
+
+ const response = await fetch(remoteUrl);
+
+ if (!response.ok) {
+ throw new Error(`Failed to download ${remoteUrl}: ${response.status} ${response.statusText}`);
+ }
+
+ const buffer = Buffer.from(await response.arrayBuffer());
+ await fs.mkdir(outputDir, { recursive: true });
+ await fs.writeFile(path.join(outputDir, filename), buffer);
+
+ return buffer;
+}
+
+export async function syncDemoDatasets(outputDir, options = {}) {
+ const { force = false } = options;
+ const results = [];
+
+ await fs.mkdir(outputDir, { recursive: true });
+
+ for (const filename of DEMO_DATASETS) {
+ const outputPath = path.join(outputDir, filename);
+
+ if (!force) {
+ try {
+ await fs.access(outputPath);
+ results.push({ filename, status: 'exists' });
+ continue;
+ } catch {
+ // Missing files are downloaded below.
+ }
+ }
+
+ await downloadDemoDataset(filename, outputDir);
+ results.push({ filename, status: 'downloaded' });
+ }
+
+ return results;
+}
+
+async function runCli() {
+ const args = process.argv.slice(2);
+ const outputDirArg = args.find((arg) => !arg.startsWith('--'));
+ const defaultOutputDir = path.resolve(process.cwd(), 'packages/graphic-walker/public/datasets');
+ const outputDir = path.resolve(outputDirArg || defaultOutputDir);
+ const force = args.includes('--force');
+
+ const results = await syncDemoDatasets(outputDir, { force });
+ const downloadedCount = results.filter((item) => item.status === 'downloaded').length;
+ const existingCount = results.filter((item) => item.status === 'exists').length;
+
+ console.log(`Demo datasets ready in ${outputDir}`);
+ console.log(`${downloadedCount} downloaded, ${existingCount} already present.`);
+}
+
+const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href;
+
+if (isDirectRun) {
+ runCli().catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ });
+}