Skip to content

Commit

Permalink
Debounce config saving
Browse files Browse the repository at this point in the history
  • Loading branch information
LucHeart committed Jul 23, 2024
1 parent 3922a63 commit 29eba35
Show file tree
Hide file tree
Showing 11 changed files with 59 additions and 51 deletions.
33 changes: 20 additions & 13 deletions ShockOsc/Config/ConfigManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,23 @@ namespace OpenShock.ShockOsc.Config;

public sealed class ConfigManager
{
private static readonly string Path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\OpenShock\ShockOSC\config.json";

private static readonly string Path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
@"\OpenShock\ShockOSC\config.json";

private readonly ILogger<ConfigManager> _logger;
public ShockOscConfig Config { get; }

private readonly Timer _saveTimer;

public ConfigManager(ILogger<ConfigManager> logger)
{
_logger = logger;

_saveTimer = new Timer(_ => { OsTask.Run(SaveInternally); });

// Load config
ShockOscConfig? config = null;

_logger.LogInformation("Config file found, trying to load config from {Path}", Path);
if (File.Exists(Path))
{
Expand Down Expand Up @@ -47,9 +52,11 @@ public ConfigManager(ILogger<ConfigManager> logger)
_logger.LogInformation("Successfully loaded config");
return;
}
_logger.LogInformation("No config file found (does not exist or empty or invalid), generating new one at {Path}", Path);

_logger.LogInformation(
"No config file found (does not exist or empty or invalid), generating new one at {Path}", Path);
Config = new ShockOscConfig();
SaveAsync().Wait();
SaveInternally().Wait();
_logger.LogInformation("New configuration file generated!");
}

Expand All @@ -58,10 +65,10 @@ public ConfigManager(ILogger<ConfigManager> logger)
WriteIndented = true,
Converters = { new JsonStringEnumConverter(), new SemVersionJsonConverter() }
};

private readonly SemaphoreSlim _saveLock = new(1, 1);

public async Task SaveAsync()
private async Task SaveInternally()
{
await _saveLock.WaitAsync().ConfigureAwait(false);
try
Expand All @@ -70,14 +77,14 @@ public async Task SaveAsync()
var directory = System.IO.Path.GetDirectoryName(Path);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);

await File.WriteAllTextAsync(Path, JsonSerializer.Serialize(Config, Options)).ConfigureAwait(false);
_logger.LogInformation("Config saved");
}
catch (Exception e)
{
_logger.LogError(e, "Error occurred while saving new config file");
}
}
finally
{
_saveLock.Release();
Expand All @@ -86,9 +93,9 @@ public async Task SaveAsync()

public void Save()
{
SaveAsync().Wait();
lock (_saveTimer)
{
_saveTimer.Change(TimeSpan.FromSeconds(1), Timeout.InfiniteTimeSpan);
}
}

public void SaveFnf() => OsTask.Run(SaveAsync);

}
2 changes: 1 addition & 1 deletion ShockOsc/Services/AuthService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public async Task Logout()
Authenticated = false;

_configManager.Config.OpenShock.Token = string.Empty;
await _configManager.SaveAsync();
_configManager.Save();

_logger.LogInformation("Logging out");
await _hubClient.StopAsync();
Expand Down
20 changes: 10 additions & 10 deletions ShockOsc/Services/UnderscoreConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
{
if (_configManager.Config.Behaviour.RandomIntensity == modeIntensity) return;
_configManager.Config.Behaviour.RandomIntensity = modeIntensity;
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}
break;
Expand All @@ -95,7 +95,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
{
if(_configManager.Config.Behaviour.RandomDuration == modeDuration) return;
_configManager.Config.Behaviour.RandomDuration = modeDuration;
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}
break;
Expand All @@ -111,7 +111,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.FixedIntensity =
Math.Clamp((byte)Math.Round(intensityFloat * 100), (byte)0, (byte)100);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -128,7 +128,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.IntensityRange.Min =
MathUtils.ClampUint((uint)Math.Round(minIntensityFloat * 100), 0, 100);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -145,7 +145,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.IntensityRange.Max =
MathUtils.ClampUint((uint)Math.Round(maxIntensityFloat * 100), 0, 100);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -161,7 +161,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.DurationRange.Min =
MathUtils.ClampUint((uint)Math.Round(minDurationFloat * 10_000), 300, 30_000);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -177,7 +177,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.DurationRange.Max =
MathUtils.ClampUint((uint)Math.Round(maxDurationFloat * 10_000), 300, 30_000);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -193,7 +193,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.FixedDuration =
MathUtils.ClampUint((uint)Math.Round(durationFloat * 10_000), 300, 10_000);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -210,7 +210,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.CooldownTime =
MathUtils.ClampUint((uint)Math.Round(cooldownTimeFloat * 100000), 0, 100000);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand All @@ -226,7 +226,7 @@ private void HandleGlobalConfigCommand(string action, object? value)
_configManager.Config.Behaviour.HoldTime =
MathUtils.ClampUint((uint)Math.Round(holdTimeFloat * 1000), 0, 1000);
ValidateSettings();
_configManager.SaveFnf();
_configManager.Save();
OnConfigUpdate?.Invoke(); // update Ui
}

