Skip to content

Commit

Permalink
refactor: increase precision of bb metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
azeier committed Aug 14, 2023
1 parent 9d039ea commit f38171b
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 12 deletions.
14 changes: 8 additions & 6 deletions Hearthstone Deck Tracker/Utility/Analytics/Influx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using BobsBuddy;
using BobsBuddy.Simulation;
using Hearthstone_Deck_Tracker.BobsBuddy;
using Hearthstone_Deck_Tracker.Hearthstone;
Expand Down Expand Up @@ -265,6 +264,7 @@ public static void OnBobsBuddySimulationCompleted(CombatResult result, Output ou
if(!Config.Instance.GoogleAnalytics)
return;
var point = new InfluxPointBuilder("hdt_bb_combat_result_v3")
.HighPrecision()
.Tag("result", result.ToString())
.Tag("terminal_case", terminalCase.ToString())
.Tag("turn", turn)
Expand Down Expand Up @@ -311,18 +311,20 @@ public static void OnMulliganToastEnabledChanged(bool newState)
WritePoint(new InfluxPointBuilder("hdt_mulligan_toast_enabled_changed").Tag("new_state", newState).Build());
}

private static List<InfluxPoint> _queue = new List<InfluxPoint>();
private static readonly List<InfluxPoint> _queue = new();
public static void SendQueuedMetrics()
{
if(!_queue.Any())
return;
WritePoints(_queue);
var points = _queue.ToList();
_queue.Clear();
foreach(var group in points.GroupBy(x => x.HighPrecision))
WritePoints(group, highPrecision: group.Key);
}

private static void WritePoint(InfluxPoint point) => WritePoints(new[] { point });
private static void WritePoint(InfluxPoint point) => WritePoints(new[] { point }, point.HighPrecision);

private static async void WritePoints(IEnumerable<InfluxPoint> points)
private static async void WritePoints(IEnumerable<InfluxPoint> points, bool highPrecision)
{
if(!points.Any())
return;
Expand All @@ -332,7 +334,7 @@ private static async void WritePoints(IEnumerable<InfluxPoint> points)
{
var line = string.Join("\n", points.Select(x => x.ToLineProtocol()));
var data = Encoding.UTF8.GetBytes(line);
var length = await client.SendAsync(data, data.Length, "metrics.hearthsim.net", 8091);
var length = await client.SendAsync(data, data.Length, "metrics.hearthsim.net", highPrecision ? 8099 : 8091);
Log.Debug(line + " - " + length);
}
}
Expand Down
7 changes: 5 additions & 2 deletions Hearthstone Deck Tracker/Utility/Analytics/InfluxPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@ internal class InfluxPoint
{
private readonly Regex _escape = new Regex("[,= ]");

public InfluxPoint(string name, Dictionary<string, object> tags, Dictionary<string, object> fields, DateTime utcNow)
public InfluxPoint(string name, Dictionary<string, object> tags, Dictionary<string, object> fields, DateTime utcNow, bool highPrecision = false)
{
Name = name;
Tags = tags ?? new Dictionary<string, object>();
Fields = fields ?? new Dictionary<string, object>();
Timestamp = utcNow;
HighPrecision = highPrecision;
}

public string Name { get; }
public Dictionary<string, object> Tags { get; }
public Dictionary<string, object> Fields { get; }
public DateTime Timestamp { get; }
public bool HighPrecision { get; }

private string Escape(string str)
{
Expand All @@ -33,7 +35,8 @@ public string ToLineProtocol()
{
var tags = string.Join(",", Tags.Select(x => $"{x.Key}={Escape(x.Value.ToString())}"));
var fields = string.Join(",", Fields.Select(x => $"{x.Key}={GetValueString(x.Value)}"));
return $"{Name}{(tags.Any() ? $",{tags}" : "")} {fields} {Timestamp.ToUnixTime()}";
var timestamp = HighPrecision ? Timestamp.ToUnixTimeMicroSeconds() : Timestamp.ToUnixTimeSeconds();
return $"{Name}{(tags.Any() ? $",{tags}" : "")} {fields} {timestamp}";
}

public string GetValueString(object value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ internal class InfluxPointBuilder
private readonly Dictionary<string, object> _tags = new Dictionary<string, object>();
private readonly string _name;
private DateTime? _timestamp;
private bool _highPrecision;

public InfluxPointBuilder(string name, bool defaultField = true)
{
Expand Down Expand Up @@ -39,11 +40,17 @@ public InfluxPointBuilder Timestamp(DateTime timestamp)
return this;
}

public InfluxPointBuilder HighPrecision(bool highPrecision = true)
{
_highPrecision = highPrecision;
return this;
}

public InfluxPoint Build()
{
if(!_fields.Any())
throw new Exception("Missing field");
return new InfluxPoint(_name, _tags, _fields, _timestamp ?? DateTime.UtcNow);
return new InfluxPoint(_name, _tags, _fields, _timestamp ?? DateTime.UtcNow, _highPrecision);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ namespace Hearthstone_Deck_Tracker.Utility.Extensions
{
public static class DateTimeExtensions
{
public static long ToUnixTime(this DateTime time)
=> Math.Max(0, (long)(time.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds);
public const double TicksPerMicroSecond = TimeSpan.TicksPerMillisecond / 1000;

private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

public static long ToUnixTimeSeconds(this DateTime time) => new DateTimeOffset(time.ToUniversalTime()).ToUnixTimeSeconds();

public static long ToUnixTimeMicroSeconds(this DateTime time) => Convert.ToInt64((new DateTimeOffset(time.ToUniversalTime()) - UnixEpoch).Ticks / TicksPerMicroSecond);
}
}
2 changes: 1 addition & 1 deletion Hearthstone Deck Tracker/Utility/Logging/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static void Initialize()
{
//can access log file => no other instance of same installation running
}
File.Move(logFile, logFile.Replace(".txt", "_" + DateTime.Now.ToUnixTime() + ".txt"));
File.Move(logFile, logFile.Replace(".txt", "_" + DateTime.Now.ToUnixTimeSeconds() + ".txt"));
//keep logs from the last 2 days plus 25 before that
foreach(var file in
new DirectoryInfo(logDir).GetFiles("hdt_log*")
Expand Down

0 comments on commit f38171b

Please sign in to comment.