-
Notifications
You must be signed in to change notification settings - Fork 17
/
ProcessId.cs
549 lines (485 loc) · 18 KB
/
ProcessId.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Text;
using LanguageExt;
using static LanguageExt.Prelude;
namespace Echo
{
class ProcessIdInternal
{
public readonly ProcessName[] Parts;
public readonly ProcessName Name;
public readonly SystemName System;
public readonly string Path;
public readonly bool IsDisp;
const string Disp = "/disp";
public ProcessIdInternal(ProcessName[] parts, ProcessName name, SystemName system, string path)
{
Parts = parts ?? throw new ArgumentNullException(nameof(parts));
Name = name;
System = system;
Path = path ?? throw new ArgumentNullException(nameof(path));
IsDisp = path.StartsWith(Disp);
}
}
/// <summary>
/// <para>
/// Process identifier
/// </para>
/// <para>
/// Use this to 'tell' a message to a process. It can be serialised and passed around
/// without concerns for internals.
/// </para>
/// </summary>
public struct ProcessId : IEquatable<ProcessId>, IComparable<ProcessId>, IComparable
{
internal readonly ProcessIdInternal value;
/// <summary>
/// The Process system qualifier
/// </summary>
public SystemName System =>
value?.System ?? default(SystemName);
/// <summary>
/// Absolute path of the process ID
/// </summary>
public string Path =>
value?.Path;
/// <summary>
/// Ctor
/// </summary>
/// <param name="path">Path of the process, in the form: /name/name/name </param>
[JsonConstructor]
public ProcessId(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
var res = TryParse(path).IfLeft(ex => raise<ProcessId>(ex));
value = new ProcessIdInternal(res.value.Parts, res.value.Name, res.System, res.value.Path);
}
ProcessId(string path, SystemName system)
{
if (path == null) throw new ArgumentNullException(nameof(path));
var res = TryParse(path).IfLeft(ex => raise<ProcessId>(ex));
value = new ProcessIdInternal(res.value.Parts, res.value.Name, res.System, res.value.Path);
}
ProcessId(ProcessName[] parts, SystemName system, ProcessName name, string path)
{
value = new ProcessIdInternal(parts, name, system, path);
}
ProcessId(ProcessIdInternal value)
{
this.value = value;
}
public static Either<Exception, ProcessId> TryParse(string path)
{
if (path == null || path.Length == 0)
{
return new InvalidProcessIdException();
}
var system = "";
if( path.StartsWith("//"))
{
var end = path.IndexOf(Sep, 2);
end = end == -1
? path.IndexOf("@", 2)
: end;
if(end == -1)
{
return new InvalidProcessIdException($"Invalid ProcessId ({path}), nothing following the system specifier");
}
system = path.Substring(2, end - 2);
path = path.Substring(end);
}
if (path[0] == '@')
{
return ParseRegisteredProcess(path.Substring(1));
}
if (path[0] != Sep)
{
return new InvalidProcessIdException();
}
ProcessName[] parts = null;
ProcessName name;
string finalPath = null;
if (path.Length == 1)
{
parts = new ProcessName[0];
}
else
{
try
{
parts = SplitOnSep(path).ToArray();
}
catch (InvalidProcessNameException)
{
return new InvalidProcessIdException();
}
}
finalPath = parts == null
? ""
: parts.Length == 0
? Sep.ToString()
: Sep + String.Join(Sep.ToString(), parts);
if (path != Sep.ToString())
{
name = parts == null
? ""
: parts.Length == 0
? Sep.ToString()
: parts.Last();
}
else
{
name = "$";
}
return new ProcessId(parts, system == "" ? default(SystemName) : system, name, finalPath);
}
static ProcessId ParseRegisteredProcess(string name) =>
TryParseRegisteredProcess(name)
.Match(
Right: r => r,
Left: ex => raise<ProcessId>(ex));
static Either<Exception, ProcessId> TryParseRegisteredProcess(string name)
{
if (name.Length == 0) return new InvalidProcessNameException("Registerd process name has nothing following the '@'");
var parts = name.Split(':');
if (parts.Length == 0) return new InvalidProcessNameException();
if (parts.Length > 2) return new InvalidProcessNameException("Too many ':' in the registered process name");
if ((from p in parts
from c in p
where ProcessName.InvalidNameChars.Contains(c)
select c)
.Any())
{
return new InvalidProcessNameException();
}
if (parts.Length == 1)
{
return Process.find(Role.Current, parts[0]);
}
else
{
return Process.find(parts[0], parts[1]);
}
}
/// <summary>
/// Traverses a string extracting an enumerable of ProcessNames that
/// make up the path.
/// </summary>
/// <param name="path">Path to traverse</param>
/// <returns>Enumerable of ProcessNames</returns>
static IEnumerable<ProcessName> SplitOnSep(string path)
{
var builder = new StringBuilder();
var selection = false;
foreach (var c in path)
{
if (selection)
{
if (c == ']')
{
selection = false;
}
builder.Append(c);
}
else
{
switch (c)
{
case '[':
selection = true;
if (builder.Length > 0)
{
throw new InvalidProcessIdException($"Selection types must cover entire names. ie. {Sep}[{Sep}root,{Sep}node]{Sep}user, not {Sep}test[{Sep}root,{Sep}node]{Sep}user");
}
builder.Append('[');
break;
case Sep:
if (builder.Length > 0)
{
yield return new ProcessName(builder.ToString());
builder.Length = 0;
}
break;
default:
builder.Append(c);
break;
}
}
}
if (selection)
{
throw new InvalidProcessIdException("ProcessId has an opening selection: '[', but no selection close: ']'");
}
if (builder.Length > 0)
{
yield return new ProcessName(builder.ToString());
}
}
/// <summary>
/// Generate new ProcessId that represents a child of this process ID
/// </summary>
/// <returns>Process ID</returns>
public ProcessId this[ProcessName child] =>
Child(child);
/// <summary>
/// Generate new ProcessId that represents a child of this process ID
/// </summary>
/// <returns>Process ID</returns>
public ProcessId this[IEnumerable<ProcessId> child] =>
Child(child);
/// <summary>
/// Generate new ProcessId that represents a child of this process ID
/// </summary>
/// <param name="name">Name of the child process</param>
/// <returns>Process ID</returns>
public ProcessId Child(ProcessName name)
{
if (value == null) new ProcessId(new ProcessIdInternal(new[] { name }, name, System, $"{Sep}{name.Value}"));
var parts = value.Parts;
if (parts.Length == 0)
{
return new ProcessId(new ProcessName[1] { name }, System, name, $"{Sep}{name.Value}");
}
else
{
var newParts = new ProcessName[parts.Length + 1];
global::System.Array.Copy(parts, newParts, parts.Length);
newParts[parts.Length] = name;
return new ProcessId(newParts, System, name, $"{Path}{Sep}{name.Value}");
}
}
/// <summary>
/// Generate new ProcessId that represents a child of this process ID
/// </summary>
/// <param name="name">Name of the child process</param>
/// <returns>Process ID</returns>
public ProcessId Child(IEnumerable<ProcessId> name)
{
if (value == null) failwith<ProcessId>("ProcessId is None");
var parts = value.Parts;
var sel = ProcessName.FromSelection(name);
if (parts.Length == 0)
{
return new ProcessId(new ProcessName[1] { sel }, System, sel, $"{Sep}{sel.Value}");
}
else
{
var newParts = new ProcessName[parts.Length + 1];
global::System.Array.Copy(parts, newParts, parts.Length);
newParts[parts.Length] = sel;
return new ProcessId(newParts, System, sel, $"{Path}{Sep}{sel.Value}");
}
}
/// <summary>
/// Returns true if the ProcessId represents a selection of N process
/// paths
/// </summary>
[JsonIgnore]
public bool IsSelection =>
value == null || value.Parts.Length == 0
? false
: value.Parts[0].IsSelection;
/// <summary>
/// If this ProcessId represents a selection of N process paths then
/// this function will return those paths as separate ProcessIds.
/// </summary>
/// <returns>An enumerable of ProcessIds representing the selection.
/// Zero ProcessIds will be returned if the ProcessId is invalid.
/// One ProcessId will be returned if this ProcessId doesn't represent
/// a selection.
/// </returns>
public IEnumerable<ProcessId> GetSelection()
{
var self = this;
return value == null || value.Parts.Length == 0
? new ProcessId[0]
: value.Parts[0].IsSelection
? from x in value.Parts[0].GetSelection()
from y in x.Append(self.Skip(1)).GetSelection()
select y
: new ProcessId[] { self };
}
/// <summary>
/// Get the parent ProcessId
/// </summary>
/// <returns>Parent process ID</returns>
[JsonIgnore]
public ProcessId Parent =>
value == null
? failwith<ProcessId>("ProcessId is None")
: value.Parts.Length == 0
? failwith<ProcessId>("ProcessId doesn't have a parent")
: Take(value.Parts.Length - 1);
/// <summary>
/// Implicit conversion from a string to a ProcessId
/// </summary>
/// <param name="value">String representation of the process ID</param>
public static implicit operator ProcessId(string value) =>
isnull(value)
? ProcessId.NoSender
: new ProcessId(value);
/// <summary>
/// Convert the ProcessId to a string
/// </summary>
/// <returns>String representation of the process ID</returns>
public override string ToString() =>
System.IsValid
? $"//{System}{Path}"
: Path;
/// <summary>
/// Hash code of process ID
/// Do not rely on this between application sessions
/// </summary>
/// <returns>Integer hash code</returns>
public override int GetHashCode() =>
Path.GetHashCode();
/// <summary>
/// Returns true if this is a valid process ID
/// </summary>
[JsonIgnore]
public bool IsValid =>
value != null;
/// <summary>
/// Get the name of the process
/// </summary>
/// <returns></returns>
[JsonIgnore]
public ProcessName Name =>
value?.Name ?? failwith<ProcessName>("ProcessId is None and has no name");
/// <summary>
/// NoSender process ID
/// </summary>
public readonly static ProcessId NoSender =
new ProcessId();
/// <summary>
/// None process ID
/// </summary>
public readonly static ProcessId None =
new ProcessId();
/// <summary>
/// Process ID name separator
/// </summary>
public const char Sep = '/';
/// <summary>
/// Equality check
/// </summary>
public bool Equals(ProcessId other) =>
ReferenceEquals(Path, other.Path) || Path.Equals(other.Path);
/// <summary>
/// Equality check
/// </summary>
public override bool Equals(object obj) =>
obj is ProcessId pid && Equals(pid);
/// <summary>
/// Equality operator
/// </summary>
public static bool operator ==(ProcessId lhs, ProcessId rhs) =>
lhs.Equals(rhs);
/// <summary>
/// Non-equality operator
/// </summary>
public static bool operator !=(ProcessId lhs, ProcessId rhs) =>
!lhs.Equals(rhs);
/// <summary>
/// Compare
/// </summary>
public int CompareTo(ProcessId other) =>
string.Compare(Path, other.Path, StringComparison.Ordinal);
/// <summary>
/// Compare
/// </summary>
public int CompareTo(object obj) =>
obj is ProcessId
? CompareTo((ProcessId)obj)
: -1;
/// <summary>
/// Remove path elements from the start of the path
/// </summary>
public ProcessId Skip(int count)
{
if (value == null || count >= value.Parts.Length ) return Top.SetSystem(System);
var newParts = value.Parts.Skip(count).ToArray();
return new ProcessId(newParts, System, Name, Top + String.Join(Sep.ToString(), newParts));
}
/// <summary>
/// Take N elements of the path
/// </summary>
public ProcessId Take(int count)
{
if (value == null || count == 0 || value.Parts.Length == 0) return Top.SetSystem(System);
var newParts = value.Parts.Take(count).ToArray();
return new ProcessId(newParts, System, newParts[newParts.Length-1], Top + String.Join(Sep.ToString(), newParts));
}
/// <summary>
/// Accessor to the head of the path as a ProcessName
/// </summary>
/// <returns></returns>
public ProcessName HeadName() =>
value == null || value.Parts.Length == 0
? failwith<ProcessName>("ProcessId is none")
: value.Parts[0];
/// <summary>
/// Take head of path
/// </summary>
public ProcessId Head() =>
Take(1);
/// <summary>
/// Take tail of path
/// </summary>
public ProcessId Tail() =>
Skip(1);
/// <summary>
/// Number of parts to the name
/// </summary>
/// <returns></returns>
public int Count() =>
value?.Parts?.Length ?? 0;
/// <summary>
/// Append one process ID to another
/// </summary>
public ProcessId Append(ProcessId pid) =>
(pid.Path?.Length ?? 0) < 2
? this
: IsValid && pid.IsValid
? new ProcessId(value.Parts.Concat(pid.value.Parts).ToArray(), pid.System, pid.Name, $"{Path}{pid.Path}")
: IsValid
? pid
: raise<ProcessId>(new InvalidProcessIdException());
/// <summary>
/// Absolute root of the process system
/// </summary>
public static readonly ProcessId Top =
new ProcessId(Sep.ToString());
/// <summary>
/// Set the Process system that this ProcessId belongs to
/// </summary>
public ProcessId SetSystem(SystemName system) =>
IsValid
? new ProcessId(value.Parts, system, Name, Path)
: this;
public bool StartsWith(ProcessId head)
{
if (head.Count() > Count()) return false;
if (head.value == null && value == null) return true;
if (head.value == null || value == null) return false;
var iterA = head.value.Parts.AsEnumerable().GetEnumerator();
var iterB = value.Parts.AsEnumerable().GetEnumerator();
while(iterA.MoveNext() && iterB.MoveNext())
{
if (iterA.Current != iterB.Current) return false;
}
return true;
}
static R failwith<R>(string message)
{
throw new Exception(message);
}
static R raise<R>(Exception ex)
{
throw ex;
}
}
}