Expand Down
2 changes: 1 addition & 1 deletion ShockOsc/Ui/Pages/Authentication/Authenticate.razor
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
{
if (string.IsNullOrEmpty(PipeService.Token) || _currentState != State.Login) return false;
ConfigManager.Config.OpenShock.Token = PipeService.Token;
await ConfigManager.SaveAsync();
ConfigManager.Save();
PipeService.Token = null;
await ProceedAuthenticated();
return true;
Expand Down
2 changes: 1 addition & 1 deletion ShockOsc/Ui/Pages/Authentication/LoginPart.razor
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@

public async Task Login()
{
await ConfigManager.SaveAsync();
ConfigManager.Save();
await ProceedAuthenticated();
}

Expand Down
4 changes: 2 additions & 2 deletions ShockOsc/Ui/Pages/Dash/Components/UpdateDialog.razor
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
InvokeAsync(StateHasChanged);
}

private async Task Skip()
private void Skip()
{
ConfigManager.Config.App.LastIgnoredVersion = Updater.LatestVersion;
await ConfigManager.SaveAsync();
ConfigManager.Save();
MudDialog.Close(DialogResult.Ok(true));
}

Expand Down
6 changes: 3 additions & 3 deletions ShockOsc/Ui/Pages/Dash/Tabs/AppSettingsTab.razor
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@
InvokeAsync(StateHasChanged);
}

private async Task OnSettingsValueChange()
private void OnSettingsValueChange()
{
await ConfigManager.SaveAsync();
ConfigManager.Save();
}

private async Task UpdateChannelChanged()
{
await OnSettingsValueChange();
OnSettingsValueChange();
await Updater.CheckUpdate();
}

Expand Down
6 changes: 3 additions & 3 deletions ShockOsc/Ui/Pages/Dash/Tabs/ChatboxTab.razor
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<br/>
<MudCheckBox Class="option-width option-checkbox-height" @bind-Value="ConfigManager.Config.Chatbox.TimeoutEnabled" Label="Timeout (Clear) Chatbox Automatically"></MudCheckBox>
<br/>
<DebouncedSlider T="uint" Size="Size.Large" Min="1_300" Max="30_000" Step="100" Style="margin-left: 16px; width: 500px !important;" @bind-SliderValue="@ConfigManager.Config.Chatbox.Timeout" OnSaveAction="_ => ConfigManager.SaveFnf()">
<DebouncedSlider T="uint" Size="Size.Large" Min="1_300" Max="30_000" Step="100" Style="margin-left: 16px; width: 500px !important;" @bind-SliderValue="@ConfigManager.Config.Chatbox.Timeout" OnSaveAction="_ => ConfigManager.Save()">
Timeout: @MathF.Round(ConfigManager.Config.Chatbox.Timeout / 1000f, 1).ToString(CultureInfo.InvariantCulture)s
</DebouncedSlider>
</MudPaper>
Expand Down Expand Up @@ -61,9 +61,9 @@
@code {


private async Task OnSettingsValueChange()
private void OnSettingsValueChange()
{
await ConfigManager.SaveAsync();
ConfigManager.Save();
}

}
3 changes: 2 additions & 1 deletion ShockOsc/Ui/Pages/Dash/Tabs/ConfigTab.razor
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@

private Task OnSettingsValueChangeAsync()
{
return Task.WhenAll(ConfigManager.SaveAsync(), underscoreConfig.SendUpdateForAll());
ConfigManager.Save();
return underscoreConfig.SendUpdateForAll();
}

protected override void OnInitialized()
Expand Down
28 changes: 14 additions & 14 deletions ShockOsc/Ui/Pages/Dash/Tabs/GroupsTab.razor
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
Group = groupId;

await InvokeAsync(StateHasChanged);
await ConfigManager.SaveAsync();
ConfigManager.Save();
await ShockOsc.RaiseOnGroupsChanged();
}

Expand All @@ -41,17 +41,17 @@
ConfigManager.Config.Groups.Remove(Group.Value);
Group = null;
await InvokeAsync(StateHasChanged);
await ConfigManager.SaveAsync();
ConfigManager.Save();
await ShockOsc.RaiseOnGroupsChanged();
}

private async Task OnSettingsValueChange()
{
await ConfigManager.SaveAsync();
ConfigManager.Save();
await ShockOsc.RaiseOnGroupsChanged();
}

private Task OnGroupSettingsValueChange() => ConfigManager.SaveAsync();
private void OnGroupSettingsValueChange() => ConfigManager.Save();

private void OnGroupSelect()
{
Expand All @@ -60,12 +60,12 @@
InvokeAsync(StateHasChanged);
}

