diff options
Diffstat (limited to 'packages/main')
-rw-r--r-- | packages/main/esbuild.config.js | 5 | ||||
-rw-r--r-- | packages/main/jest.config.js | 3 | ||||
-rw-r--r-- | packages/main/package.json | 3 | ||||
-rw-r--r-- | packages/main/src/compositionRoot.ts | 4 | ||||
-rw-r--r-- | packages/main/src/controllers/__tests__/config.spec.ts | 184 | ||||
-rw-r--r-- | packages/main/src/controllers/__tests__/nativeTheme.spec.ts | 71 | ||||
-rw-r--r-- | packages/main/src/controllers/config.ts | 16 | ||||
-rw-r--r-- | packages/main/src/services/ConfigPersistenceService.ts | 106 | ||||
-rw-r--r-- | packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts | 128 | ||||
-rw-r--r-- | packages/main/src/utils/index.ts | 2 | ||||
-rw-r--r-- | packages/main/src/utils/logging.ts | 16 | ||||
-rw-r--r-- | packages/main/tsconfig.json | 1 |
12 files changed, 420 insertions, 119 deletions
diff --git a/packages/main/esbuild.config.js b/packages/main/esbuild.config.js index a39534d..af52f27 100644 --- a/packages/main/esbuild.config.js +++ b/packages/main/esbuild.config.js | |||
@@ -1,5 +1,6 @@ | |||
1 | import { node, fileURLToDirname } from '../../config/build-common.js'; | 1 | import { node } from '../../config/buildConstants.js'; |
2 | import { getConfig } from '../../config/esbuild-config.js'; | 2 | import { getConfig } from '../../config/esbuildConfig.js'; |
3 | import { fileURLToDirname } from '../../config/utils.js'; | ||
3 | 4 | ||
4 | const externalPackages = ['electron']; | 5 | const externalPackages = ['electron']; |
5 | 6 | ||
diff --git a/packages/main/jest.config.js b/packages/main/jest.config.js new file mode 100644 index 0000000..b86463c --- /dev/null +++ b/packages/main/jest.config.js | |||
@@ -0,0 +1,3 @@ | |||
1 | import rootConfig from '../../config/jest.config.base.js'; | ||
2 | |||
3 | export default rootConfig; | ||
diff --git a/packages/main/package.json b/packages/main/package.json index 99451bd..eb2ecf6 100644 --- a/packages/main/package.json +++ b/packages/main/package.json | |||
@@ -10,7 +10,7 @@ | |||
10 | "dependencies": { | 10 | "dependencies": { |
11 | "@sophie/service-shared": "workspace:*", | 11 | "@sophie/service-shared": "workspace:*", |
12 | "@sophie/shared": "workspace:*", | 12 | "@sophie/shared": "workspace:*", |
13 | "chalk": "^5.0.0", | 13 | "chalk": "^4.1.2", |
14 | "electron": "16.0.5", | 14 | "electron": "16.0.5", |
15 | "json5": "^2.2.0", | 15 | "json5": "^2.2.0", |
16 | "lodash-es": "^4.17.21", | 16 | "lodash-es": "^4.17.21", |
@@ -27,6 +27,7 @@ | |||
27 | "@types/node": "^17.0.5", | 27 | "@types/node": "^17.0.5", |
28 | "electron-devtools-installer": "^3.2.0", | 28 | "electron-devtools-installer": "^3.2.0", |
29 | "esbuild": "^0.14.9", | 29 | "esbuild": "^0.14.9", |
30 | "jest": "^27.4.5", | ||
30 | "rimraf": "^3.0.2", | 31 | "rimraf": "^3.0.2", |
31 | "typescript": "^4.5.4" | 32 | "typescript": "^4.5.4" |
32 | } | 33 | } |
diff --git a/packages/main/src/compositionRoot.ts b/packages/main/src/compositionRoot.ts index eb6f50f..d420bd6 100644 --- a/packages/main/src/compositionRoot.ts +++ b/packages/main/src/compositionRoot.ts | |||
@@ -22,12 +22,12 @@ import { app } from 'electron'; | |||
22 | 22 | ||
23 | import { initConfig } from './controllers/config'; | 23 | import { initConfig } from './controllers/config'; |
24 | import { initNativeTheme } from './controllers/nativeTheme'; | 24 | import { initNativeTheme } from './controllers/nativeTheme'; |
25 | import { ConfigPersistenceService } from './services/ConfigPersistenceService'; | 25 | import { ConfigPersistenceServiceImpl } from './services/impl/ConfigPersistenceServiceImpl'; |
26 | import { MainStore } from './stores/MainStore'; | 26 | import { MainStore } from './stores/MainStore'; |
27 | import { Disposer } from './utils'; | 27 | import { Disposer } from './utils'; |
28 | 28 | ||
29 | export async function init(store: MainStore): Promise<Disposer> { | 29 | export async function init(store: MainStore): Promise<Disposer> { |
30 | const configPersistenceService = new ConfigPersistenceService(app.getPath('userData')); | 30 | const configPersistenceService = new ConfigPersistenceServiceImpl(app.getPath('userData')); |
31 | const disposeConfigController = await initConfig(store.config, configPersistenceService); | 31 | const disposeConfigController = await initConfig(store.config, configPersistenceService); |
32 | const disposeNativeThemeController = initNativeTheme(store); | 32 | const disposeNativeThemeController = initNativeTheme(store); |
33 | 33 | ||
diff --git a/packages/main/src/controllers/__tests__/config.spec.ts b/packages/main/src/controllers/__tests__/config.spec.ts new file mode 100644 index 0000000..9471ca9 --- /dev/null +++ b/packages/main/src/controllers/__tests__/config.spec.ts | |||
@@ -0,0 +1,184 @@ | |||
1 | /* | ||
2 | * Copyright (C) 2021-2022 Kristóf Marussy <kristof@marussy.com> | ||
3 | * | ||
4 | * This file is part of Sophie. | ||
5 | * | ||
6 | * Sophie is free software: you can redistribute it and/or modify | ||
7 | * it under the terms of the GNU Affero General Public License as | ||
8 | * published by the Free Software Foundation, version 3. | ||
9 | * | ||
10 | * This program is distributed in the hope that it will be useful, | ||
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
13 | * GNU Affero General Public License for more details. | ||
14 | * | ||
15 | * You should have received a copy of the GNU Affero General Public License | ||
16 | * along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
17 | * | ||
18 | * SPDX-License-Identifier: AGPL-3.0-only | ||
19 | */ | ||
20 | |||
21 | import { jest } from '@jest/globals'; | ||
22 | import { mocked } from 'jest-mock'; | ||
23 | import ms from 'ms'; | ||
24 | |||
25 | import { initConfig } from '../config'; | ||
26 | import type { ConfigPersistenceService } from '../../services/ConfigPersistenceService'; | ||
27 | import { Config, config as configModel } from '../../stores/Config'; | ||
28 | import { Disposer, silenceLogger } from '../../utils'; | ||
29 | |||
30 | let config: Config; | ||
31 | let persistenceService: ConfigPersistenceService = { | ||
32 | readConfig: jest.fn(), | ||
33 | writeConfig: jest.fn(), | ||
34 | watchConfig: jest.fn(), | ||
35 | }; | ||
36 | let lessThanThrottleMs = ms('0.1s'); | ||
37 | let throttleMs = ms('1s'); | ||
38 | |||
39 | beforeAll(() => { | ||
40 | jest.useFakeTimers(); | ||
41 | silenceLogger(); | ||
42 | }); | ||
43 | |||
44 | beforeEach(() => { | ||
45 | config = configModel.create(); | ||
46 | }); | ||
47 | |||
48 | describe('when initializing', () => { | ||
49 | describe('when there is no config file', () => { | ||
50 | beforeEach(() => { | ||
51 | mocked(persistenceService.readConfig).mockResolvedValueOnce({ | ||
52 | found: false, | ||
53 | }); | ||
54 | }); | ||
55 | |||
56 | it('should create a new config file', async () => { | ||
57 | await initConfig(config, persistenceService); | ||
58 | expect(persistenceService.writeConfig).toBeCalledTimes(1); | ||
59 | }); | ||
60 | |||
61 | it('should bail if there is an an error creating the config file', async () => { | ||
62 | mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo')); | ||
63 | await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error); | ||
64 | }); | ||
65 | }); | ||
66 | |||
67 | describe('when there is a valid config file', () => { | ||
68 | beforeEach(() => { | ||
69 | mocked(persistenceService.readConfig).mockResolvedValueOnce({ | ||
70 | found: true, | ||
71 | data: { | ||
72 | themeSource: 'dark', | ||
73 | }, | ||
74 | }); | ||
75 | }); | ||
76 | |||
77 | it('should read the existing config file is there is one', async () => { | ||
78 | await initConfig(config, persistenceService); | ||
79 | expect(persistenceService.writeConfig).not.toBeCalled(); | ||
80 | expect(config.themeSource).toBe('dark'); | ||
81 | }); | ||
82 | |||
83 | it('should bail if it cannot set up a watcher', async () => { | ||
84 | mocked(persistenceService.watchConfig).mockImplementationOnce(() => { | ||
85 | throw new Error('boo'); | ||
86 | }); | ||
87 | await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error); | ||
88 | }); | ||
89 | }); | ||
90 | |||
91 | it('should not apply an invalid config file', async () => { | ||
92 | mocked(persistenceService.readConfig).mockResolvedValueOnce({ | ||
93 | found: true, | ||
94 | data: { | ||
95 | themeSource: -1, | ||
96 | }, | ||
97 | }); | ||
98 | await initConfig(config, persistenceService); | ||
99 | expect(config.themeSource).not.toBe(-1); | ||
100 | }); | ||
101 | |||
102 | it('should bail if it cannot determine whether there is a config file', async () => { | ||
103 | mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo')); | ||
104 | await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error); | ||
105 | }); | ||
106 | }); | ||
107 | |||
108 | describe('when it has loaded the config', () => { | ||
109 | let sutDisposer: Disposer; | ||
110 | let watcherDisposer: Disposer = jest.fn(); | ||
111 | let configChangedCallback: () => Promise<void>; | ||
112 | |||
113 | beforeEach(async () => { | ||
114 | mocked(persistenceService.readConfig).mockResolvedValueOnce({ | ||
115 | found: true, | ||
116 | data: {}, | ||
117 | }); | ||
118 | mocked(persistenceService.watchConfig).mockReturnValueOnce(watcherDisposer); | ||
119 | sutDisposer = await initConfig(config, persistenceService, throttleMs); | ||
120 | configChangedCallback = mocked(persistenceService.watchConfig).mock.calls[0][0]; | ||
121 | jest.resetAllMocks(); | ||
122 | }); | ||
123 | |||
124 | it('should throttle saving changes to the config file', () => { | ||
125 | mocked(persistenceService.writeConfig).mockResolvedValue(undefined); | ||
126 | config.setThemeSource('dark'); | ||
127 | jest.advanceTimersByTime(lessThanThrottleMs); | ||
128 | config.setThemeSource('light'); | ||
129 | jest.advanceTimersByTime(throttleMs); | ||
130 | expect(persistenceService.writeConfig).toBeCalledTimes(1); | ||
131 | }); | ||
132 | |||
133 | it('should handle config writing errors gracefully', () => { | ||
134 | mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo')); | ||
135 | config.setThemeSource('dark'); | ||
136 | jest.advanceTimersByTime(throttleMs); | ||
137 | expect(persistenceService.writeConfig).toBeCalledTimes(1); | ||
138 | }); | ||
139 | |||
140 | it('should read the config file when it has changed', async () => { | ||
141 | mocked(persistenceService.readConfig).mockResolvedValueOnce({ | ||
142 | found: true, | ||
143 | data: { | ||
144 | themeSource: 'dark', | ||
145 | }, | ||
146 | }); | ||
147 | await configChangedCallback(); | ||
148 | // Do not write back the changes we have just read. | ||
149 | expect(persistenceService.writeConfig).not.toBeCalled(); | ||
150 | expect(config.themeSource).toBe('dark'); | ||
151 | }); | ||
152 | |||
153 | it('should not apply an invalid config file when it has changed', async () => { | ||
154 | mocked(persistenceService.readConfig).mockResolvedValueOnce({ | ||
155 | found: true, | ||
156 | data: { | ||
157 | themeSource: -1, | ||
158 | }, | ||
159 | }); | ||
160 | await configChangedCallback(); | ||
161 | expect(config.themeSource).not.toBe(-1); | ||
162 | }); | ||
163 | |||
164 | it('should handle config writing errors gracefully', async () => { | ||
165 | mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo')); | ||
166 | await configChangedCallback(); | ||
167 | }); | ||
168 | |||
169 | describe('when it was disposed', () => { | ||
170 | beforeEach(() => { | ||
171 | sutDisposer(); | ||
172 | }); | ||
173 | |||
174 | it('should dispose the watcher', () => { | ||
175 | expect(watcherDisposer).toBeCalled(); | ||
176 | }); | ||
177 | |||
178 | it('should not listen to store changes any more', () => { | ||
179 | config.setThemeSource('dark'); | ||
180 | jest.advanceTimersByTime(2 * throttleMs); | ||
181 | expect(persistenceService.writeConfig).not.toBeCalled(); | ||
182 | }); | ||
183 | }); | ||
184 | }); | ||
diff --git a/packages/main/src/controllers/__tests__/nativeTheme.spec.ts b/packages/main/src/controllers/__tests__/nativeTheme.spec.ts new file mode 100644 index 0000000..cfb557c --- /dev/null +++ b/packages/main/src/controllers/__tests__/nativeTheme.spec.ts | |||
@@ -0,0 +1,71 @@ | |||
1 | /* | ||
2 | * Copyright (C) 2021-2022 Kristóf Marussy <kristof@marussy.com> | ||
3 | * | ||
4 | * This file is part of Sophie. | ||
5 | * | ||
6 | * Sophie is free software: you can redistribute it and/or modify | ||
7 | * it under the terms of the GNU Affero General Public License as | ||
8 | * published by the Free Software Foundation, version 3. | ||
9 | * | ||
10 | * This program is distributed in the hope that it will be useful, | ||
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
13 | * GNU Affero General Public License for more details. | ||
14 | * | ||
15 | * You should have received a copy of the GNU Affero General Public License | ||
16 | * along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
17 | * | ||
18 | * SPDX-License-Identifier: AGPL-3.0-only | ||
19 | */ | ||
20 | |||
21 | import { jest } from '@jest/globals'; | ||
22 | import { mocked } from 'jest-mock'; | ||
23 | |||
24 | import { createMainStore, MainStore } from '../../stores/MainStore'; | ||
25 | import { Disposer } from '../../utils'; | ||
26 | |||
27 | let shouldUseDarkColors = false; | ||
28 | |||
29 | jest.unstable_mockModule('electron', () => ({ | ||
30 | nativeTheme: { | ||
31 | themeSource: 'system', | ||
32 | get shouldUseDarkColors() { | ||
33 | return shouldUseDarkColors; | ||
34 | }, | ||
35 | on: jest.fn(), | ||
36 | off: jest.fn(), | ||
37 | }, | ||
38 | })); | ||
39 | |||
40 | const { nativeTheme } = await import('electron'); | ||
41 | const { initNativeTheme } = await import('../nativeTheme'); | ||
42 | |||
43 | let store: MainStore; | ||
44 | let disposeSut: Disposer; | ||
45 | |||
46 | beforeEach(() => { | ||
47 | store = createMainStore(); | ||
48 | disposeSut = initNativeTheme(store); | ||
49 | }); | ||
50 | |||
51 | it('should register a nativeTheme updated listener', () => { | ||
52 | expect(nativeTheme.on).toBeCalledWith('updated', expect.anything()); | ||
53 | }); | ||
54 | |||
55 | it('should synchronize themeSource changes to the nativeTheme', () => { | ||
56 | store.config.setThemeSource('dark'); | ||
57 | expect(nativeTheme.themeSource).toBe('dark'); | ||
58 | }); | ||
59 | |||
60 | it('should synchronize shouldUseDarkColors changes to the store', () => { | ||
61 | const listener = mocked(nativeTheme.on).mock.calls.find(([event]) => event === 'updated')![1]; | ||
62 | shouldUseDarkColors = true; | ||
63 | listener(); | ||
64 | expect(store.shared.shouldUseDarkColors).toBe(true); | ||
65 | }); | ||
66 | |||
67 | it('should remove the listener on dispose', () => { | ||
68 | const listener = mocked(nativeTheme.on).mock.calls.find(([event]) => event === 'updated')![1]; | ||
69 | disposeSut(); | ||
70 | expect(nativeTheme.off).toBeCalledWith('updated', listener); | ||
71 | }); | ||
diff --git a/packages/main/src/controllers/config.ts b/packages/main/src/controllers/config.ts index 600a142..d3559c8 100644 --- a/packages/main/src/controllers/config.ts +++ b/packages/main/src/controllers/config.ts | |||
@@ -60,12 +60,8 @@ export async function initConfig( | |||
60 | 60 | ||
61 | if (!await readConfig()) { | 61 | if (!await readConfig()) { |
62 | log.info('Config file was not found'); | 62 | log.info('Config file was not found'); |
63 | try { | 63 | await writeConfig(); |
64 | await writeConfig(); | 64 | log.info('Created config file'); |
65 | log.info('Created config file'); | ||
66 | } catch (err) { | ||
67 | log.error('Failed to initialize config', err); | ||
68 | } | ||
69 | } | 65 | } |
70 | 66 | ||
71 | const disposeOnSnapshot = onSnapshot(config, debounce((snapshot) => { | 67 | const disposeOnSnapshot = onSnapshot(config, debounce((snapshot) => { |
@@ -73,12 +69,16 @@ export async function initConfig( | |||
73 | if (lastSnapshotOnDisk !== snapshot) { | 69 | if (lastSnapshotOnDisk !== snapshot) { |
74 | writeConfig().catch((err) => { | 70 | writeConfig().catch((err) => { |
75 | log.error('Failed to write config on config change', err); | 71 | log.error('Failed to write config on config change', err); |
76 | }) | 72 | }); |
77 | } | 73 | } |
78 | }, debounceTime)); | 74 | }, debounceTime)); |
79 | 75 | ||
80 | const disposeWatcher = persistenceService.watchConfig(async () => { | 76 | const disposeWatcher = persistenceService.watchConfig(async () => { |
81 | await readConfig(); | 77 | try { |
78 | await readConfig(); | ||
79 | } catch (err) { | ||
80 | log.error('Failed to read config', err); | ||
81 | } | ||
82 | }, debounceTime); | 82 | }, debounceTime); |
83 | 83 | ||
84 | return () => { | 84 | return () => { |
diff --git a/packages/main/src/services/ConfigPersistenceService.ts b/packages/main/src/services/ConfigPersistenceService.ts index b2109f6..b3ad162 100644 --- a/packages/main/src/services/ConfigPersistenceService.ts +++ b/packages/main/src/services/ConfigPersistenceService.ts | |||
@@ -17,112 +17,16 @@ | |||
17 | * | 17 | * |
18 | * SPDX-License-Identifier: AGPL-3.0-only | 18 | * SPDX-License-Identifier: AGPL-3.0-only |
19 | */ | 19 | */ |
20 | import { watch } from 'fs'; | ||
21 | import { readFile, stat, writeFile } from 'fs/promises'; | ||
22 | import JSON5 from 'json5'; | ||
23 | import throttle from 'lodash-es/throttle'; | ||
24 | import { join } from 'path'; | ||
25 | 20 | ||
26 | import type { ConfigSnapshotOut } from '../stores/Config'; | 21 | import type { ConfigSnapshotOut } from '../stores/Config'; |
27 | import { Disposer, getLogger } from '../utils'; | 22 | import { Disposer } from '../utils'; |
28 | |||
29 | const log = getLogger('configPersistence'); | ||
30 | 23 | ||
31 | export type ReadConfigResult = { found: true; data: unknown; } | { found: false; }; | 24 | export type ReadConfigResult = { found: true; data: unknown; } | { found: false; }; |
32 | 25 | ||
33 | export class ConfigPersistenceService { | 26 | export interface ConfigPersistenceService { |
34 | private readonly configFilePath: string; | 27 | readConfig(): Promise<ReadConfigResult>; |
35 | |||
36 | private writingConfig = false; | ||
37 | |||
38 | private timeLastWritten: Date | null = null; | ||
39 | |||
40 | constructor( | ||
41 | private readonly userDataDir: string, | ||
42 | private readonly configFileName: string = 'config.json5', | ||
43 | ) { | ||
44 | this.configFileName = configFileName; | ||
45 | this.configFilePath = join(this.userDataDir, this.configFileName); | ||
46 | } | ||
47 | |||
48 | async readConfig(): Promise<ReadConfigResult> { | ||
49 | let configStr; | ||
50 | try { | ||
51 | configStr = await readFile(this.configFilePath, 'utf8'); | ||
52 | } catch (err) { | ||
53 | if ((err as NodeJS.ErrnoException).code === 'ENOENT') { | ||
54 | log.debug('Config file', this.configFilePath, 'was not found'); | ||
55 | return { found: false }; | ||
56 | } | ||
57 | throw err; | ||
58 | } | ||
59 | log.info('Read config file', this.configFilePath); | ||
60 | return { | ||
61 | found: true, | ||
62 | data: JSON5.parse(configStr), | ||
63 | }; | ||
64 | } | ||
65 | |||
66 | async writeConfig(configSnapshot: ConfigSnapshotOut): Promise<void> { | ||
67 | const configJson = JSON5.stringify(configSnapshot, { | ||
68 | space: 2, | ||
69 | }); | ||
70 | this.writingConfig = true; | ||
71 | try { | ||
72 | await writeFile(this.configFilePath, configJson, 'utf8'); | ||
73 | const { mtime } = await stat(this.configFilePath); | ||
74 | log.trace('Config file', this.configFilePath, 'last written at', mtime); | ||
75 | this.timeLastWritten = mtime; | ||
76 | } finally { | ||
77 | this.writingConfig = false; | ||
78 | } | ||
79 | log.info('Wrote config file', this.configFilePath); | ||
80 | } | ||
81 | |||
82 | watchConfig(callback: () => Promise<void>, throttleMs: number): Disposer { | ||
83 | log.debug('Installing watcher for', this.userDataDir); | ||
84 | |||
85 | const configChanged = throttle(async () => { | ||
86 | let mtime: Date; | ||
87 | try { | ||
88 | const stats = await stat(this.configFilePath); | ||
89 | mtime = stats.mtime; | ||
90 | log.trace('Config file last modified at', mtime); | ||
91 | } catch (err) { | ||
92 | if ((err as NodeJS.ErrnoException).code === 'ENOENT') { | ||
93 | log.debug('Config file', this.configFilePath, 'was deleted after being changed'); | ||
94 | return; | ||
95 | } | ||
96 | throw err; | ||
97 | } | ||
98 | if (!this.writingConfig | ||
99 | && (this.timeLastWritten === null || mtime > this.timeLastWritten)) { | ||
100 | log.debug( | ||
101 | 'Found a config file modified at', | ||
102 | mtime, | ||
103 | 'whish is newer than last written', | ||
104 | this.timeLastWritten, | ||
105 | ); | ||
106 | return callback(); | ||
107 | } | ||
108 | }, throttleMs); | ||
109 | |||
110 | const watcher = watch(this.userDataDir, { | ||
111 | persistent: false, | ||
112 | }); | ||
113 | 28 | ||
114 | watcher.on('change', (eventType, filename) => { | 29 | writeConfig(configSnapshot: ConfigSnapshotOut): Promise<void>; |
115 | if (eventType === 'change' | ||
116 | && (filename === this.configFileName || filename === null)) { | ||
117 | configChanged()?.catch((err) => { | ||
118 | console.log('Unhandled error while listening for config changes', err); | ||
119 | }); | ||
120 | } | ||
121 | }); | ||
122 | 30 | ||
123 | return () => { | 31 | watchConfig(callback: () => Promise<void>, throttleMs: number): Disposer; |
124 | log.trace('Removing watcher for', this.configFilePath); | ||
125 | watcher.close(); | ||
126 | }; | ||
127 | } | ||
128 | } | 32 | } |
diff --git a/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts b/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts new file mode 100644 index 0000000..bffc38c --- /dev/null +++ b/packages/main/src/services/impl/ConfigPersistenceServiceImpl.ts | |||
@@ -0,0 +1,128 @@ | |||
1 | |||
2 | /* | ||
3 | * Copyright (C) 2021-2022 Kristóf Marussy <kristof@marussy.com> | ||
4 | * | ||
5 | * This file is part of Sophie. | ||
6 | * | ||
7 | * Sophie is free software: you can redistribute it and/or modify | ||
8 | * it under the terms of the GNU Affero General Public License as | ||
9 | * published by the Free Software Foundation, version 3. | ||
10 | * | ||
11 | * This program is distributed in the hope that it will be useful, | ||
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | * GNU Affero General Public License for more details. | ||
15 | * | ||
16 | * You should have received a copy of the GNU Affero General Public License | ||
17 | * along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
18 | * | ||
19 | * SPDX-License-Identifier: AGPL-3.0-only | ||
20 | */ | ||
21 | import { watch } from 'fs'; | ||
22 | import { readFile, stat, writeFile } from 'fs/promises'; | ||
23 | import JSON5 from 'json5'; | ||
24 | import throttle from 'lodash-es/throttle'; | ||
25 | import { join } from 'path'; | ||
26 | |||
27 | import type { ConfigPersistenceService, ReadConfigResult } from '../ConfigPersistenceService'; | ||
28 | import type { ConfigSnapshotOut } from '../../stores/Config'; | ||
29 | import { Disposer, getLogger } from '../../utils'; | ||
30 | |||
31 | const log = getLogger('configPersistence'); | ||
32 | |||
33 | export class ConfigPersistenceServiceImpl implements ConfigPersistenceService { | ||
34 | private readonly configFilePath: string; | ||
35 | |||
36 | private writingConfig = false; | ||
37 | |||
38 | private timeLastWritten: Date | null = null; | ||
39 | |||
40 | constructor( | ||
41 | private readonly userDataDir: string, | ||
42 | private readonly configFileName: string = 'config.json5', | ||
43 | ) { | ||
44 | this.configFileName = configFileName; | ||
45 | this.configFilePath = join(this.userDataDir, this.configFileName); | ||
46 | } | ||
47 | |||
48 | async readConfig(): Promise<ReadConfigResult> { | ||
49 | let configStr; | ||
50 | try { | ||
51 | configStr = await readFile(this.configFilePath, 'utf8'); | ||
52 | } catch (err) { | ||
53 | if ((err as NodeJS.ErrnoException).code === 'ENOENT') { | ||
54 | log.debug('Config file', this.configFilePath, 'was not found'); | ||
55 | return { found: false }; | ||
56 | } | ||
57 | throw err; | ||
58 | } | ||
59 | log.info('Read config file', this.configFilePath); | ||
60 | return { | ||
61 | found: true, | ||
62 | data: JSON5.parse(configStr), | ||
63 | }; | ||
64 | } | ||
65 | |||
66 | async writeConfig(configSnapshot: ConfigSnapshotOut): Promise<void> { | ||
67 | const configJson = JSON5.stringify(configSnapshot, { | ||
68 | space: 2, | ||
69 | }); | ||
70 | this.writingConfig = true; | ||
71 | try { | ||
72 | await writeFile(this.configFilePath, configJson, 'utf8'); | ||
73 | const { mtime } = await stat(this.configFilePath); | ||
74 | log.trace('Config file', this.configFilePath, 'last written at', mtime); | ||
75 | this.timeLastWritten = mtime; | ||
76 | } finally { | ||
77 | this.writingConfig = false; | ||
78 | } | ||
79 | log.info('Wrote config file', this.configFilePath); | ||
80 | } | ||
81 | |||
82 | watchConfig(callback: () => Promise<void>, throttleMs: number): Disposer { | ||
83 | log.debug('Installing watcher for', this.userDataDir); | ||
84 | |||
85 | const configChanged = throttle(async () => { | ||
86 | let mtime: Date; | ||
87 | try { | ||
88 | const stats = await stat(this.configFilePath); | ||
89 | mtime = stats.mtime; | ||
90 | log.trace('Config file last modified at', mtime); | ||
91 | } catch (err) { | ||
92 | if ((err as NodeJS.ErrnoException).code === 'ENOENT') { | ||
93 | log.debug('Config file', this.configFilePath, 'was deleted after being changed'); | ||
94 | return; | ||
95 | } | ||
96 | throw err; | ||
97 | } | ||
98 | if (!this.writingConfig | ||
99 | && (this.timeLastWritten === null || mtime > this.timeLastWritten)) { | ||
100 | log.debug( | ||
101 | 'Found a config file modified at', | ||
102 | mtime, | ||
103 | 'whish is newer than last written', | ||
104 | this.timeLastWritten, | ||
105 | ); | ||
106 | return callback(); | ||
107 | } | ||
108 | }, throttleMs); | ||
109 | |||
110 | const watcher = watch(this.userDataDir, { | ||
111 | persistent: false, | ||
112 | }); | ||
113 | |||
114 | watcher.on('change', (eventType, filename) => { | ||
115 | if (eventType === 'change' | ||
116 | && (filename === this.configFileName || filename === null)) { | ||
117 | configChanged()?.catch((err) => { | ||
118 | console.log('Unhandled error while listening for config changes', err); | ||
119 | }); | ||
120 | } | ||
121 | }); | ||
122 | |||
123 | return () => { | ||
124 | log.trace('Removing watcher for', this.configFilePath); | ||
125 | watcher.close(); | ||
126 | }; | ||
127 | } | ||
128 | } | ||
diff --git a/packages/main/src/utils/index.ts b/packages/main/src/utils/index.ts index 9a57e02..2b85989 100644 --- a/packages/main/src/utils/index.ts +++ b/packages/main/src/utils/index.ts | |||
@@ -22,4 +22,4 @@ import { IDisposer } from 'mobx-state-tree'; | |||
22 | 22 | ||
23 | export type Disposer = IDisposer; | 23 | export type Disposer = IDisposer; |
24 | 24 | ||
25 | export { getLogger } from './logging'; | 25 | export { getLogger, silenceLogger } from './logging'; |
diff --git a/packages/main/src/utils/logging.ts b/packages/main/src/utils/logging.ts index 6c4cba2..ed40365 100644 --- a/packages/main/src/utils/logging.ts +++ b/packages/main/src/utils/logging.ts | |||
@@ -18,17 +18,17 @@ | |||
18 | * SPDX-License-Identifier: AGPL-3.0-only | 18 | * SPDX-License-Identifier: AGPL-3.0-only |
19 | */ | 19 | */ |
20 | 20 | ||
21 | import chalk, { ChalkInstance } from 'chalk'; | 21 | import chalk, { Chalk } from 'chalk'; |
22 | import loglevel, { Logger } from 'loglevel'; | 22 | import loglevel, { Logger } from 'loglevel'; |
23 | import prefix from 'loglevel-plugin-prefix'; | 23 | import prefix from 'loglevel-plugin-prefix'; |
24 | 24 | ||
25 | if (import.meta.env.DEV) { | 25 | if (import.meta.env?.DEV) { |
26 | loglevel.setLevel('debug'); | 26 | loglevel.setLevel('debug'); |
27 | } else { | 27 | } else { |
28 | loglevel.setLevel('info'); | 28 | loglevel.setLevel('info'); |
29 | } | 29 | } |
30 | 30 | ||
31 | const COLORS: Partial<Record<string, ChalkInstance>> = { | 31 | const COLORS: Partial<Record<string, Chalk>> = { |
32 | TRACE: chalk.magenta, | 32 | TRACE: chalk.magenta, |
33 | DEBUG: chalk.cyan, | 33 | DEBUG: chalk.cyan, |
34 | INFO: chalk.blue, | 34 | INFO: chalk.blue, |
@@ -37,7 +37,7 @@ const COLORS: Partial<Record<string, ChalkInstance>> = { | |||
37 | CRITICAL: chalk.red, | 37 | CRITICAL: chalk.red, |
38 | }; | 38 | }; |
39 | 39 | ||
40 | function getColor(level: string): ChalkInstance { | 40 | function getColor(level: string): Chalk { |
41 | return COLORS[level] ?? chalk.gray; | 41 | return COLORS[level] ?? chalk.gray; |
42 | } | 42 | } |
43 | 43 | ||
@@ -52,3 +52,11 @@ prefix.apply(loglevel, { | |||
52 | export function getLogger(loggerName: string): Logger { | 52 | export function getLogger(loggerName: string): Logger { |
53 | return loglevel.getLogger(loggerName); | 53 | return loglevel.getLogger(loggerName); |
54 | } | 54 | } |
55 | |||
56 | export function silenceLogger(): void { | ||
57 | loglevel.disableAll(); | ||
58 | const loggers = loglevel.getLoggers(); | ||
59 | for (const loggerName of Object.keys(loggers)) { | ||
60 | loggers[loggerName].disableAll(); | ||
61 | } | ||
62 | } | ||
diff --git a/packages/main/tsconfig.json b/packages/main/tsconfig.json index 10f5765..1401445 100644 --- a/packages/main/tsconfig.json +++ b/packages/main/tsconfig.json | |||
@@ -3,6 +3,7 @@ | |||
3 | "compilerOptions": { | 3 | "compilerOptions": { |
4 | "noEmit": true, | 4 | "noEmit": true, |
5 | "types": [ | 5 | "types": [ |
6 | "@types/jest", | ||
6 | "node" | 7 | "node" |
7 | ] | 8 | ] |
8 | }, | 9 | }, |