This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathUsageService.cs
More file actions
195 lines (171 loc) · 6.1 KB
/
Copy pathUsageService.cs
File metadata and controls
195 lines (171 loc) · 6.1 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
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GitHub.Logging;
using GitHub.Models;
using Serilog;
using Rothko;
using Microsoft.VisualStudio.Threading;
using Microsoft.VisualStudio.Shell;
using Environment = System.Environment;
using Task = System.Threading.Tasks.Task;
namespace GitHub.Services
{
[Export(typeof(IUsageService))]
public sealed class UsageService : IUsageService, IDisposable
{
const string StoreFileName = "metrics.json";
const string UserStoreFileName = "user.json";
static readonly ILogger log = LogManager.ForContext<UsageService>();
readonly IGitHubServiceProvider serviceProvider;
readonly IEnvironment environment;
readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
string storePath;
string userStorePath;
Guid? userGuid;
[ImportingConstructor]
public UsageService(IGitHubServiceProvider serviceProvider, IEnvironment environment,
[Import(AllowDefault = true)] JoinableTaskContext joinableTaskContext)
{
this.serviceProvider = serviceProvider;
this.environment = environment;
JoinableTaskContext = joinableTaskContext ?? ThreadHelper.JoinableTaskContext;
}
public void Dispose()
{
semaphoreSlim.Dispose();
}
public async Task<Guid> GetUserGuid()
{
await Initialize();
if (!userGuid.HasValue)
{
try
{
if (File.Exists(userStorePath))
{
var json = await ReadAllTextAsync(userStorePath);
var data = SimpleJson.DeserializeObject<UserData>(json);
userGuid = data.UserGuid;
}
}
catch (Exception ex)
{
log.Error(ex, "Failed reading user metrics GUID");
}
}
if (!userGuid.HasValue || userGuid.Value == Guid.Empty)
{
userGuid = Guid.NewGuid();
try
{
var data = new UserData { UserGuid = userGuid.Value };
var json = SimpleJson.SerializeObject(data);
await WriteAllTextAsync(userStorePath, json);
}
catch (Exception ex)
{
log.Error(ex, "Failed writing user metrics GUID");
}
}
return userGuid.Value;
}
public IDisposable StartTimer(Func<Task> callback, TimeSpan dueTime, TimeSpan period)
{
return new Timer(
#pragma warning disable VSTHRD101 // Avoid unsupported async delegates
async _ =>
{
try { await callback(); }
catch (Exception ex) { log.Warning(ex, "Failed submitting usage data"); }
},
#pragma warning restore VSTHRD101 // Avoid unsupported async delegates
null,
dueTime,
period);
}
public async Task<UsageData> ReadLocalData()
{
await Initialize();
var json = File.Exists(storePath) ? await ReadAllTextAsync(storePath) : null;
try
{
return json != null ?
SimpleJson.DeserializeObject<UsageData>(json) :
new UsageData { Reports = new List<UsageModel>() };
}
catch (Exception ex)
{
log.Error(ex, "Error deserializing usage");
return new UsageData { Reports = new List<UsageModel>() };
}
}
public async Task WriteLocalData(UsageData data)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(storePath));
var json = SimpleJson.SerializeObject(data);
await WriteAllTextAsync(storePath, json);
}
catch (Exception ex)
{
log.Error(ex, "Failed to write usage data");
}
}
async Task Initialize()
{
if (storePath == null)
{
await JoinableTaskContext.Factory.SwitchToMainThreadAsync();
var program = serviceProvider.GetService<IProgram>();
var localApplicationDataPath = environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
storePath = Path.Combine(localApplicationDataPath, program.ApplicationName, StoreFileName);
userStorePath = Path.Combine(localApplicationDataPath, program.ApplicationName, UserStoreFileName);
}
}
async Task<string> ReadAllTextAsync(string path)
{
// Avoid IOException when metrics updated multiple times in quick succession
await semaphoreSlim.WaitAsync();
try
{
using (var s = File.OpenRead(path))
using (var r = new StreamReader(s, Encoding.UTF8))
{
return await r.ReadToEndAsync();
}
}
finally
{
semaphoreSlim.Release();
}
}
async Task WriteAllTextAsync(string path, string text)
{
// Avoid IOException when metrics updated multiple times in quick succession
await semaphoreSlim.WaitAsync();
try
{
using (var s = new FileStream(path, FileMode.Create))
using (var w = new StreamWriter(s, Encoding.UTF8))
{
await w.WriteAsync(text);
}
}
finally
{
semaphoreSlim.Release();
}
}
class UserData
{
public Guid UserGuid { get; set; }
}
JoinableTaskContext JoinableTaskContext { get; }
}
}