forked from akkadotnet/akka.net
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ScriptedTest.cs
355 lines (309 loc) · 14.3 KB
/
ScriptedTest.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
//-----------------------------------------------------------------------
// <copyright file="ScriptedTest.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Configuration;
using Akka.Streams.Dsl;
using Akka.TestKit;
using Akka.Util;
using Akka.Util.Internal;
using Reactive.Streams;
using Xunit.Abstractions;
namespace Akka.Streams.TestKit
{
[Serializable]
public class ScriptException : Exception
{
public ScriptException() { }
public ScriptException(string message) : base(message) { }
public ScriptException(string message, Exception inner) : base(message, inner) { }
protected ScriptException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
public abstract class ScriptedTest : AkkaSpec
{
protected static class Script
{
public static Script<TIn, TOut> Create<TIn, TOut>(params (ICollection<TIn>, ICollection<TOut>)[] phases)
{
var providedInputs = new List<TIn>();
var expectedOutputs = new List<TOut>();
var jumps = new List<int>();
foreach (var phase in phases)
{
var ins = phase.Item1;
var outs = phase.Item2;
providedInputs.AddRange(ins);
expectedOutputs.AddRange(outs);
var jump = new int[ins.Count];
jump.Initialize();
jump[jump.Length - 1] = outs.Count;
jumps.AddRange(jump);
}
return new Script<TIn, TOut>(providedInputs.ToArray(), expectedOutputs.ToArray(), jumps.ToArray(), 0, 0, 0, false);
}
}
protected class Script<TIn, TOut>
{
internal readonly TIn[] ProvidedInputs;
internal readonly TOut[] ExpectedOutputs;
internal readonly int[] Jumps;
internal readonly int InputCursor;
internal readonly int OutputCursor;
internal readonly int OutputEndCursor;
internal readonly bool Completed;
public Script(TIn[] providedInputs, TOut[] expectedOutputs, int[] jumps, int inputCursor, int outputCursor, int outputEndCursor, bool completed)
{
if (jumps.Length != providedInputs.Length) throw new ArgumentException("Inputs count must be equal jumps count");
ProvidedInputs = providedInputs;
ExpectedOutputs = expectedOutputs;
Jumps = jumps;
InputCursor = inputCursor;
OutputCursor = outputCursor;
OutputEndCursor = outputEndCursor;
Completed = completed;
}
public bool IsFinished => OutputCursor == ExpectedOutputs.Length;
public int PendingOutputs => OutputEndCursor - OutputCursor;
public bool NoOutputsPending => PendingOutputs == 0;
public bool SomeOutputsPending => !NoOutputsPending;
public int PendingInputs => ProvidedInputs.Length - InputCursor;
public bool NoInputsPending => PendingInputs == 0;
public bool SomeInputsPending => !NoInputsPending;
public (TIn, Script<TIn, TOut>) ProvideInput()
{
if (NoInputsPending)
throw new ScriptException("Script cannot provide more inputs");
var script = new Script<TIn, TOut>(ProvidedInputs, ExpectedOutputs, Jumps, InputCursor + 1, OutputCursor, OutputEndCursor + Jumps[InputCursor], Completed);
return (ProvidedInputs[InputCursor], script);
}
public Script<TIn, TOut> ConsumeOutput(TOut output)
{
if (NoOutputsPending)
throw new ScriptException($"Tried to produce element {output} but no elements should be produced right now");
var equalsExpectedOutput = typeof (IEnumerable).IsAssignableFrom(typeof (TOut))
? ((IEnumerable) output).Cast<object>().SequenceEqual(((IEnumerable) ExpectedOutputs[OutputCursor]).Cast<object>())
: Equals(output, ExpectedOutputs[OutputCursor]);
if (!equalsExpectedOutput)
throw new ArgumentException("Unexpected output", nameof(output));
return new Script<TIn, TOut>(ProvidedInputs, ExpectedOutputs, Jumps, InputCursor, OutputCursor + 1, OutputEndCursor, Completed);
}
public Script<TIn, TOut> Complete()
{
if (!IsFinished)
throw new Exception("Received OnComplete prematurely");
return new Script<TIn, TOut>(ProvidedInputs, ExpectedOutputs, Jumps, InputCursor, OutputCursor + 1, OutputEndCursor, true);
}
public Script<TIn, TOut> Error(Exception e)
{
throw e;
}
public string Debug()
{
return
$"Script(pending=({string.Join(",", PendingInputs)} in, {string.Join(",", PendingOutputs)} out), remainingIns={string.Join("/", ProvidedInputs.Skip(InputCursor))}, remainingOuts={string.Join("/", ExpectedOutputs.Skip(OutputCursor))})";
}
}
protected class ScriptRunner<TIn, TOut, TMat> : ChainSetup<TIn, TOut, TMat>
{
private readonly int _maximumRequests;
private readonly int _maximumBuffer;
private readonly List<string> _debugLog = new List<string>();
private Script<TIn, TOut> _currentScript;
private int _remainingDemand;
private long _pendingRequests;
private long _outstandingDemand;
private bool _completed;
public ScriptRunner(
Func<Flow<TIn, TIn, NotUsed>, Flow<TIn, TOut, TMat>> op,
ActorMaterializerSettings settings,
Script<TIn, TOut> script,
int maximumOverrun,
int maximumRequests,
int maximumBuffer,
TestKitBase system) : base(op, settings, ToPublisher, system)
{
_currentScript = script;
_maximumRequests = maximumRequests;
_maximumBuffer = maximumBuffer;
_remainingDemand = _currentScript.ExpectedOutputs.Length + ThreadLocalRandom.Current.Next(1, maximumOverrun);
DebugLog($"Starting with remaining demand={_remainingDemand}");
}
public new async Task<ScriptRunner<TIn, TOut, TMat>> InitializeAsync()
{
await base.InitializeAsync();
return this;
}
public bool MayProvideInput => _currentScript.SomeInputsPending && (_pendingRequests > 0) && (_currentScript.PendingOutputs <= _maximumBuffer);
public bool MayRequestMore => _remainingDemand > 0;
public int GetNextDemand()
{
var max = Math.Min(_remainingDemand, _maximumRequests);
if (max == 1)
{
_remainingDemand = 0;
return 1;
}
else
{
var demand = ThreadLocalRandom.Current.Next(1, max);
_remainingDemand -= demand;
return demand;
}
}
public void DebugLog(string str)
{
_debugLog.Add(str);
}
public void Request(int demand)
{
DebugLog($"Test environment requests {demand}");
DownstreamSubscription.Request(demand);
_outstandingDemand += demand;
}
public async Task<bool> ShakeItAsync()
{
var oneMilli = TimeSpan.FromMilliseconds(10);
var marker = new object();
var u = await Upstream.ReceiveWhileAsync(oneMilli, filter: msg =>
{
if (msg is TestPublisher.RequestMore more)
{
DebugLog($"Operation requests {more.NrOfElements}");
_pendingRequests += more.NrOfElements;
return marker;
}
DebugLog($"Operation received {msg}");
return null;
}).ToListAsync();
var d = await Downstream.ReceiveWhileAsync(oneMilli, filter: msg =>
{
switch (msg)
{
case TestSubscriber.OnNext<TOut> next:
DebugLog($"Operation produces [{next.Element}]");
if (_outstandingDemand == 0)
throw new Exception("operation produced while there was no demand");
_outstandingDemand--;
_currentScript = _currentScript.ConsumeOutput(next.Element);
return marker;
case TestSubscriber.OnComplete _:
DebugLog("Operation complete.");
_currentScript = _currentScript.Complete();
return marker;
case TestSubscriber.OnError error:
_currentScript = _currentScript.Error(error.Cause);
return marker;
default:
return null;
}
})
.ToListAsync();
return u.Concat(d).Any(x => x == marker);
}
public async Task RunAsync()
{
try
{
DebugLog($"Running {_currentScript}");
Request(GetNextDemand());
var idleRounds = 0;
while (true)
{
if (idleRounds > 250) throw new Exception("Too many idle rounds");
if (_currentScript.Completed)
break;
idleRounds = await ShakeItAsync() ? 0 : idleRounds + 1;
var tieBreak = ThreadLocalRandom.Current.Next(0, 1) == 0;
if (MayProvideInput && (!MayRequestMore || tieBreak))
{
var (input, nextScript) = _currentScript.ProvideInput();
DebugLog($"Test environment produces [{input}]");
_pendingRequests--;
_currentScript = nextScript;
UpstreamSubscription.SendNext(input);
}
else if (MayRequestMore && (!MayProvideInput || !tieBreak))
{
Request(GetNextDemand());
}
else
{
if (_currentScript.NoInputsPending && !_completed)
{
DebugLog("Test environment completes");
UpstreamSubscription.SendComplete();
_completed = true;
return; // don't execute again if completed
}
}
}
}
catch (Exception)
{
Console.WriteLine(
$"Steps leading to failure:\n{string.Join("\n", _debugLog)}\nCurrentScript: {_currentScript.Debug()}");
throw;
}
}
}
protected ScriptedTest(ActorSystem system, ITestOutputHelper output = null) : base(system, output)
{
}
protected ScriptedTest(Config config, ITestOutputHelper output = null) : base(config, output)
{
}
protected ScriptedTest(string config, ITestOutputHelper output = null) : base(config, output)
{
}
protected ScriptedTest(ITestOutputHelper output = null) : base(output)
{
}
[Obsolete("Will be removed after async_testkit conversion is done. Use RunScriptAsync instead")]
protected void RunScript<TIn2, TOut2, TMat2>(
Script<TIn2, TOut2> script,
ActorMaterializerSettings settings,
Func<Flow<TIn2, TIn2, NotUsed>, Flow<TIn2, TOut2, TMat2>> op,
int maximumOverrun = 3,
int maximumRequest = 3,
int maximumBuffer = 3,
AkkaSpec spec = null)
=> RunScriptAsync(spec, script, settings, op, maximumOverrun, maximumRequest, maximumBuffer)
.ConfigureAwait(false).GetAwaiter().GetResult();
protected async Task RunScriptAsync<TIn2, TOut2, TMat2>(
AkkaSpec spec,
Script<TIn2, TOut2> script,
ActorMaterializerSettings settings,
Func<Flow<TIn2, TIn2, NotUsed>, Flow<TIn2, TOut2, TMat2>> op,
int maximumOverrun = 3,
int maximumRequest = 3,
int maximumBuffer = 3)
{
var runner = new ScriptRunner<TIn2, TOut2, TMat2>(op, settings, script, maximumOverrun, maximumRequest, maximumBuffer, this);
async Task Run()
{
await runner.InitializeAsync();
await runner.RunAsync();
}
if(spec != null)
await spec.AssertAllStagesStoppedAsync(async () =>
{
await Run();
}, runner.Materializer);
else
await Run();
}
protected static IPublisher<TOut> ToPublisher<TOut>(Source<TOut, NotUsed> source, IMaterializer materializer)
{
return source.RunWith(Sink.AsPublisher<TOut>(false), materializer);
}
}
}