Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: config reset on app restart and improve migrations handling #394

Merged
merged 2 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/main/src/modules/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'node:path';
import log from 'electron-log';
import { randomUUID, type UUID } from 'node:crypto';
import { FileSystemStorage } from '/shared/types/storage';
import { config } from './config';
import { getConfig } from './config';
import { getWorkspaceConfigPath } from './electron';

let analytics: Analytics | null = null;
Expand All @@ -19,6 +19,7 @@ export function setUserId(userId: string) {
}

export async function getAnonymousId() {
const config = await getConfig();
const userId = await config.get<string>('userId');
if (!userId) {
const uuid = randomUUID();
Expand Down
46 changes: 26 additions & 20 deletions packages/main/src/modules/config.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
import path from 'node:path';
import { FileSystemStorage } from '/shared/types/storage';
import { FileSystemStorage, type IFileSystemStorage } from '/shared/types/storage';
import { SETTINGS_DIRECTORY, CONFIG_FILE_NAME, getFullScenesPath } from '/shared/paths';
import { DEFAULT_CONFIG, mergeConfig } from '/shared/types/config';
import { DEFAULT_CONFIG, mergeConfig, type Config } from '/shared/types/config';
import { getUserDataPath } from './electron';
import { waitForMigrations } from './migrations';
import log from 'electron-log/main';

export const CONFIG_PATH = path.join(getUserDataPath(), SETTINGS_DIRECTORY, CONFIG_FILE_NAME);
const storage = await FileSystemStorage.getOrCreate(CONFIG_PATH);

// Initialize with default values if empty
const existingConfig = await storage.get<Record<string, any>>('');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line was the bug, this always returns undefined, and causes the default config to be applied over the existing one.

const defaultConfig = { ...DEFAULT_CONFIG };
defaultConfig.settings.scenesPath = getFullScenesPath(getUserDataPath());
let configStorage: IFileSystemStorage | undefined;

if (!existingConfig || Object.keys(existingConfig).length === 0) {
// Write the default config
for (const [key, value] of Object.entries(defaultConfig)) {
await storage.set(key, value);
}
} else {
// Deep merge with defaults if config exists but might be missing properties
const mergedConfig = mergeConfig(existingConfig, defaultConfig);
if (JSON.stringify(existingConfig) !== JSON.stringify(mergedConfig)) {
for (const [key, value] of Object.entries(mergedConfig)) {
await storage.set(key, value);
export async function getConfig(): Promise<IFileSystemStorage> {
await waitForMigrations();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just to avoid possible race conditions between the migration of the config and the initialization of the default values.


if (!configStorage) {
configStorage = await FileSystemStorage.getOrCreate(CONFIG_PATH);

// Initialize with default values if empty or merge with defaults if partial
const defaultConfig = { ...DEFAULT_CONFIG };
defaultConfig.settings.scenesPath = getFullScenesPath(getUserDataPath());

const existingConfig = await configStorage.getAll<Partial<Config>>();

// Deep merge with defaults if config exists but might be missing properties
const mergedConfig = mergeConfig(existingConfig, defaultConfig);
if (JSON.stringify(existingConfig) !== JSON.stringify(mergedConfig)) {
log.info('[Config] Writing merged config to storage');
await configStorage.setAll(mergedConfig);
} else {
log.info('[Config] Config already exists and is up to date');
}
}
}

export const config = storage;
return configStorage;
}
20 changes: 17 additions & 3 deletions packages/main/src/modules/migrations.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
import path from 'path';
import fs from 'fs/promises';
import log from 'electron-log/main';
import { future } from 'fp-future';
import { SCENES_DIRECTORY } from '/shared/paths';
import { getAppHomeLegacy, getUserDataPath } from './electron';
import { CONFIG_PATH } from './config';

const migrationsFuture = future<void>();

export async function waitForMigrations(): Promise<void> {
return migrationsFuture;
}

export async function runMigrations() {
log.info('[Migrations] Starting migrations');
await migrateLegacyPaths();
log.info('[Migrations] Migrations completed');
try {
log.info('[Migrations] Starting migrations');
await migrateLegacyPaths();
log.info('[Migrations] Migrations completed');
migrationsFuture.resolve();
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
migrationsFuture.reject(err);
throw error;
}
}

async function isValidScene(scenePath: string): Promise<boolean> {
Expand Down
3 changes: 2 additions & 1 deletion packages/preload/src/modules/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,17 +304,18 @@ export async function duplicateProject(_path: string): Promise<Project> {
* @throws An error if the selected directory is not a valid project.
*/
export async function importProject(): Promise<Project | undefined> {
const config = await getConfig();
const [projectPath] = await invoke('electron.showOpenDialog', {
title: 'Import project',
properties: ['openDirectory'],
defaultPath: config.settings.scenesPath,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a quality-of-life improvement for users

});

const cancelled = !projectPath;

if (cancelled) return undefined;

const pathBaseName = path.basename(projectPath);
const config = await getConfig();
const [projects] = await getProjects(config.workspace.paths);
const projectAlreadyExists = projects.find($ => $.path === projectPath);

Expand Down
7 changes: 7 additions & 0 deletions packages/shared/types/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,18 @@ async function _createFileSystemStorage(storagePath: string) {
const data = await read();
return data[key] as T | undefined;
},
getAll: async <T extends StorageData>(): Promise<T> => {
const data = await read();
return data as T;
},
set: async <T>(key: string, value: T): Promise<void> => {
const data = await read();
data[key] = value;
await write(data);
},
setAll: async <T extends StorageData>(data: T): Promise<void> => {
await write(data);
},
has: async (key: string): Promise<boolean> => {
const data = await read();
return key in data;
Expand Down
Loading