summaryrefslogtreecommitdiff
path: root/server/lib/core/settings_store.dart
blob: 520ed97bc69959c3feace3ce02dced256a3eaebb (plain)
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
import 'dart:io';

import 'package:path/path.dart' as p;

/// Persistent store for the server settings JSON (Phase 6: the settings
/// split). Same contract as [SaveStore]: the server changes a setting, and
/// "written through on every change" must be on disk when [write] returns.
abstract class SettingsStore {
  /// Returns the stored settings JSON, or null if nothing has been saved yet.
  String? read();

  /// Writes the settings JSON.
  void write(String data);

  /// Removes the stored settings.
  void clear();
}

/// In-memory [SettingsStore] — used by tests.
class InMemorySettingsStore implements SettingsStore {
  String? _data;

  @override
  String? read() => _data;

  @override
  void write(String data) => _data = data;

  @override
  void clear() => _data = null;
}

/// File-backed [SettingsStore] writing one JSON document into [directory].
class FileSettingsStore implements SettingsStore {
  final File _file;

  FileSettingsStore(String directory)
    : _file = File(p.join(directory, 'settings.json'));

  @override
  String? read() => _file.existsSync() ? _file.readAsStringSync() : null;

  @override
  void write(String data) {
    final dir = _file.parent;
    if (!dir.existsSync()) dir.createSync(recursive: true);
    // Synchronous write: the same kill −9 race the save store had — the
    // settings must be on disk when [write] returns.
    _file.writeAsStringSync(data, flush: true);
  }

  @override
  void clear() {
    if (_file.existsSync()) _file.deleteSync();
  }
}