aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/infrastructure/config/impl/ConfigFile.ts
blob: 8f0cc3f98faba43511b52f40e4ef24655b10f663 (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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
/*
 * 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 { watch } from 'node:fs';
import { readFile, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';

import { debounce } from 'lodash-es';

import type Disposer from '../../../utils/Disposer.js';
import getLogger from '../../../utils/getLogger.js';
import isErrno from '../../../utils/isErrno.js';
import type ConfigRepository from '../ConfigRepository.js';
import type { ReadConfigResult } from '../ConfigRepository.js';

const log = getLogger('ConfigFile');

export const CONFIG_FILE_NAME = 'settings.json';
export const DEFAULT_CONFIG_CHANGE_DEBOUNCE_MS = 10;

export default class ConfigFile implements ConfigRepository {
  private readonly configFilePath: string;

  private writingConfig = false;

  private timeLastWritten: Date | undefined;

  constructor(
    private readonly userDataDir: string,
    private readonly configFileName = CONFIG_FILE_NAME,
    private readonly debounceTime = DEFAULT_CONFIG_CHANGE_DEBOUNCE_MS,
  ) {
    this.configFilePath = path.join(userDataDir, configFileName);
  }

  async readConfig(): Promise<ReadConfigResult> {
    let contents: string;
    try {
      contents = await readFile(this.configFilePath, 'utf8');
    } catch (error) {
      if (isErrno(error, 'ENOENT')) {
        log.debug('Config file', this.configFilePath, 'was not found');
        return { found: false };
      }
      throw error;
    }
    log.debug('Read config file', this.configFilePath);
    return {
      found: true,
      contents,
    };
  }

  async writeConfig(contents: string): Promise<void> {
    if (this.writingConfig) {
      throw new Error('writeConfig cannot be called reentrantly');
    }
    this.writingConfig = true;
    try {
      await writeFile(this.configFilePath, contents, 'utf8');
      const { mtime } = await stat(this.configFilePath);
      log.trace('Config file', this.configFilePath, 'last written at', mtime);
      this.timeLastWritten = mtime;
    } finally {
      this.writingConfig = false;
    }
    log.debug('Wrote config file', this.configFilePath);
  }

  watchConfig(callback: () => Promise<void>): Disposer {
    log.debug('Installing watcher for', this.userDataDir);

    const configChanged = debounce(async () => {
      let mtime: Date;
      try {
        const stats = await stat(this.configFilePath);
        mtime = stats.mtime;
        log.trace('Config file last modified at', mtime);
      } catch (error) {
        if (isErrno(error, 'ENOENT')) {
          log.debug(
            'Config file',
            this.configFilePath,
            'was deleted after being changed',
          );
          return;
        }
        log.error(
          'Unexpected error while listening for config file changes',
          error,
        );
        return;
      }
      if (
        !this.writingConfig &&
        (this.timeLastWritten === undefined || mtime > this.timeLastWritten)
      ) {
        log.debug(
          'Found a config file modified at',
          mtime,
          'which is newer than last written',
          this.timeLastWritten,
        );
        try {
          await callback();
        } catch (error) {
          log.error('Callback error while listening for config changes', error);
        }
      }
    }, this.debounceTime);

    const watcher = watch(
      this.userDataDir,
      {
        persistent: false,
        recursive: false,
      },
      (_eventType, filename) => {
        // We handle both `rename` and `change` events for maximum portability.
        // This may result in multiple calls to `configChanged` for a single config change,
        // so we debounce it with a short (imperceptible) delay.
        if (filename === this.configFileName || filename === null) {
          configChanged()?.catch((err) => {
            // This should never happen, because `configChanged` handles all exceptions.
            log.error(
              'Unhandled error while listening for config changes',
              err,
            );
          });
        }
      },
    );

    return () => {
      log.trace('Removing watcher for', this.configFilePath);
      watcher.close();
      configChanged.cancel();
    };
  }
}