Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: reserve data export filenames while writes are pending

Afloat3695658084c1
diff --git a/server/data/tools.test.ts b/server/data/tools.test.ts
index fc7a3b2d73..59efab3ee4 100644
--- a/server/data/tools.test.ts
+++ b/server/data/tools.test.ts
@@ -659,6 +659,86 @@ describe("data_show", () => {
});
describe("data_export", () => {
+ it.each(["png", "svg"] as const)("keeps both concurrent %s exports instead of overwriting one", async (format) => {
+ const { ctx } = context();
+ await showCard(ctx, { kind: "chart", sql: "SELECT a FROM t", chart: { type: "pie", x: "a" }, title: "Share" });
+ const entered = deferred();
+ const finish = deferred();
+ let count = 0;
+ const render = async () => {
+ const n = ++count;
+ if (n === 2) entered.resolve();
+ await finish.promise;
+ return `image ${n}`;
+ };
+ ctx.renderer = { svg: render, png: async () => Buffer.from(await render()) };
+ const first = exportData(ctx, { id: "c_1", format });
+ const second = exportData(ctx, { id: "c_1", format });
+ await entered.promise;
+ finish.resolve();
+ const [a, b] = await Promise.all([first, second]);
+ expect(readFileSync(a.path, "utf8")).toBe("image 1");
+ expect(readFileSync(b.path, "utf8")).toBe("image 2");
+ expect(a.path).not.toBe(b.path);
+ });
+
+ it("reserves distinct CSV destinations before either database copy finishes", async () => {
+ const { ctx, database } = context();
+ const original = database.run.bind(database);
+ const entered = deferred();
+ const finish = deferred();
+ let count = 0;
+ database.run = async (sql, options) => {
+ if (sql.startsWith("COPY ")) {
+ if (++count === 2) entered.resolve();
+ await finish.promise;
+ }
+ return original(sql, options);
+ };
+ const first = exportData(ctx, { sql: "SELECT 1", format: "csv" });
+ const second = exportData(ctx, { sql: "SELECT 2", format: "csv" });
+ await entered.promise;
+ finish.resolve();
+ const [a, b] = await Promise.all([first, second]);
+ expect(a.path).not.toBe(b.path);
+ expect(existsSync(a.path)).toBe(true);
+ expect(existsSync(b.path)).toBe(true);
+ });
+
+ it("recognizes a pending export through another allowed directory alias", async () => {
+ const { ctx, dir } = context();
+ await showCard(ctx, { kind: "chart", sql: "SELECT a FROM t", chart: { type: "pie", x: "a" } });
+ symlinkSync(join(dir, "work"), join(dir, "work-alias"), "junction");
+ ctx.exportRoots = () => [join(dir, "work"), join(dir, "work-alias")];
+ const entered = deferred();
+ const finish = deferred();
+ let count = 0;
+ ctx.renderer.svg = async () => {
+ const n = ++count;
+ if (n === 2) entered.resolve();
+ await finish.promise;
+ return `image ${n}`;
+ };
+ const first = exportData(ctx, { id: "c_1", format: "svg", path: join(dir, "work", "same.svg") });
+ const second = exportData(ctx, { id: "c_1", format: "svg", path: join(dir, "work-alias", "same.svg") });
+ await entered.promise;
+ finish.resolve();
+ const [a, b] = await Promise.all([first, second]);
+ expect(readFileSync(a.path, "utf8")).toBe("image 1");
+ expect(readFileSync(b.path, "utf8")).toBe("image 2");
+ });
+
+ it("releases a destination when rendering fails before creating its file", async () => {
+ const { ctx, dir } = context();
+ await showCard(ctx, { kind: "chart", sql: "SELECT a FROM t", chart: { type: "pie", x: "a" }, title: "Share" });
+ const render = ctx.renderer.png;
+ ctx.renderer.png = async () => { throw new Error("renderer failed"); };
+ await expect(exportData(ctx, { id: "c_1", format: "png" })).rejects.toThrow("renderer failed");
+ ctx.renderer.png = render;
+ const next = await exportData(ctx, { id: "c_1", format: "png" });
+ expect(next.path).toBe(join(dir, "work", "share.png"));
+ });
+
it("writes csv with COPY TO under the first allowed folder and numbers a repeat", async () => {
const { ctx, database, dir } = context();
await showCard(ctx, { kind: "table", sql: "SELECT * FROM orders", title: "Paid orders" });
diff --git a/server/data/tools.ts b/server/data/tools.ts
index d61f3aef19..7b25844cdd 100644
--- a/server/data/tools.ts
+++ b/server/data/tools.ts
@@ -860,6 +860,12 @@ function realIntent(path: string): string {
return join(realpathSync.native(dir), ...rest);
}
+const pendingExportPaths = new Set<string>();
+function exportPathKey(path: string): string {
+ const real = realIntent(path);
+ return process.platform === "win32" ? real.toLowerCase() : real;
+}
+
/** Confined to `roots`: throws invalid_input for a path outside every root. */
export function resolveExportPath(roots: string[], requested: string | undefined, stem: string, ext: string): string {
const allowed = roots.filter((root) => root && isAbsolute(root)).map((root) => resolve(root));
@@ -878,11 +884,24 @@ export function resolveExportPath(roots: string[], requested: string | undefined
throw fail("invalid_input", `${requested ?? target} is outside the folders an export may use.`, { hint: `Export into ${allowed.join(" or ")}.` });
}
let unique = target;
- for (let n = 2; existsSync(unique); n++) unique = join(dirname(target), `${basename(target, extname(target))}-${n}${extname(target)}`);
+ for (let n = 2; existsSync(unique) || pendingExportPaths.has(exportPathKey(unique)); n++) unique = join(dirname(target), `${basename(target, extname(target))}-${n}${extname(target)}`);
mkdirSync(dirname(unique), { recursive: true });
return unique;
}
+async function atExportPath(ctx: DataContext, input: ExportInput, stem: string, write: (path: string) => Promise<ExportOutput>): Promise<ExportOutput> {
+ const path = resolveExportPath(ctx.exportRoots(), input.path, stem, input.format);
+ const key = exportPathKey(path);
+ // Rendering and COPY both await before creating the file; another export must
+ // not choose the same destination in that interval, even through a symlink.
+ pendingExportPaths.add(key);
+ try {
+ return await write(path);
+ } finally {
+ pendingExportPaths.delete(key);
+ }
+}
+
async function chartRows(ctx: DataContext, card: DataCard): Promise<RunResult> {
if (card.kind !== "chart" || !card.vegaLite || !card.result) throw fail("invalid_input", `${card.id} is not a rendered chart card.`, { hint: "png and svg export a chart card; export data as csv, parquet or xlsx." });
return ctx.database.run(`SELECT * FROM ${resultRelation(card.result)} LIMIT ${DATA_LIMITS.chartMaxMarks}`, runOptions(ctx, { maxRows: DATA_LIMITS.chartMaxMarks }));
@@ -903,10 +922,12 @@ export async function exportData(ctx: DataContext, input: ExportInput): Promise<
if (input.id && !card) throw fail("card_not_found", `No card ${input.id} on the sheet.`);
if (input.format === "png" || input.format === "svg") {
if (!card) throw fail("invalid_input", "png and svg render a chart card: pass its id.");
- const path = resolveExportPath(ctx.exportRoots(), input.path, card.title, input.format);
- const image = await renderCard(ctx, card, input.format, { theme: input.theme, width: input.width, scale: input.scale });
- writeFileSync(path, image);
- return { path, bytes: statSync(path).size };
+ const format = input.format;
+ return atExportPath(ctx, input, card.title, async (path) => {
+ const image = await renderCard(ctx, card, format, { theme: input.theme, width: input.width, scale: input.scale });
+ writeFileSync(path, image);
+ return { path, bytes: statSync(path).size };
+ });
}
let relation: string;
let stem: string;
@@ -924,11 +945,12 @@ export async function exportData(ctx: DataContext, input: ExportInput): Promise<
relation = `(${input.sql})`;
stem = "query";
}
- const path = resolveExportPath(ctx.exportRoots(), input.path, stem, input.format);
const format = input.format === "csv" ? "FORMAT csv, HEADER true" : input.format === "xlsx" ? "FORMAT xlsx, HEADER true" : "FORMAT parquet";
- const copied = await ctx.database.run(`COPY (SELECT * FROM ${relation}) TO ${quoteLiteral(path)} (${format})`, runOptions(ctx, { maxRows: 1, extensions: input.format === "xlsx" ? ["excel"] : [] }));
- const count = Number(copied.rows[0]?.[0]);
- return { path, bytes: statSync(path).size, ...(Number.isFinite(count) ? { rowCount: count } : {}) };
+ return atExportPath(ctx, input, stem, async (path) => {
+ const copied = await ctx.database.run(`COPY (SELECT * FROM ${relation}) TO ${quoteLiteral(path)} (${format})`, runOptions(ctx, { maxRows: 1, extensions: input.format === "xlsx" ? ["excel"] : [] }));
+ const count = Number(copied.rows[0]?.[0]);
+ return { path, bytes: statSync(path).size, ...(Number.isFinite(count) ? { rowCount: count } : {}) };
+ });
}
export type DataToolResult = {