private async Task OnSelectedShockersUpdate()
private void OnSelectedShockersUpdate()
{
if (CurrentGroup != null)
{
CurrentGroup.Shockers = _selectedShockers.ToList();
await ConfigManager.SaveAsync();
ConfigManager.Save();
}
}

Expand Down Expand Up @@ -112,7 +112,7 @@
CurrentGroup.RandomIntensity = ConfigManager.Config.Behaviour.RandomIntensity;

await InvokeAsync(StateHasChanged);
await ConfigManager.SaveAsync();
ConfigManager.Save();
}

private async Task ResetDuration()
Expand All @@ -123,7 +123,7 @@
CurrentGroup.RandomDuration = ConfigManager.Config.Behaviour.RandomDuration;

await InvokeAsync(StateHasChanged);
await ConfigManager.SaveAsync();
ConfigManager.Save();
}

}
Expand Down Expand Up @@ -167,21 +167,21 @@
@if (!CurrentGroup.RandomIntensity)
{
<DebouncedSlider T="byte" Size="Size.Large" Min="0" Max="100" Class="openshock-slider-length" @bind-SliderValue="@CurrentGroup.FixedIntensity"
OnSaveAction="_ => ConfigManager.SaveFnf()">
OnSaveAction="_ => ConfigManager.Save()">
Intensity: @CurrentGroup.FixedIntensity%
</DebouncedSlider>
}
else
{
<DebouncedSlider T="uint" Size="Size.Large" Min="0" Max="100" Class="openshock-slider-length" @bind-SliderValue="@CurrentGroup.IntensityRange.Min"
OnValueChanged="u => { if (CurrentGroup.IntensityRange.Max < u) CurrentGroup.IntensityRange.Max = u; }"
OnSaveAction="_ => ConfigManager.SaveFnf()">
OnSaveAction="_ => ConfigManager.Save()">
Min Intensity: @CurrentGroup.IntensityRange.Min%
</DebouncedSlider>

<DebouncedSlider T="uint" Size="Size.Large" Min="0" Max="100" Class="openshock-slider-length" @bind-SliderValue="@CurrentGroup.IntensityRange.Max"
OnValueChanged="u => { if (CurrentGroup.IntensityRange.Min > u) CurrentGroup.IntensityRange.Min = u; }"
OnSaveAction="_ => ConfigManager.SaveFnf()">
OnSaveAction="_ => ConfigManager.Save()">
Max Intensity: @CurrentGroup.IntensityRange.Max%
</DebouncedSlider>
}
Expand All @@ -208,7 +208,7 @@
@if (!CurrentGroup.RandomDuration)
{
<DebouncedSlider T="uint" Size="Size.Large" Class="openshock-slider-length" @bind-SliderValue="@CurrentGroup.FixedDuration"
OnSaveAction="_ => ConfigManager.SaveFnf()"
OnSaveAction="_ => ConfigManager.Save()"
Min="300" Max="30000" Step="100">
Duration: @MathF.Round(CurrentGroup.FixedDuration / 1000f, 1).ToString(CultureInfo.InvariantCulture)s
</DebouncedSlider>
Expand All @@ -217,14 +217,14 @@
{
<DebouncedSlider T="uint" Size="Size.Large" Class="openshock-slider-length" @bind-SliderValue="@CurrentGroup.DurationRange.Min"
OnValueChanged="u => { if (CurrentGroup.DurationRange.Max < u) CurrentGroup.DurationRange.Max = u; }"
OnSaveAction="_ => ConfigManager.SaveFnf()"
OnSaveAction="_ => ConfigManager.Save()"
Min="300" Max="30000" Step="100">
Min Duration: @MathF.Round(CurrentGroup.DurationRange.Min / 1000f, 1).ToString(CultureInfo.InvariantCulture)s
</DebouncedSlider>

<DebouncedSlider T="uint" Size="Size.Large" Class="openshock-slider-length" @bind-SliderValue="@CurrentGroup.DurationRange.Max"
OnValueChanged="u => { if (CurrentGroup.DurationRange.Min > u) CurrentGroup.DurationRange.Min = u; }"
OnSaveAction="_ => ConfigManager.SaveFnf()"
OnSaveAction="_ => ConfigManager.Save()"
Min="300" Max="30000" Step="100">
Max Duration: @MathF.Round(CurrentGroup.DurationRange.Max / 1000f, 1).ToString(CultureInfo.InvariantCulture)s
</DebouncedSlider>
Expand Down
4 changes: 2 additions & 2 deletions ShockOsc/Ui/Pages/Dash/Tabs/ShockersTab.razor
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@

@code {

private Task OnShockerConfigUpdate()
private void OnShockerConfigUpdate()
{
return ConfigManager.SaveAsync();
ConfigManager.Save();
}

}

0 comments on commit 29eba35

Please sign in to comment.