-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathAppSettingsService.cs
More file actions
291 lines (249 loc) · 11 KB
/
Copy pathAppSettingsService.cs
File metadata and controls
291 lines (249 loc) · 11 KB
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
290
291
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PlanViewer.App.Services;
/// <summary>
/// Persists recent plans and open session state to a JSON file in the app's local data directory.
/// </summary>
internal sealed class AppSettingsService
{
private const int MaxRecentPlans = 10;
private static readonly string SettingsDir;
private static readonly string SettingsPath;
private static readonly string OldFormatSettingsPath;
private static AppSettings? _cached;
static AppSettingsService()
{
SettingsDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"PerformanceStudio");
SettingsPath = Path.Combine(SettingsDir, "appsettings.json");
OldFormatSettingsPath = Path.Combine(SettingsDir, "perfstudio_format_settings.json");
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
/// <summary>
/// Options used by <see cref="AppSettings.Clone"/> — includes nulls so the roundtrip is lossless.
/// </summary>
internal static readonly JsonSerializerOptions CloneOptions = new()
{
WriteIndented = false,
DefaultIgnoreCondition = JsonIgnoreCondition.Never
};
/// <summary>
/// Loads settings from disk. Returns default settings if the file is missing or corrupt.
/// Migrates legacy format settings from the old standalone file if present.
/// </summary>
/// <remarks>
/// Returns the in-process cached instance — callers must not mutate it. Use
/// <see cref="AppSettings.Clone"/> if you need an editable copy, or <see cref="Save"/>
/// to persist new state (which also refreshes the cache).
/// </remarks>
public static AppSettings Load()
{
if (_cached != null)
return _cached;
try
{
AppSettings settings;
if (!File.Exists(SettingsPath))
settings = new AppSettings();
else
{
var json = File.ReadAllText(SettingsPath);
settings = JsonSerializer.Deserialize<AppSettings>(json, JsonOptions) ?? new AppSettings();
}
// Migrate legacy format settings file into unified settings
MigrateFormatSettings(settings);
// Clamp numeric values to valid ranges
settings.QueryStoreSlicerDays = Math.Clamp(settings.QueryStoreSlicerDays, 1, 365);
settings.QueryStoreTopLimit = Math.Clamp(settings.QueryStoreTopLimit, 1, 200);
settings.MultiQsTopDbCount = Math.Clamp(settings.MultiQsTopDbCount, 2, 20);
settings.QueryHistoryMaxPlans = Math.Clamp(settings.QueryHistoryMaxPlans, 1, 100);
_cached = settings;
return settings;
}
catch (Exception ex)
{
Debug.WriteLine($"AppSettings: failed to load settings: {ex.Message}");
return new AppSettings();
}
}
/// <summary>
/// Clears the in-process settings cache so the next <see cref="Load"/> re-reads from disk.
/// </summary>
public static void Invalidate() => _cached = null;
/// <summary>
/// Saves settings to disk. Silently ignores write failures.
/// </summary>
public static void Save(AppSettings settings)
{
try
{
Directory.CreateDirectory(SettingsDir);
var json = JsonSerializer.Serialize(settings, JsonOptions);
AtomicFile.WriteAllText(SettingsPath, json);
_cached = settings;
}
catch
{
// Best-effort persistence — don't crash the app
}
}
/// <summary>
/// If the old perfstudio_format_settings.json exists, migrate it into AppSettings
/// (when FormatOptions is not yet set) and delete the old file unconditionally.
/// Note: this intentionally calls <see cref="Save"/> inside <see cref="Load"/> as a
/// one-time migration step. If Save fails, the old file remains and migration retries
/// on the next Load — acceptable because the window is small and self-healing.
/// </summary>
private static void MigrateFormatSettings(AppSettings settings)
{
try
{
if (!File.Exists(OldFormatSettingsPath))
return;
if (settings.FormatOptions == null)
{
var json = File.ReadAllText(OldFormatSettingsPath);
var legacy = JsonSerializer.Deserialize<SqlFormatSettings>(json, JsonOptions);
if (legacy != null)
{
settings.FormatOptions = legacy;
Save(settings);
}
}
// Delete the old file whether we migrated or FormatOptions was already set
File.Delete(OldFormatSettingsPath);
}
catch (Exception ex)
{
Debug.WriteLine($"AppSettingsService: failed to migrate format settings: {ex.Message}");
}
}
/// <summary>
/// Adds a file path to the recent plans list (most recent first).
/// Deduplicates by full path (case-insensitive on Windows).
/// </summary>
public static void AddRecentPlan(AppSettings settings, string filePath)
{
var fullPath = Path.GetFullPath(filePath);
// Remove any existing entry for this path
settings.RecentPlans.RemoveAll(p =>
string.Equals(p, fullPath, StringComparison.OrdinalIgnoreCase));
// Insert at the front
settings.RecentPlans.Insert(0, fullPath);
// Trim to max size
if (settings.RecentPlans.Count > MaxRecentPlans)
settings.RecentPlans.RemoveRange(MaxRecentPlans, settings.RecentPlans.Count - MaxRecentPlans);
}
/// <summary>
/// Removes a specific path from the recent plans list.
/// </summary>
public static void RemoveRecentPlan(AppSettings settings, string filePath)
{
settings.RecentPlans.RemoveAll(p =>
string.Equals(p, filePath, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Default color palette for Multi QS Overview top databases.
/// </summary>
internal static readonly List<string> DefaultTopDbColors = new()
{
"#2EAEF1", "#F2994A", "#27AE60", "#9B51E0", "#EB5757",
"#F2C94C", "#56CCF2", "#BB6BD9", "#E91E63", "#00BCD4",
};
}
/// <summary>
/// Serializable settings model for the application.
/// </summary>
internal sealed class AppSettings
{
// ── App State ────────────────────────────────────────────────────
[JsonPropertyName("recent_plans")]
public List<string> RecentPlans { get; set; } = new();
[JsonPropertyName("open_plans")]
public List<string> OpenPlans { get; set; } = new();
/// <summary>
/// Divergence limit for accuracy ratio coloring on plan links. Default 10.
/// Links with accuracy ratio between 1/limit and limit keep the default edge color.
/// </summary>
[JsonPropertyName("accuracy_ratio_divergence_limit")]
public double AccuracyRatioDivergenceLimit { get; set; } = 10;
// ── Query Store Settings ─────────────────────────────────────────
/// <summary>
/// Number of days of Query Store data to load in the time-range slicer. Default 30.
/// </summary>
[JsonPropertyName("query_store_slicer_days")]
public int QueryStoreSlicerDays { get; set; } = 30;
/// <summary>
/// Default metric for the top queries grid. Default "cpu" (= Total CPU).
/// Values: cpu, avg-cpu, duration, avg-duration, reads, avg-reads,
/// writes, avg-writes, physical-reads, avg-physical-reads, memory, avg-memory, executions.
/// </summary>
[JsonPropertyName("query_store_default_metric")]
public string QueryStoreDefaultMetric { get; set; } = "cpu";
/// <summary>
/// Default number of top elements/groups shown in the grid. Default 25.
/// </summary>
[JsonPropertyName("query_store_top_limit")]
public int QueryStoreTopLimit { get; set; } = 25;
/// <summary>
/// Default time range quick-filter selection (hours as string).
/// Options: "3" (3h), "24" (24h), "48" (48h), "168" (7d), "720" (30d).
/// </summary>
[JsonPropertyName("query_store_default_time_range")]
public string QueryStoreDefaultTimeRange { get; set; } = "24";
/// <summary>
/// Default time display mode: "Local", "Utc", or "Server".
/// </summary>
[JsonPropertyName("query_store_default_time_display")]
public string QueryStoreDefaultTimeDisplay { get; set; } = "Local";
/// <summary>
/// Default group-by mode: "None", "QueryHash", or "Module".
/// </summary>
[JsonPropertyName("query_store_default_group_by")]
public string QueryStoreDefaultGroupBy { get; set; } = "QueryHash";
// ── Multi QS Overview Settings ───────────────────────────────────
/// <summary>
/// Number of top databases shown in the overview. Default 5, min 2, max 20.
/// </summary>
[JsonPropertyName("multi_qs_top_db_count")]
public int MultiQsTopDbCount { get; set; } = 5;
/// <summary>
/// Hex color codes for top databases in the overview chart.
/// </summary>
[JsonPropertyName("multi_qs_top_db_colors")]
public List<string> MultiQsTopDbColors { get; set; } = new(AppSettingsService.DefaultTopDbColors);
// ── Query History Settings ───────────────────────────────────────
/// <summary>
/// Default metric for the query history chart. Default "AvgDurationMs".
/// </summary>
[JsonPropertyName("query_history_default_metric")]
public string QueryHistoryDefaultMetric { get; set; } = "AvgDurationMs";
/// <summary>
/// Maximum number of plans fetched for a query history. Default 10, min 1, max 100.
/// </summary>
[JsonPropertyName("query_history_max_plans")]
public int QueryHistoryMaxPlans { get; set; } = 10;
// ── Script Options (Format) ──────────────────────────────────────
/// <summary>
/// SQL format options. Null means use <see cref="SqlFormatSettings"/> defaults.
/// </summary>
[JsonPropertyName("format_options")]
public SqlFormatSettings? FormatOptions { get; set; }
/// <summary>
/// Creates a deep copy via JSON roundtrip so mutations don't leak to callers.
/// </summary>
internal AppSettings Clone()
{
var json = JsonSerializer.Serialize(this, AppSettingsService.CloneOptions);
return JsonSerializer.Deserialize<AppSettings>(json, AppSettingsService.CloneOptions) ?? new AppSettings();
}
}