aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/infrastructure/config/impl/__tests__/ConfigFile.integ.test.ts
blob: c443d99b428828caff4a790d0502f72f171916dd (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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
 * Copyright (C)  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 {
  chmod,
  mkdir,
  mkdtemp,
  readFile,
  rename,
  rm,
  stat,
  utimes,
  writeFile,
} from 'node:fs/promises';
import { platform, tmpdir, userInfo } from 'node:os';
import path from 'node:path';

import { jest } from '@jest/globals';
import { testIf } from '@sophie/test-utils';
import { mocked } from 'jest-mock';

import Disposer from '../../../../utils/Disposer.js';
import ConfigFile, { CONFIG_FILE_NAME } from '../ConfigFile.js';

const CONFIG_CHANGE_DEBOUNCE_MS = 10;

let filesystemDelay = 100;
let realSetTimeout: typeof setTimeout;
let userDataDir: string | undefined;
let configFilePath: string;
let repository: ConfigFile;

async function realDelay(ms: number): Promise<void> {
  return new Promise<void>((resolve) => {
    realSetTimeout(() => resolve(), ms);
  });
}

/**
 * Wait for a short (real-time) delay to let node be notified of file changes.
 *
 * Use the `SOPHIE_INTEG_TEST_DELAY` environmental variable to customize the delay
 * (e.g., quicker test execution on faster computers or longer wait time in CI).
 * The default delay is 100 ms, but as little as 10 ms might be enough, depending on your system.
 *
 * @param ms The time that should elapse after noticing the filesystem change.
 * @returns A promise that resolves in a `filesystemDelay` ms.
 */
async function catchUpWithFilesystem(
  ms = CONFIG_CHANGE_DEBOUNCE_MS,
): Promise<void> {
  await realDelay(filesystemDelay);
  jest.advanceTimersByTime(ms);
  // Some extra real time is needed after advancing the timer to make sure the callback runs.
  await realDelay(Math.max(filesystemDelay / 10, 1));
}

beforeAll(() => {
  const delayEnv = process.env.SOPHIE_INTEG_TEST_DELAY;
  if (delayEnv !== undefined) {
    filesystemDelay = Number.parseInt(delayEnv, 10);
  }
  jest.useRealTimers();
  // Save the real implementation of `setTimeout` before we mock it.
  realSetTimeout = setTimeout;
  jest.useFakeTimers();
});

beforeEach(async () => {
  try {
    userDataDir = await mkdtemp(path.join(tmpdir(), 'sophie-configFile-'));
    configFilePath = path.join(userDataDir, CONFIG_FILE_NAME);
    repository = new ConfigFile(
      userDataDir,
      CONFIG_FILE_NAME,
      CONFIG_CHANGE_DEBOUNCE_MS,
    );
  } catch (error) {
    userDataDir = undefined;
    throw error;
  }
});

afterEach(async () => {
  jest.clearAllTimers();
  if (userDataDir === undefined) {
    return;
  }
  if (!userDataDir.startsWith(tmpdir())) {
    throw new Error(
      `Refusing to delete directory ${userDataDir} outside of tmp directory`,
    );
  }
  await rm(userDataDir, {
    force: true,
    recursive: true,
  });
  userDataDir = undefined;
});

describe('readConfig', () => {
  test('returns false when the config file is not found', async () => {
    const result = await repository.readConfig();
    expect(result.found).toBe(false);
  });

  test('reads the contents of the config file if found', async () => {
    await writeFile(configFilePath, 'Hello World!', 'utf8');
    const result = await repository.readConfig();
    expect(result.found).toBe(true);
    expect(result).toHaveProperty('contents', 'Hello World!');
  });

  test('throws an error if the config file cannot be read', async () => {
    await mkdir(configFilePath);
    await expect(repository.readConfig()).rejects.toThrow();
  });
});

describe('writeConfig', () => {
  test('writes the config file', async () => {
    await repository.writeConfig('Hi Mars!');
    const contents = await readFile(configFilePath, 'utf8');
    expect(contents).toBe('Hi Mars!');
  });

  test('overwrites the config file', async () => {
    await writeFile(configFilePath, 'Hello World!', 'utf8');
    await repository.writeConfig('Hi Mars!');
    const contents = await readFile(configFilePath, 'utf8');
    expect(contents).toBe('Hi Mars!');
  });

  test('throws an error if the config file cannot be written', async () => {
    await mkdir(configFilePath);
    await expect(repository.writeConfig('Hi Mars!')).rejects.toThrow();
  });

  test('throws an error when called reentrantly', async () => {
    const promise = repository.writeConfig('Hello World!');
    try {
      await expect(repository.writeConfig('Hi Mars!')).rejects.toThrow();
    } finally {
      await promise;
    }
  });
});

describe('watchConfig', () => {
  let callback: () => Promise<void>;
  let watcher: Disposer | undefined;

  beforeEach(() => {
    callback = jest.fn(() => Promise.resolve());
  });

  afterEach(() => {
    if (watcher !== undefined) {
      // Make sure we dispose the watcher.
      watcher();
    }
  });

  describe('when the config file does not exist', () => {
    beforeEach(() => {
      watcher = repository.watchConfig(callback);
    });

    test('notifies when the config file is created externally', async () => {
      await writeFile(configFilePath, 'Hello World!', 'utf8');
      await catchUpWithFilesystem();
      expect(callback).toHaveBeenCalled();
    });

    test('does not notify when the config file is created by the repository', async () => {
      await repository.writeConfig('Hello World!');
      await catchUpWithFilesystem();
      expect(callback).not.toHaveBeenCalled();
    });
  });

  describe('when the config file already exists', () => {
    beforeEach(async () => {
      await writeFile(configFilePath, 'Hello World!', 'utf8');
      watcher = repository.watchConfig(callback);
    });

    test('notifies when the config file is updated externally', async () => {
      await writeFile(configFilePath, 'Hi Mars!', 'utf8');
      await catchUpWithFilesystem();
      expect(callback).toHaveBeenCalled();
    });

    test('does not notify when the config file is created by the repository', async () => {
      await repository.writeConfig('Hi Mars!');
      await catchUpWithFilesystem();
      expect(callback).not.toHaveBeenCalled();
    });

    test('debounces changes to the config file', async () => {
      await writeFile(configFilePath, 'Hi Mars!', 'utf8');
      await catchUpWithFilesystem(5);
      expect(callback).not.toHaveBeenCalled();

      await writeFile(configFilePath, 'Hi Mars!', 'utf8');
      await catchUpWithFilesystem();
      expect(callback).toHaveBeenCalledTimes(1);
    });

    test('handles the config file being deleted', async () => {
      await rm(configFilePath);
      await catchUpWithFilesystem();
      expect(callback).not.toHaveBeenCalled();

      await writeFile(configFilePath, 'Hello World!', 'utf8');
      await catchUpWithFilesystem();
      expect(callback).toHaveBeenCalled();
    });

    test('handles the config file being renamed', async () => {
      const renamedPath = `${configFilePath}.renamed`;

      await rename(configFilePath, renamedPath);
      await catchUpWithFilesystem();
      expect(callback).not.toHaveBeenCalled();

      await writeFile(renamedPath, 'Hello World!', 'utf8');
      await catchUpWithFilesystem();
      expect(callback).not.toHaveBeenCalled();

      await writeFile(configFilePath, 'Hello World!', 'utf8');
      await catchUpWithFilesystem();
      expect(callback).toHaveBeenCalled();
    });

    // We can only cause a filesystem error by changing permissions if we run on a POSIX-like
    // system and we aren't root (i.e., not in CI).
    testIf(platform() !== 'win32' && userInfo().uid !== 0)(
      'handles other filesystem errors',
      async () => {
        const { mode } = await stat(userDataDir!);
        await writeFile(configFilePath, 'Hi Mars!', 'utf8');
        // Remove permission to force a filesystem error.
        // eslint-disable-next-line no-bitwise -- Compute reduced permissions.
        await chmod(userDataDir!, mode & 0o666);
        try {
          await catchUpWithFilesystem();
          expect(callback).not.toHaveBeenCalled();
        } finally {
          await chmod(userDataDir!, mode);
        }
      },
    );

    test('does not notify when the modification date is prior to the last write', async () => {
      await repository.writeConfig('Hello World!');
      const date = new Date(Date.now() - 3_600_000);
      await utimes(configFilePath, date, date);
      await catchUpWithFilesystem();
      expect(callback).not.toHaveBeenCalled();
    });

    test('handles callback errors', async () => {
      mocked(callback).mockRejectedValue(new Error('Test error'));
      await writeFile(configFilePath, 'Hi Mars!', 'utf8');
      await catchUpWithFilesystem();
      // This test would fail an unhandled promise rejection error if `ConfigFile`
      // did not handle the rejection properly.
      expect(callback).toHaveBeenCalled();
    });
  });
});