-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSession.cs
130 lines (115 loc) · 4.89 KB
/
Session.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DvMod.RemoteDispatch
{
public static class Sessions
{
private static readonly TimeSpan SessionTimeout = TimeSpan.FromMinutes(5);
private static readonly object allSesssionsLock = new object();
private static readonly Dictionary<string, Session> allSessions = new Dictionary<string, Session>();
private static readonly HashSet<string> AllTags = new HashSet<string>() { "cars", "jobs", "junctions", "player" };
public static event Action<string>? OnSessionStarted;
public static event Action<string>? OnSessionEnded;
private class Session
{
public readonly string username;
public readonly AsyncSet<string> pendingTags = new AsyncSet<string>();
public readonly Stopwatch timeSinceLastFetch = new Stopwatch();
public Session(string username)
{
this.username = username;
foreach (var tag in AllTags)
pendingTags.Add(tag);
}
}
public static HashSet<string> GetUsersWithActiveSessions()
{
return new HashSet<string>(allSessions.Values.Select(s => s.username));
}
public static void AddTag(string tag)
{
lock (allSesssionsLock)
{
List<string> timedOutSessions = new List<string>();
foreach (var kvp in allSessions)
{
var sessionId = kvp.Key;
var session = kvp.Value;
if (session.timeSinceLastFetch.Elapsed > SessionTimeout)
timedOutSessions.Add(sessionId);
else
session.pendingTags.Add(tag);
}
foreach (var sessionId in timedOutSessions)
{
Main.DebugLog(() => $"Session {sessionId} timed out");
allSessions.Remove(sessionId);
OnSessionEnded?.Invoke(sessionId);
}
}
}
private static async Task<IEnumerable<string>> GetTags(string username, string sessionId)
{
Session session;
lock (allSesssionsLock)
{
if (!allSessions.TryGetValue(sessionId, out session))
{
Main.DebugLog(() => $"Starting new session {sessionId} for user {username}");
session = new Session(username);
allSessions.Add(sessionId, session);
OnSessionStarted?.Invoke(username);
}
}
session.timeSinceLastFetch.Restart();
var tags = new HashSet<string>(session.pendingTags.TakeAll());
if (tags.Count > 0)
return tags;
// No data available
var (success, awaitedTag) = await session.pendingTags.TryTakeAsync(TimeSpan.FromMinutes(1)).ConfigureAwait(false);
return success ? new string[1] { awaitedTag } : new string[0];
}
private static JObject? GetUpdateForCarGuid(string carGuid)
{
return CarData.GetCarGuidDataJson(carGuid);
}
private static JObject GetUpdateForTrainset(string trainsetId)
{
return JObject.FromObject(CarData.GetTrainsetData(int.Parse(trainsetId)));
}
private static JToken? GetUpdateForSplitTag(string tag)
{
var index = tag.IndexOf('-');
var tagType = tag.Substring(0, index);
var tagId = tag.Substring(index + 1);
return tagType switch
{
"carguid" => GetUpdateForCarGuid(tagId),
"trainset" => GetUpdateForTrainset(tagId),
_ => throw new NotImplementedException($"Unexpected update tag {tag}"),
};
}
private static JToken? GetUpdateForTag(string tag)
{
return tag switch
{
"cars" => JObject.FromObject(CarData.GetAllCarData().ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToJson())),
"jobs" => JObject.FromObject(JobData.GetAllJobData()),
"junctions" => new JArray(Junctions.GetAllJunctionStates()),
"player" => PlayerData.GetPlayerData(),
_ when tag.Contains('-') => GetUpdateForSplitTag(tag),
_ => throw new NotImplementedException($"Unexpected update tag {tag}"),
};
}
public static async Task<string> GetUpdates(string username, string sessionId)
{
var tags = await GetTags(username, sessionId).ConfigureAwait(false);
return JsonConvert.SerializeObject(tags.ToDictionary(tag => tag, tag => GetUpdateForTag(tag)));
}
}
}