aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/reactions/synchronizeConfig.ts
blob: 6044ee7770f92dc5449f88a638f12f55d9895b17 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
 * Copyright (C)  2021-2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { debounce } from 'lodash-es';
import { reaction } from 'mobx';

import type ConfigRepository from '../infrastructure/config/ConfigRepository.js';
import type SharedStore from '../stores/SharedStore.js';
import type Config from '../stores/config/Config.js';
import type Disposer from '../utils/Disposer.js';
import getLogger from '../utils/getLogger.js';

const DEFAULT_CONFIG_DEBOUNCE_TIME_MS = 1000;

const log = getLogger('synchronizeConfig');

export function serializeConfig(config: Config): string {
  return `${JSON.stringify(config, undefined, 2)}\n`;
}

export default async function synchronizeConfig(
  sharedStore: SharedStore,
  repository: ConfigRepository,
  debounceTime: number = DEFAULT_CONFIG_DEBOUNCE_TIME_MS,
): Promise<Disposer> {
  let lastConfigOnDisk: string | undefined;

  async function writeConfig(serializedConfig: string): Promise<void> {
    await repository.writeConfig(serializedConfig);
    lastConfigOnDisk = serializedConfig;
  }

  async function readConfig(): Promise<boolean> {
    const result = await repository.readConfig();
    if (result.found) {
      const { contents } = result;
      if (contents === lastConfigOnDisk) {
        // No need to re-apply config if we have already applied it.
        return true;
      }
      try {
        // This cast is unsound if the config file is invalid,
        // but we'll throw an error in the end anyways.
        const data = JSON.parse(contents) as Config;
        sharedStore.loadConfig(data);
        log.info('Loaded config');
      } catch (error) {
        log.error('Failed to apply config snapshot', contents, error);
        return true;
      }
      lastConfigOnDisk = serializeConfig(sharedStore.config);
      if (contents !== lastConfigOnDisk) {
        await writeConfig(lastConfigOnDisk);
      }
    }
    return result.found;
  }

  if (!(await readConfig())) {
    log.info('Config file was not found');
    const serializedConfig = serializeConfig(sharedStore.config);
    await writeConfig(serializedConfig);
    log.info('Created config file');
  }

  const debouncedSerializeConfig = debounce(() => {
    const serializedConfig = serializeConfig(sharedStore.config);
    if (serializedConfig !== lastConfigOnDisk) {
      writeConfig(serializedConfig).catch((error) => {
        log.error('Failed to write config on config change', error);
      });
    }
  }, debounceTime);

  const disposeReaction = reaction(
    () => sharedStore.config,
    debouncedSerializeConfig,
  );

  const disposeWatcher = repository.watchConfig(async () => {
    try {
      await readConfig();
    } catch (error) {
      log.error('Failed to read config', error);
    }
  });

  return () => {
    disposeWatcher();
    disposeReaction();
    debouncedSerializeConfig.flush();
  };
}