Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: clean up the Apple Health import temp file and read stream on failure (#5654)

Adam Eivybdaa073fc2ce
diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.js
index 86bb8ff3c4..407a6cd06d 100644
--- a/server/routes/appleHealth.js
+++ b/server/routes/appleHealth.js
@@ -112,9 +112,17 @@ router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {
// If ZIP, extract export.xml to a temp file and collect clinical records
let clinicalJsons = [];
+ // Set once a ZIP is extracted: the private mkdtemp directory holding
+ // export.xml, removed in the finally below whether the import succeeds or not.
+ let extractDir = null;
if (req.file.originalname.endsWith('.zip') || isZip(req.file)) {
- const xmlPath = join(tmpdir(), `apple-health-${Date.now()}.xml`);
+ // mkdtemp, not `apple-health-${Date.now()}.xml`: two imports issued in the
+ // same millisecond would otherwise write into one another's file. One
+ // directory per extraction is also a single recursive remove to clean up
+ // (matching codexAppServer.ensureTextTurnCwd and repoCloner).
+ extractDir = await fs.mkdtemp(join(tmpdir(), 'portos-apple-health-'));
+ const xmlPath = join(extractDir, 'export.xml');
let foundXml = false;
let xmlWriteFinished = false;
// Each clinical-record collect is async (entries stream through an inflate
@@ -190,14 +198,14 @@ router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {
//
// settle(reject) already destroy()'d xmlWriteStream, but createWriteStream
// opens its fd asynchronously and can finish creating xmlPath *after* an
- // early destroy — so unlinking immediately can no-op and leave the temp
- // file behind. Wait for the stream to emit 'close' (the fd is fully
- // opened-and-closed by then) before unlinking.
+ // early destroy — so removing immediately can race and leave a re-created
+ // export.xml (and its directory) behind. Wait for the stream to emit
+ // 'close' (the fd is fully opened-and-closed by then) before removing.
if (xmlWriteStream && !xmlWriteStream.closed) {
await new Promise((res) => xmlWriteStream.once('close', res));
}
await fs.unlink(filePath).catch(() => {});
- await fs.unlink(xmlPath).catch(() => {});
+ await fs.rm(extractDir, { recursive: true, force: true }).catch(() => {});
throw err;
});
@@ -206,7 +214,14 @@ router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {
console.log(`📋 Found ${clinicalJsons.length} clinical record files in ZIP`);
}
- const result = await importAppleHealthXml(filePath, io);
+ // importAppleHealthXml unlinks the XML it was handed on both outcomes; the
+ // extraction directory around it is ours to remove, on both outcomes too.
+ let result;
+ try {
+ result = await importAppleHealthXml(filePath, io);
+ } finally {
+ if (extractDir) await fs.rm(extractDir, { recursive: true, force: true }).catch(() => {});
+ }
// Import clinical records if any were found
let clinicalResult = null;
diff --git a/server/routes/appleHealth.test.js b/server/routes/appleHealth.test.js
new file mode 100644
index 0000000000..96cbf081f6
--- /dev/null
+++ b/server/routes/appleHealth.test.js
@@ -0,0 +1,96 @@
+/**
+ * ZIP-extraction temp-directory contract for POST /api/health/import/xml.
+ *
+ * The extracted export.xml used to be minted as `apple-health-${Date.now()}.xml`
+ * in the shared temp dir, so two imports issued inside the same millisecond
+ * wrote into one another's file — and a failed import left the multi-GB
+ * extraction behind forever (issue #5654).
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import express from 'express';
+import { readdir } from 'fs/promises';
+import { tmpdir } from 'os';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { createZip } from '../lib/zipWriter.js';
+
+const imports = vi.hoisted(() => ({ paths: [], impl: null }));
+vi.mock('../services/appleHealthXml.js', () => ({
+ importAppleHealthXml: vi.fn(async (filePath) => {
+ imports.paths.push(filePath);
+ if (imports.impl) return imports.impl(filePath);
+ return { days: 1, records: 2 };
+ }),
+}));
+vi.mock('../services/appleHealthClinical.js', () => ({
+ importClinicalRecords: vi.fn(async () => ({ imported: 0 })),
+}));
+
+const { default: appleHealthRoutes } = await import('./appleHealth.js');
+
+const XML = '<?xml version="1.0"?><HealthData><Record type="HKQuantityTypeIdentifierStepCount" unit="count" startDate="2025-01-15 08:00:00 -0800" value="120"/></HealthData>';
+
+const buildApp = () => {
+ const app = express();
+ app.use('/api/health', appleHealthRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const multipart = (boundary, bytes, fileName = 'export.zip') => Buffer.concat([
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${fileName}"\r\nContent-Type: application/zip\r\n\r\n`),
+ bytes,
+ Buffer.from(`\r\n--${boundary}--\r\n`),
+]);
+
+const postZip = (entries) => request(buildApp())
+ .post('/api/health/import/xml')
+ .set('content-type', 'multipart/form-data; boundary=----portoshealth')
+ .send(multipart('----portoshealth', createZip(entries)));
+
+const extractDirs = async () =>
+ (await readdir(tmpdir())).filter((n) => n.startsWith('portos-apple-health-'));
+
+describe('POST /api/health/import/xml — ZIP extraction temp dir', () => {
+ let preexisting;
+
+ beforeEach(async () => {
+ imports.paths = [];
+ imports.impl = null;
+ preexisting = new Set(await extractDirs());
+ });
+
+ afterEach(async () => {
+ const leaked = (await extractDirs()).filter((n) => !preexisting.has(n));
+ expect(leaked).toEqual([]);
+ });
+
+ it('gives back-to-back imports distinct extraction directories and cleans both up', async () => {
+ const entries = [{ name: 'apple_health_export/export.xml', data: XML }];
+
+ const [a, b] = await Promise.all([postZip(entries), postZip(entries)]);
+
+ expect(a.status).toBe(200);
+ expect(b.status).toBe(200);
+ expect(imports.paths).toHaveLength(2);
+ expect(imports.paths[0]).not.toBe(imports.paths[1]);
+ for (const p of imports.paths) expect(p).toMatch(/portos-apple-health-[^/\\]+[/\\]export\.xml$/);
+ });
+
+ it('removes the extraction directory when the import itself fails', async () => {
+ imports.impl = () => { throw new Error('parse exploded'); };
+
+ const res = await postZip([{ name: 'export.xml', data: XML }]);
+
+ expect(res.status).toBe(500);
+ // afterEach asserts nothing was left behind.
+ });
+
+ it('removes the extraction directory when the ZIP has no export.xml', async () => {
+ const res = await postZip([{ name: 'apple_health_export/other.txt', data: 'nope' }]);
+
+ expect(res.status).toBe(400);
+ expect(imports.paths).toHaveLength(0);
+ });
+});
diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.js
index c592839de8..07cb17f65e 100644
--- a/server/services/appleHealthXml.js
+++ b/server/services/appleHealthXml.js
@@ -7,7 +7,7 @@
*/
import { createReadStream } from 'fs';
-import { unlink } from 'fs';
+import { unlink } from 'fs/promises';
import { extractDateStr, readDayFile, writeDayFile } from './appleHealthIngest.js';
import { createAppleHealthRecordStream } from './appleHealthXmlParser.js';
@@ -266,57 +266,64 @@ export async function importAppleHealthXml(filePath, io = null) {
const inputStream = createReadStream(filePath);
- await new Promise((resolve, reject) => {
- const parser = createAppleHealthRecordStream({
- onRecord: (node) => {
- const normalized = normalizeXmlRecord(node);
- if (!normalized) return;
-
- const { metricName, dateStr, dataPoint } = normalized;
-
- if (!dayBuckets[dateStr]) dayBuckets[dateStr] = {};
- if (!dayBuckets[dateStr][metricName]) dayBuckets[dateStr][metricName] = [];
- dayBuckets[dateStr][metricName].push(dataPoint);
- allDays.add(dateStr);
-
- processedRecords++;
-
- if (processedRecords % 10000 === 0) {
- io?.emit('health:xml:progress', { processed: processedRecords });
- console.log(`🍎 XML import progress: ${processedRecords} records`);
- }
-
- // Batch flush to prevent OOM — pause input stream, flush to disk, resume
- if (processedRecords - lastFlush >= FLUSH_INTERVAL && !flushing) {
- flushing = true;
- lastFlush = processedRecords;
- inputStream.pause();
- flushDayBuckets(dayBuckets).then(() => {
- console.log(`🍎 Flushed batch at ${processedRecords} records (${allDays.size} days total)`);
- flushing = false;
- inputStream.resume();
- }).catch(reject);
- }
- },
+ try {
+ await new Promise((resolve, reject) => {
+ const parser = createAppleHealthRecordStream({
+ onRecord: (node) => {
+ const normalized = normalizeXmlRecord(node);
+ if (!normalized) return;
+
+ const { metricName, dateStr, dataPoint } = normalized;
+
+ if (!dayBuckets[dateStr]) dayBuckets[dateStr] = {};
+ if (!dayBuckets[dateStr][metricName]) dayBuckets[dateStr][metricName] = [];
+ dayBuckets[dateStr][metricName].push(dataPoint);
+ allDays.add(dateStr);
+
+ processedRecords++;
+
+ if (processedRecords % 10000 === 0) {
+ io?.emit('health:xml:progress', { processed: processedRecords });
+ console.log(`🍎 XML import progress: ${processedRecords} records`);
+ }
+
+ // Batch flush to prevent OOM — pause input stream, flush to disk, resume
+ if (processedRecords - lastFlush >= FLUSH_INTERVAL && !flushing) {
+ flushing = true;
+ lastFlush = processedRecords;
+ inputStream.pause();
+ flushDayBuckets(dayBuckets).then(() => {
+ console.log(`🍎 Flushed batch at ${processedRecords} records (${allDays.size} days total)`);
+ flushing = false;
+ inputStream.resume();
+ }).catch(reject);
+ }
+ },
+ });
+
+ // Malformed records can't throw here — records missing required attributes
+ // are dropped by normalizeXmlRecord, so minor XML malformations are skipped
+ // rather than fatal (matching the prior sax error-skip behavior).
+ parser.on('finish', resolve);
+ parser.on('error', reject);
+
+ inputStream.on('error', reject);
+ inputStream.pipe(parser);
});
- // Malformed records can't throw here — records missing required attributes
- // are dropped by normalizeXmlRecord, so minor XML malformations are skipped
- // rather than fatal (matching the prior sax error-skip behavior).
- parser.on('finish', resolve);
- parser.on('error', reject);
-
- inputStream.on('error', reject);
- inputStream.pipe(parser);
- });
-
- console.log(`🍎 XML parsing done: ${processedRecords} raw records across ${allDays.size} days — flushing remaining`);
-
- // Final flush for remaining records
- await flushDayBuckets(dayBuckets);
-
- // Clean up temp file
- unlink(filePath, () => {});
+ console.log(`🍎 XML parsing done: ${processedRecords} raw records across ${allDays.size} days — flushing remaining`);
+
+ // Final flush for remaining records
+ await flushDayBuckets(dayBuckets);
+ } finally {
+ // Runs on success AND on every rejection route (parser error, input-stream
+ // error, rejected batch flush). Destroy before unlink: a batch-flush
+ // rejection leaves the stream pause()d and still holding its fd, and on
+ // Windows unlink fails while the file is open. An Apple Health export.xml
+ // is routinely 0.5-3GB, so a leaked temp file is expensive.
+ inputStream.destroy();
+ await unlink(filePath).catch(() => {});
+ }
io?.emit('health:xml:complete', { days: allDays.size, records: processedRecords });
console.log(`🍎 XML import complete: ${processedRecords} records across ${allDays.size} days`);
diff --git a/server/services/appleHealthXml.test.js b/server/services/appleHealthXml.test.js
new file mode 100644
index 0000000000..b34bcbc26e
--- /dev/null
+++ b/server/services/appleHealthXml.test.js
@@ -0,0 +1,88 @@
+/**
+ * Temp-file / read-stream lifecycle contract for the Apple Health XML import.
+ *
+ * An `export.xml` is routinely 0.5-3GB and the route has already unlinked the
+ * uploaded ZIP by the time the import runs, so `importAppleHealthXml` is the
+ * last owner of that file: it must remove it and release its fd on EVERY exit,
+ * not just the success path (issue #5654).
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, writeFile, rm, access } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// Keep the import off the real health day-file store; `writeDayFile` doubles as
+// the injection point for a failing flush.
+const store = vi.hoisted(() => ({ writeDayFile: null }));
+vi.mock('./appleHealthIngest.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readDayFile: vi.fn(async (date) => ({ date, metrics: {} })),
+ writeDayFile: vi.fn((...args) => store.writeDayFile(...args)),
+ };
+});
+
+// Capture the read streams the service opens so the fd-release half of the
+// contract is assertable (unlink alone succeeds on POSIX with the fd still open).
+const streams = [];
+vi.mock('fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ createReadStream: (...args) => {
+ const s = actual.createReadStream(...args);
+ streams.push(s);
+ return s;
+ },
+ };
+});
+
+const { importAppleHealthXml } = await import('./appleHealthXml.js');
+
+const XML = `<?xml version="1.0" encoding="UTF-8"?>
+<HealthData locale="en_US">
+ <Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count" startDate="2025-01-15 08:00:00 -0800" endDate="2025-01-15 08:05:00 -0800" value="120"/>
+ <Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Watch" unit="count/min" startDate="2025-01-15 08:01:00 -0800" endDate="2025-01-15 08:01:00 -0800" value="72"/>
+</HealthData>`;
+
+const exists = (p) => access(p).then(() => true, () => false);
+
+describe('importAppleHealthXml temp-file lifecycle', () => {
+ let dir;
+ let xmlPath;
+
+ beforeEach(async () => {
+ streams.length = 0;
+ store.writeDayFile = async () => {};
+ dir = await mkdtemp(join(tmpdir(), 'portos-apple-health-test-'));
+ xmlPath = join(dir, 'export.xml');
+ await writeFile(xmlPath, XML, 'utf-8');
+ });
+
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ it('removes the input file and releases its fd after a successful import', async () => {
+ const result = await importAppleHealthXml(xmlPath, null);
+
+ expect(result).toEqual({ days: 1, records: 2 });
+ expect(await exists(xmlPath)).toBe(false);
+ expect(streams).toHaveLength(1);
+ expect(streams[0].destroyed).toBe(true);
+ });
+
+ it('removes the input file and releases its fd when the flush rejects', async () => {
+ store.writeDayFile = async () => { throw new Error('disk full'); };
+
+ await expect(importAppleHealthXml(xmlPath, null)).rejects.toThrow('disk full');
+
+ // Without the try/finally the multi-GB file and the open fd both survived
+ // the rejection for the life of the process.
+ expect(await exists(xmlPath)).toBe(false);
+ expect(streams).toHaveLength(1);
+ expect(streams[0].destroyed).toBe(true);
+ });
+});