Skip to content

armgit / SOMA

Public Imported from GitHub
0

Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice

Speichern: Absturz bei Datei, die sich beim Packen ändert

Kai-Jungsthoefel9904fc84db27
diff --git a/app/src/main/build.ts b/app/src/main/build.ts
index 0a0bfb0..8e9f1d1 100644
--- a/app/src/main/build.ts
+++ b/app/src/main/build.ts
@@ -39,6 +39,9 @@ export class BuildManager extends EventEmitter {
private installing: string[] | null = null;
private afterInstall = false;
private packageError: string | null = null;
+ /** Speichern packt gerade den Ordner (hold): Builds warten, danach läuft genau einer. */
+ private holds = 0;
+ private afterHold = false;
/**
* Parameter des Modells aus dem letzten Build, der sie kannte (null: noch keiner). Scheitert ein Build, bevor der Code
* seine Parameter anlegt, bleibt die Liste des vorigen stehen (`paramsStale`): Das Panel soll gerade dann bedienbar
@@ -97,6 +100,11 @@ export class BuildManager extends EventEmitter {
this.setStatus({ ...this.status, queued: true });
return;
}
+ if (this.holds) {
+ this.afterHold = true;
+ this.setStatus({ ...this.status, queued: true });
+ return;
+ }
if (this.proc) {
this.rerun = true;
this.setStatus({ ...this.status, queued: true });
@@ -215,6 +223,23 @@ export class BuildManager extends EventEmitter {
});
}
+ /**
+ * Builds zurückhalten, solange das Speichern den Ordner packt: Ein Build schreibt output/ und .soma/ neu, und eine Datei,
+ * die sich beim Packen ändert, macht die ZIP unbrauchbar. Ein laufender Build läuft weiter (vorher whenIdle abwarten).
+ * Gibt die Freigabe zurück, danach baut er nach, falls inzwischen jemand bauen wollte.
+ */
+ hold(): () => void {
+ this.holds++;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ if (--this.holds > 0 || this.disposed || !this.afterHold) return;
+ this.afterHold = false;
+ this.start('change during saving');
+ };
+ }
+
cancel(): void {
this.rerun = false;
if (this.timer) { clearTimeout(this.timer); this.timer = null; }
diff --git a/app/src/main/projects.ts b/app/src/main/projects.ts
index 32abed5..ee79980 100644
--- a/app/src/main/projects.ts
+++ b/app/src/main/projects.ts
@@ -485,11 +485,13 @@ export class ProjectController {
if (c !== 0) return { ok: false, files: [], cancelled: true };
}
const warnings: string[] = [];
+ let release: (() => void) | undefined;
try {
- // Wie beim Speichern: aktuelles Ergebnis, Verlauf gepackt
+ // Wie beim Speichern: aktuelles Ergebnis, Verlauf gepackt, kein Build während des Packens
if (!s.builds.busy && buildIsStale(s.dir)) s.builds.start('before exporting');
await s.builds.whenIdle();
if (s.builds.status.state === 'error') warnings.push('The last build failed. The ZIP contains the last successful version of output/model.step.');
+ release = s.builds.hold();
let dirty = false;
// Im Ordner-Modus geht das Repository des Nutzers nicht mit und wird nicht umgepackt
if (!s.folder && await s.git.isRepo()) {
@@ -502,6 +504,8 @@ export class ProjectController {
return { ok: true, files: [dest], target: dest, ...(warnings.length ? { warnings } : {}) };
} catch (e) {
return { ok: false, files: [], error: `Export failed: ${e instanceof Error ? e.message : String(e)}` };
+ } finally {
+ release?.();
}
}
@@ -537,11 +541,14 @@ export class ProjectController {
renameProject(s.id, path.basename(zipPath, path.extname(zipPath))); // der Modellname folgt dem Dateinamen
}
const warnings: string[] = [];
+ let release: (() => void) | undefined;
try {
// Die Datei soll das aktuelle Ergebnis enthalten: laufenden Build abwarten, veralteten vorher nachholen.
if (!s.builds.busy && buildIsStale(s.dir)) s.builds.start('before saving');
await s.builds.whenIdle();
if (s.builds.status.state === 'error') warnings.push('The last build failed. The file contains the last successful version of output/model.step.');
+ // Ab hier kein neuer Build mehr, bis die Datei geschrieben ist: Er schriebe output/ und .soma/ mitten ins Packen
+ release = s.builds.hold();
stampAppVersion(s.id); // mit welcher Version zuletzt gespeichert (E68), steht so auch im Snapshot
let snapshot: string | null = null;
@@ -563,6 +570,8 @@ export class ProjectController {
return { cancelled: false, zipPath, snapshot, files: r.files, bytes: r.bytes, warnings };
} catch (e) {
return { cancelled: false, error: `Saving failed: ${e instanceof Error ? e.message : String(e)}` };
+ } finally {
+ release?.();
}
}
diff --git a/app/src/main/zip.ts b/app/src/main/zip.ts
index 35aeec6..6049c48 100644
--- a/app/src/main/zip.ts
+++ b/app/src/main/zip.ts
@@ -1,5 +1,6 @@
import fs from 'node:fs';
import path from 'node:path';
+import type { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import yauzl from 'yauzl';
import yazl from 'yazl';
@@ -45,19 +46,41 @@ function collect(root: string, withGit: boolean): string[] {
/** Packt den Projektordner (inklusive .git) atomar in `zipPath`: erst eine .part-Datei, dann umbenennen. */
/** `withGit`: false für einen geöffneten Ordner (Ordner-Modus): Sein Repository gehört dem Nutzer und geht nicht mit. */
export async function saveProjectZip(dir: string, zipPath: string, info: ZipInfo, withGit = true): Promise<{ files: number; bytes: number }> {
+ fs.mkdirSync(path.dirname(zipPath), { recursive: true });
+ // Ändert sich eine Datei beim Packen (Agent, Build, OneDrive), ist sie meist beim zweiten Versuch wieder still
+ try { return await packOnce(dir, zipPath, info, withGit); }
+ catch (e) {
+ if (!(e instanceof FileChangedError)) throw e;
+ console.warn(`[zip] ${e.cause instanceof Error ? e.cause.message : String(e.cause)}, packing again`);
+ return await packOnce(dir, zipPath, info, withGit);
+ }
+}
+
+/** Eine Datei hat sich zwischen Auflisten und Lesen geändert oder ist verschwunden. */
+class FileChangedError extends Error {
+ constructor(cause: unknown) { super('A file of the model changed while it was being saved. Please save again.', { cause }); }
+}
+
+async function packOnce(dir: string, zipPath: string, info: ZipInfo, withGit: boolean): Promise<{ files: number; bytes: number }> {
const files = collect(dir, withGit);
const zip = new yazl.ZipFile();
+ // yazl merkt sich die Größe beim addFile und meldet eine Abweichung beim Lesen als 'error' am ZipFile, nicht am Stream.
+ // Ohne Listener wäre das eine Uncaught Exception im Main-Prozess, und der Stream endete nie (Speichern hinge).
+ let failure: FileChangedError | null = null;
+ zip.on('error', (e: unknown) => { failure ??= new FileChangedError(e); (zip.outputStream as Readable).destroy(failure); });
for (const rel of files) if (rel !== ZIP_INFO_PATH) zip.addFile(path.join(dir, rel), rel, { compress: !STORED.test(rel) });
zip.addBuffer(Buffer.from(JSON.stringify(info, null, 2)), ZIP_INFO_PATH);
zip.end();
const tmp = zipPath + '.part';
- fs.mkdirSync(path.dirname(zipPath), { recursive: true });
+ const out = fs.createWriteStream(tmp);
try {
- await pipeline(zip.outputStream, fs.createWriteStream(tmp));
+ await pipeline(zip.outputStream, out);
fs.renameSync(tmp, zipPath);
} catch (e) {
+ // Unter Windows lässt sich die Datei erst löschen, wenn der Stream sie geschlossen hat
+ if (!out.closed) await new Promise<void>((r) => out.once('close', () => r()));
fs.rmSync(tmp, { force: true });
- throw e;
+ throw failure ?? e;
}
return { files: files.length + 1, bytes: fs.statSync(zipPath).size };
}
diff --git a/app/test/unit.mjs b/app/test/unit.mjs
index df7072e..21cd95b 100644
--- a/app/test/unit.mjs
+++ b/app/test/unit.mjs
@@ -419,6 +419,26 @@ try {
check('ZIP: ohne .soma/results, .soma/anim, .soma/drawings und renders/ (E75, E76), mit Modell', inZip['model.py'] === 'x = 2\n' && inZip['.soma/results/thickness.glb'] === null
&& inZip['.soma/anim/deckel.glb'] === null && inZip['renders/view-iso.png'] === null && inZip['.soma/drawings/Halter.png'] === null, JSON.stringify(inZip));
+ // Eine Datei ändert sich beim Packen (Build, Agent): yazl kennt ihre Größe vom addFile und meldet die Abweichung erst
+ // beim Lesen. Früher eine Uncaught Exception im Main-Prozess, und das Speichern hing. Die große Datei vorn hält das
+ // Packen lange genug auf, dass die kleine sich zwischen Größe und Lesen ändert.
+ const busy = path.join(tmp, 'aenderung');
+ fs.mkdirSync(busy);
+ fs.writeFileSync(path.join(busy, 'a-gross.bin'), Buffer.alloc(40 * 1024 * 1024, 7));
+ fs.writeFileSync(path.join(busy, 'z-log.txt'), 'start\n');
+ const busyZip = path.join(tmp, 'aenderung.soma');
+ const once = setTimeout(() => fs.appendFileSync(path.join(busy, 'z-log.txt'), 'einmal\n'), 15);
+ const r1 = await saveProjectZip(busy, busyZip, { savedAt: '', head: null, id: 'x', name: 'x' }).catch((e) => e);
+ clearTimeout(once);
+ const t1 = r1 instanceof Error ? null : await readZipTexts(busyZip, ['z-log.txt']);
+ check('ZIP: Datei ändert sich einmal beim Packen, der zweite Versuch gelingt', t1?.['z-log.txt'] === 'start\neinmal\n', String(r1?.message ?? JSON.stringify(t1)));
+ fs.rmSync(busyZip, { force: true });
+ const always = setInterval(() => fs.appendFileSync(path.join(busy, 'z-log.txt'), 'immer\n'), 5);
+ const r2 = await saveProjectZip(busy, busyZip, { savedAt: '', head: null, id: 'x', name: 'x' }).catch((e) => e);
+ clearInterval(always);
+ check('ZIP: Datei ändert sich ständig, verständlicher Fehler statt Absturz, keine .part und keine Datei', r2 instanceof Error
+ && /changed while it was being saved/.test(r2.message) && !fs.existsSync(busyZip + '.part') && !fs.existsSync(busyZip), String(r2?.message ?? r2));
+
// Packen vor der ZIP (E75): Verlauf und Hashes bleiben. Unerreichbares geht nicht verloren: der Blob, den addAll oben aus
// dem Index genommen hat (lose), und ein Objekt, das nur in einem älteren Pack liegt (ohne --keep-unreachable weg).
const loose = async () => Number(/^count: (\d+)$/m.exec((await repo.run(['count-objects', '-v'])).out)?.[1] ?? -1);