forked from Blendman974/faceclaw
Fix ring health persistence and page acknowledgements
This commit is contained in:
1 parent
22c851a6b9
commit
c595cb4b6e
10 files changed
+472
-92
No files matched your search
-12
@@ -13,7 +13,6 @@ installNativeUserAgent()
|
||||
registerShareIntentHandler()
|
||||
registerPhoneRotation()
|
||||
|
||||
import { resyncSystemAppearance } from './native/system-appearance'
|
||||
import { startLiveHealthSync, startAlignedRingPull } from './health/health-live'
|
||||
|
||||
installNativeUserAgent()
|
||||
@@ -30,17 +29,6 @@ startLiveHealthSync()
|
||||
// so a ring that stays connected is never read.
|
||||
startAlignedRingPull()
|
||||
|
||||
// Live system dark/light switches while the app is running were confirmed
|
||||
// (Chris, both directions, 2026-09-02) to leave the Ghost companion's Terminal
|
||||
// and Doc panes white-on-white and Rich View visually dark-locked -- while a
|
||||
// COLD launch in either theme renders correctly. That proves the app.css
|
||||
// .ns-dark rules themselves are right and the LIVE-UPDATE signal is the gap,
|
||||
// not any one pane's styling -- see system-appearance.ts for the actual fix
|
||||
// and why it resyncs from two triggers instead of trusting the framework's
|
||||
// own automatic recolor alone.
|
||||
Application.on(Application.systemAppearanceChangedEvent, resyncSystemAppearance)
|
||||
Application.on(Application.resumeEvent, resyncSystemAppearance)
|
||||
|
||||
Application.run({ moduleName: 'app-root' })
|
||||
|
||||
// Don't place any code after the application has been started
|
||||
@@ -467,7 +467,9 @@ export function syncLiveRecords(): LiveSyncResult {
|
||||
const store = healthStore();
|
||||
const samplesWritten = store.ingestSamples(samples);
|
||||
const sleepWritten = store.ingestSleep(sleep);
|
||||
if (samplesWritten > 0 || sleepWritten > 0) markLiveData();
|
||||
// Also mark on a retry whose samples were already appended before a later
|
||||
// write failed. Otherwise opening Health could seed fixtures over real data.
|
||||
markLiveData();
|
||||
|
||||
// ONLY here. Both store writes have returned, so the records are durable.
|
||||
// If either threw, or the process died above this line, nothing is cleared
|
||||
|
||||
+22
-16
@@ -20,7 +20,7 @@
|
||||
import { File, knownFolders } from "@nativescript/core";
|
||||
|
||||
import { buildFixtures, FIXTURE_VERSION } from "./health-fixtures";
|
||||
import { healthStore } from "./health-store-files";
|
||||
import { checkedFileOperation, healthStore } from "./health-store-files";
|
||||
|
||||
const MARKER_FILE = "fixture-marker.json";
|
||||
|
||||
@@ -63,11 +63,10 @@ export function hasLiveData(): boolean {
|
||||
|
||||
/** Record that real data has been stored. Called by the live ingest path. */
|
||||
export function markLiveData(): void {
|
||||
try {
|
||||
File.fromPath(livePath()).writeTextSync(JSON.stringify({ firstAtMs: Date.now() }));
|
||||
} catch (error) {
|
||||
console.warn("health live marker write failed", error);
|
||||
}
|
||||
if (hasLiveData()) return;
|
||||
checkedFileOperation((onError) =>
|
||||
File.fromPath(livePath()).writeTextSync(JSON.stringify({ firstAtMs: Date.now() }), onError),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,12 +88,17 @@ export function purgeFixtureData(): void {
|
||||
(name.startsWith("samples-") && name.endsWith(".jsonl")) ||
|
||||
name === "sleep.jsonl" ||
|
||||
name === "rollups.json";
|
||||
if (isStoreFile) File.fromPath(entity.path).removeSync();
|
||||
if (isStoreFile) {
|
||||
checkedFileOperation((onError) => File.fromPath(entity.path).removeSync(onError));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("health fixture purge failed", error);
|
||||
// Keep the badge until every fixture file is gone. A failed purge must
|
||||
// stop live ingest so it cannot mix real records with remaining fixtures.
|
||||
clearFixtureMarker();
|
||||
} finally {
|
||||
// Also invalidate after a partial purge; cached rows no longer match disk.
|
||||
healthStore().resetCache();
|
||||
}
|
||||
clearFixtureMarker();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,10 +120,14 @@ export function seedFixtures(days = 45): boolean {
|
||||
try {
|
||||
const store = healthStore();
|
||||
const { samples, sleep } = buildFixtures({ days, nowMs: Date.now() });
|
||||
// Label before the first append so a failed seed remains identifiable and
|
||||
// can be purged before real data is ingested.
|
||||
const marker: Marker = { version: FIXTURE_VERSION, seededAtMs: Date.now(), days };
|
||||
checkedFileOperation((onError) =>
|
||||
File.fromPath(markerPath()).writeTextSync(JSON.stringify(marker), onError),
|
||||
);
|
||||
store.ingestSamples(samples);
|
||||
store.ingestSleep(sleep);
|
||||
const marker: Marker = { version: FIXTURE_VERSION, seededAtMs: Date.now(), days };
|
||||
File.fromPath(markerPath()).writeTextSync(JSON.stringify(marker));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("health fixture seed failed", error);
|
||||
@@ -129,9 +137,7 @@ export function seedFixtures(days = 45): boolean {
|
||||
|
||||
/** Drop the marker. Call before the first real ingest. */
|
||||
export function clearFixtureMarker(): void {
|
||||
try {
|
||||
if (File.exists(markerPath())) File.fromPath(markerPath()).removeSync();
|
||||
} catch (error) {
|
||||
console.warn("health fixture marker clear failed", error);
|
||||
if (File.exists(markerPath())) {
|
||||
checkedFileOperation((onError) => File.fromPath(markerPath()).removeSync(onError));
|
||||
}
|
||||
}
|
||||
@@ -42,27 +42,13 @@ class FileBackend implements HealthStorageBackend {
|
||||
}
|
||||
|
||||
append(name: string, text: string): void {
|
||||
try {
|
||||
// `File.fromPath` creates the file when it is missing, and
|
||||
// `appendTextSync` is the durable single-call append - deliberately not
|
||||
// read-modify-write, which would put every record already on disk at
|
||||
// risk on every new one.
|
||||
File.fromPath(pathFor(name)).appendTextSync(text, (error) => {
|
||||
console.warn(`health store append failed (${name})`, error);
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(`health store append threw (${name})`, error);
|
||||
}
|
||||
// NativeScript reports IO failures through callbacks as well as throws.
|
||||
// Propagate both so the caller retains the unconsumed ring batch.
|
||||
checkedFileOperation((onError) => File.fromPath(pathFor(name)).appendTextSync(text, onError));
|
||||
}
|
||||
|
||||
write(name: string, text: string): void {
|
||||
try {
|
||||
File.fromPath(pathFor(name)).writeTextSync(text, (error) => {
|
||||
console.warn(`health store write failed (${name})`, error);
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(`health store write threw (${name})`, error);
|
||||
}
|
||||
checkedFileOperation((onError) => File.fromPath(pathFor(name)).writeTextSync(text, onError));
|
||||
}
|
||||
|
||||
list(): string[] {
|
||||
@@ -77,6 +63,15 @@ class FileBackend implements HealthStorageBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/** Convert a synchronous NativeScript error callback into a thrown failure. */
|
||||
export function checkedFileOperation(operation: (onError: (error: any) => void) => void): void {
|
||||
let failure: Error | undefined;
|
||||
operation((error) => {
|
||||
failure = error instanceof Error ? error : new Error(error?.message ?? String(error));
|
||||
});
|
||||
if (failure) throw failure;
|
||||
}
|
||||
|
||||
let store: HealthStore | null = null;
|
||||
|
||||
/** The app's one health store. Created on first use. */
|
||||
|
||||
+31
-11
@@ -121,9 +121,18 @@ export class HealthStore {
|
||||
private readonly shards = new Map<string, Map<string, HealthSample>>();
|
||||
private sleep: SleepSession[] | null = null;
|
||||
private rollups: RollupFile | null = null;
|
||||
private rollupsDirty = false;
|
||||
|
||||
constructor(private readonly backend: HealthStorageBackend) {}
|
||||
|
||||
/** Forget cached data after the backing files have been purged. */
|
||||
resetCache(): void {
|
||||
this.shards.clear();
|
||||
this.sleep = null;
|
||||
this.rollups = null;
|
||||
this.rollupsDirty = false;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Writing
|
||||
|
||||
@@ -154,26 +163,36 @@ export class HealthStore {
|
||||
* If the shard grows again, the value is changing and the question is why.
|
||||
*/
|
||||
ingestSamples(samples: readonly HealthSample[]): number {
|
||||
const byShard = new Map<string, HealthSample[]>();
|
||||
const byShard = new Map<string, Map<string, HealthSample>>();
|
||||
for (const sample of samples) {
|
||||
if (!Number.isFinite(sample.startMs) || sample.spanMs <= 0) continue;
|
||||
const name = shardName(sample.startMs);
|
||||
const shard = this.loadShard(name);
|
||||
const key = sampleKey(sample);
|
||||
const existing = shard.get(key);
|
||||
const pending = byShard.get(name) ?? new Map<string, HealthSample>();
|
||||
const existing = pending.get(key) ?? shard.get(key);
|
||||
if (existing && sameSample(existing, sample)) continue;
|
||||
shard.set(key, sample);
|
||||
const pending = byShard.get(name);
|
||||
if (pending) pending.push(sample);
|
||||
else byShard.set(name, [sample]);
|
||||
pending.set(key, sample);
|
||||
byShard.set(name, pending);
|
||||
}
|
||||
let written = 0;
|
||||
for (const [name, list] of byShard) {
|
||||
for (const [name, pending] of byShard) {
|
||||
const list = [...pending.values()];
|
||||
const text = list.map((sample) => `${JSON.stringify(toLine(sample))}\n`).join("");
|
||||
this.backend.append(name, text);
|
||||
// A failed append can leave an incomplete final line. Start each batch
|
||||
// on a fresh line so retrying cannot concatenate a valid record onto it.
|
||||
this.backend.append(name, `\n${text}`);
|
||||
this.rollupsDirty = true;
|
||||
// Only durable values participate in deduplication. If another shard
|
||||
// fails, a retry skips this successful append and retries the rest.
|
||||
const shard = this.loadShard(name);
|
||||
for (const [key, sample] of pending) shard.set(key, sample);
|
||||
written += list.length;
|
||||
}
|
||||
if (written > 0) this.updateRollupsFor(samples);
|
||||
if (this.rollupsDirty) {
|
||||
this.updateRollupsFor(samples);
|
||||
this.rollupsDirty = false;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
@@ -184,7 +203,7 @@ export class HealthStore {
|
||||
* later sync replaces rather than duplicates.
|
||||
*/
|
||||
ingestSleep(sessions: readonly SleepSession[]): number {
|
||||
const held = this.loadSleep();
|
||||
const held = this.loadSleep().slice();
|
||||
const fresh: SleepSession[] = [];
|
||||
for (const session of sessions) {
|
||||
const index = held.findIndex(
|
||||
@@ -200,7 +219,8 @@ export class HealthStore {
|
||||
fresh.push(session);
|
||||
}
|
||||
if (fresh.length > 0) {
|
||||
this.backend.append(SLEEP_FILE, fresh.map((s) => `${JSON.stringify(s)}\n`).join(""));
|
||||
this.backend.append(SLEEP_FILE, "\n" + fresh.map((s) => `${JSON.stringify(s)}\n`).join(""));
|
||||
this.sleep = held;
|
||||
}
|
||||
return fresh.length;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user