/
ServerV2.cs
441 lines (368 loc) · 11.6 KB
/
ServerV2.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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Speckle.Core.Credentials;
using Speckle.Core.Helpers;
using Speckle.Core.Logging;
using Speckle.Core.Models;
using Speckle.Core.Transports.ServerUtils;
using Speckle.Newtonsoft.Json.Linq;
namespace Speckle.Core.Transports;
public sealed class ServerTransport : IDisposable, ICloneable, ITransport, IBlobCapableTransport
{
private readonly object _elapsedLock = new();
private Exception? _exception;
private bool IsInErrorState => _exception is not null;
private bool _isWriteComplete;
// TODO: make send buffer more flexible to accept blobs too
private List<(string id, string data)> _sendBuffer = new();
private readonly object _sendBufferLock = new();
private Thread? _sendingThread;
private volatile bool _shouldSendThreadRun;
/// <param name="account"></param>
/// <param name="streamId"></param>
/// <param name="timeoutSeconds"></param>
/// <param name="blobStorageFolder">Defaults to <see cref="SpecklePathProvider.BlobStoragePath"/></param>
/// <exception cref="ArgumentException"><paramref name="streamId"/> was not formatted as valid stream id</exception>
public ServerTransport(Account account, string streamId, int timeoutSeconds = 60, string? blobStorageFolder = null)
{
if (string.IsNullOrWhiteSpace(streamId))
{
throw new ArgumentException($"{streamId} is not a valid id", streamId);
}
Account = account;
BaseUri = account.serverInfo.url;
StreamId = streamId;
AuthorizationToken = account.token;
TimeoutSeconds = timeoutSeconds;
BlobStorageFolder = blobStorageFolder ?? SpecklePathProvider.BlobStoragePath();
Initialize(account.serverInfo.url);
Directory.CreateDirectory(BlobStorageFolder);
}
public int TotalSentBytes { get; private set; }
public Account Account { get; }
public string BaseUri { get; }
public string StreamId { get; internal set; }
public int TimeoutSeconds { get; set; }
private string AuthorizationToken { get; }
internal ParallelServerApi Api { get; private set; }
public string BlobStorageFolder { get; set; }
public void SaveBlob(Blob obj)
{
var hash = obj.GetFileHash();
lock (_sendBufferLock)
{
if (IsInErrorState)
{
return;
}
_sendBuffer.Add(($"blob:{hash}", obj.filePath));
}
}
public object Clone()
{
return new ServerTransport(Account, StreamId, TimeoutSeconds, BlobStorageFolder)
{
OnProgressAction = OnProgressAction,
CancellationToken = CancellationToken,
};
}
public void Dispose()
{
if (_sendingThread != null)
{
_shouldSendThreadRun = false;
_sendingThread.Join();
}
Api.Dispose();
}
public string TransportName { get; set; } = "RemoteTransport";
public Dictionary<string, object> TransportContext =>
new()
{
{ "name", TransportName },
{ "type", GetType().Name },
{ "streamId", StreamId },
{ "serverUrl", BaseUri },
{ "blobStorageFolder", BlobStorageFolder }
};
public CancellationToken CancellationToken { get; set; }
public Action<string, int>? OnProgressAction { get; set; }
public int SavedObjectCount { get; private set; }
public TimeSpan Elapsed { get; private set; } = TimeSpan.Zero;
public async Task<string> CopyObjectAndChildren(
string id,
ITransport targetTransport,
Action<int>? onTotalChildrenCountKnown = null
)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentException("Cannot copy object with empty id", nameof(id));
}
CancellationToken.ThrowIfCancellationRequested();
using ParallelServerApi api = new(BaseUri, AuthorizationToken, BlobStorageFolder, TimeoutSeconds);
var stopwatch = Stopwatch.StartNew();
api.CancellationToken = CancellationToken;
string rootObjectJson = await api.DownloadSingleObject(StreamId, id).ConfigureAwait(false);
IList<string> allIds = ParseChildrenIds(rootObjectJson);
List<string> childrenIds = allIds.Where(x => !x.Contains("blob:")).ToList();
List<string> blobIds = allIds.Where(x => x.Contains("blob:")).Select(x => x.Remove(0, 5)).ToList();
onTotalChildrenCountKnown?.Invoke(allIds.Count);
//
// Objects download
//
// Check which children are not already in the local transport
var childrenFoundMap = await targetTransport.HasObjects(childrenIds).ConfigureAwait(false);
List<string> newChildrenIds = new(from objId in childrenFoundMap.Keys where !childrenFoundMap[objId] select objId);
targetTransport.BeginWrite();
await api.DownloadObjects(
StreamId,
newChildrenIds,
(childId, childData) =>
{
stopwatch.Stop();
targetTransport.SaveObject(childId, childData);
OnProgressAction?.Invoke(TransportName, 1);
stopwatch.Start();
}
)
.ConfigureAwait(false);
// pausing until writing to the target transport
stopwatch.Stop();
targetTransport.SaveObject(id, rootObjectJson);
await targetTransport.WriteComplete().ConfigureAwait(false);
targetTransport.EndWrite();
stopwatch.Start();
//
// Blobs download
//
var localBlobTrimmedHashes = Directory
.GetFiles(BlobStorageFolder)
.Select(fileName => fileName.Split(Path.DirectorySeparatorChar).Last())
.Where(fileName => fileName.Length > 10)
.Select(fileName => fileName.Substring(0, Blob.LocalHashPrefixLength))
.ToList();
var newBlobIds = blobIds
.Where(blobId => !localBlobTrimmedHashes.Contains(blobId.Substring(0, Blob.LocalHashPrefixLength)))
.ToList();
await api.DownloadBlobs(
StreamId,
newBlobIds,
() =>
{
OnProgressAction?.Invoke(TransportName, 1);
}
)
.ConfigureAwait(false);
stopwatch.Stop();
Elapsed += stopwatch.Elapsed;
return rootObjectJson;
}
public string GetObject(string id)
{
CancellationToken.ThrowIfCancellationRequested();
var stopwatch = Stopwatch.StartNew();
var result = Api.DownloadSingleObject(StreamId, id).Result;
stopwatch.Stop();
Elapsed += stopwatch.Elapsed;
return result;
}
public async Task<Dictionary<string, bool>> HasObjects(IReadOnlyList<string> objectIds)
{
return await Api.HasObjects(StreamId, objectIds).ConfigureAwait(false);
}
public void SaveObject(string id, string serializedObject)
{
lock (_sendBufferLock)
{
if (IsInErrorState)
{
return;
}
_sendBuffer.Add((id, serializedObject));
_isWriteComplete = false;
}
}
public void SaveObject(string id, ITransport sourceTransport)
{
var objectData = sourceTransport.GetObject(id);
if (objectData is null)
{
throw new TransportException(
this,
$"Cannot copy {id} from {sourceTransport.TransportName} to {TransportName} as source returned null"
);
}
SaveObject(id, objectData);
}
public void BeginWrite()
{
if (_shouldSendThreadRun || _sendingThread != null)
{
throw new InvalidOperationException("ServerTransport already sending");
}
TotalSentBytes = 0;
SavedObjectCount = 0;
_exception = null;
_shouldSendThreadRun = true;
_sendingThread = new Thread(SendingThreadMain) { Name = "ServerTransportSender", IsBackground = true };
_sendingThread.Start();
}
public async Task WriteComplete()
{
while (true)
{
lock (_sendBufferLock)
{
if (_isWriteComplete || IsInErrorState)
{
CancellationToken.ThrowIfCancellationRequested();
if (_exception is not null)
{
throw new TransportException(this, $"{TransportName} transport failed", _exception);
}
return;
}
}
await Task.Delay(50, CancellationToken).ConfigureAwait(false);
}
}
public void EndWrite()
{
if (!_shouldSendThreadRun || _sendingThread == null)
{
throw new InvalidOperationException("ServerTransport not sending");
}
_shouldSendThreadRun = false;
_sendingThread.Join();
_sendingThread = null;
}
private void Initialize(string baseUri)
{
SpeckleLog.Logger.Information("Initializing a new Remote Transport for {baseUri}", baseUri);
Api = new ParallelServerApi(BaseUri, AuthorizationToken, BlobStorageFolder, TimeoutSeconds)
{
OnBatchSent = (num, size) =>
{
OnProgressAction?.Invoke(TransportName, num);
TotalSentBytes += size;
SavedObjectCount += num;
}
};
}
public override string ToString()
{
return $"Server Transport @{Account.serverInfo.url}";
}
private static IList<string> ParseChildrenIds(string json)
{
List<string> childrenIds = new();
JObject doc1 = JObject.Parse(json);
JToken? closures = doc1["__closure"];
if (closures == null)
{
return Array.Empty<string>();
}
foreach (JToken prop in closures)
{
childrenIds.Add(((JProperty)prop).Name);
}
return childrenIds;
}
private async void SendingThreadMain()
{
while (true)
{
var stopwatch = Stopwatch.StartNew();
if (!_shouldSendThreadRun || CancellationToken.IsCancellationRequested)
{
return;
}
List<(string id, string data)>? buffer = null;
lock (_sendBufferLock)
{
if (_sendBuffer.Count > 0)
{
buffer = _sendBuffer;
_sendBuffer = new();
}
else
{
_isWriteComplete = true;
}
}
if (buffer is null)
{
Thread.Sleep(100);
continue;
}
try
{
var bufferObjects = buffer.Where(tuple => !tuple.id.Contains("blob")).ToList();
var bufferBlobs = buffer.Where(tuple => tuple.id.Contains("blob")).ToList();
List<string> objectIds = new(bufferObjects.Count);
foreach ((string id, _) in bufferObjects)
{
if (id != "blob")
{
objectIds.Add(id);
}
}
Dictionary<string, bool> hasObjects = await Api.HasObjects(StreamId, objectIds).ConfigureAwait(false);
List<(string, string)> newObjects = new();
foreach ((string id, object json) in bufferObjects)
{
if (!hasObjects[id])
{
newObjects.Add((id, (string)json));
}
}
// Report the objects that are already on the server
OnProgressAction?.Invoke(TransportName, hasObjects.Count - newObjects.Count);
await Api.UploadObjects(StreamId, newObjects).ConfigureAwait(false);
if (bufferBlobs.Count != 0)
{
var blobIdsToUpload = await Api.HasBlobs(StreamId, bufferBlobs).ConfigureAwait(false);
var formattedIds = blobIdsToUpload.Select(id => $"blob:{id}").ToList();
var newBlobs = bufferBlobs.Where(tuple => formattedIds.IndexOf(tuple.id) != -1).ToList();
if (newBlobs.Count != 0)
{
await Api.UploadBlobs(StreamId, newBlobs).ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
lock (_sendBufferLock)
{
_sendBuffer.Clear();
_exception = ex;
}
if (ex.IsFatal())
{
throw;
}
}
finally
{
stopwatch.Stop();
lock (_elapsedLock)
{
Elapsed += stopwatch.Elapsed;
}
}
}
}
[Obsolete("Transport will throw exceptions instead", true)]
public Action<string, Exception>? OnErrorAction { get; set; }
}
[Obsolete("Use " + nameof(ServerTransport), true)]
public sealed class ServerTransportV2
{
public ServerTransportV2(params object[] _) { }
}