Datei: StressTests/StressTest/Worker.cs

Last Commit (9de6a8c)
1 -- File didn't exist --
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
New Commit (bbf1d57)
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Threading;
5 using System.Threading.Tasks;
6 using NDO;
7 using NDO.Linq;
8 using StressTestClasses;
9
10 namespace StressTest
11 {
12 ····/// <summary>
13 ····/// Thrown if the data read from the database doesn't match the expected data.
14 ····/// </summary>
15 ····public class VerificationException : Exception
16 ····{
17 ········public VerificationException( string message ) : base( message )
18 ········{
19 ········}
20 ····}
21
22 ····/// <summary>
23 ····/// A worker runs the test scenario in a loop. All database operations use the async API of NDO.
24 ····/// </summary>
25 ····/// <remarks>
26 ····/// Each step uses a new PersistenceManager, so that the data is really read from the database
27 ····/// and not from the cache of a PersistenceManager. The data of a worker is identified by the run id,
28 ····/// the worker number and the iteration, so that the workers don't interfere with each other, except
29 ····/// for the tags, which are shared by all workers.
30 ····/// </remarks>
31 ····public class Worker
32 ····{
33 ········readonly int workerNo;
34 ········readonly TestDatabase db;
35 ········readonly StressTestOptions options;
36 ········readonly Statistics statistics;
37 ········readonly int[] tagIds;
38 ········readonly string runId;
39 ········readonly Random random;
40
41 ········public Worker( int workerNo, TestDatabase db, StressTestOptions options, Statistics statistics, int[] tagIds, string runId )
42 ········{
43 ············this.workerNo = workerNo;
44 ············this.db = db;
45 ············this.options = options;
46 ············this.statistics = statistics;
47 ············this.tagIds = tagIds;
48 ············this.runId = runId;
49 ············this.random = new Random( workerNo );
50 ········}
51
52 ········static void Check( bool condition, string message )
53 ········{
54 ············if (!condition)
55 ················throw new VerificationException( message );
56 ········}
57
58 ········static int IdOf( object o ) => (int) ((IPersistenceCapable) o).NDOObjectId.Id[0];
59
60 ········/// <summary>
61 ········/// Runs the iterations until the number of iterations is reached, the time is up or cancellation is requested.
62 ········/// </summary>
63 ········/// <param name="endTime">If not null, the worker runs until this time instead of a fixed number of iterations.</param>
64 ········/// <param name="ct"></param>
65 ········public async Task RunAsync( DateTime? endTime, CancellationToken ct )
66 ········{
67 ············for (int iteration = 0; ; iteration++)
68 ············{
69 ················if (ct.IsCancellationRequested)
70 ····················break;
71 ················if (endTime.HasValue ? DateTime.UtcNow >= endTime.Value : iteration >= this.options.Iterations)
72 ····················break;
73
74 ················var state = new IterationState( $"{this.runId}-{this.workerNo}-{iteration}" );
75 ················try
76 ················{
77 ····················await RunIterationAsync( state, ct );
78 ····················this.statistics.IterationSucceeded();
79 ················}
80 ················catch (OperationCanceledException) when (ct.IsCancellationRequested)
81 ················{
82 ····················break;
83 ················}
84 ················catch (Exception ex)
85 ················{
86 ····················this.statistics.IterationFailed( new Statistics.ErrorInfo { Worker = this.workerNo, Iteration = iteration, Step = state.Step, Exception = ex } );
87 ····················if (this.options.StopOnFirstError)
88 ························throw;
89 ················}
90 ············}
91 ········}
92
93 ········class IterationState
94 ········{
95 ············public IterationState( string key )
96 ············{
97 ················OrderNumber = "O-" + key;
98 ················CustomerName = "C-" + key;
99 ············}
100
101 ············public string Step;
102 ············public readonly string OrderNumber;
103 ············public readonly string CustomerName;
104 ············public int OrderId;
105 ············public HashSet<int> ExpectedTagIds;
106 ············public int ExpectedLineCount;
107 ············public decimal ExpectedPriceSum;
108 ············public decimal ExpectedTotal;
109 ········}
110
111 ········async Task RunIterationAsync( IterationState s, CancellationToken ct )
112 ········{
113 ············s.Step = "Create";
114 ············await CreateAsync( s, ct );
115 ············s.Step = "Read and change";
116 ············await ChangeAsync( s, ct );
117 ············s.Step = "Verify";
118 ············await VerifyAsync( s, ct );
119 ············s.Step = "Query";
120 ············await QueryAsync( ct );
121 ············s.Step = "Delete";
122 ············await DeleteAsync( s, ct );
123 ············s.Step = "Verify deletion";
124 ············await VerifyDeletionAsync( s, ct );
125 ········}
126
127 ········/// <summary>
128 ········/// Creates a customer and an order with lines and two tags.
129 ········/// </summary>
130 ········async Task CreateAsync( IterationState s, CancellationToken ct )
131 ········{
132 ············await using (var pm = this.db.NewPersistenceManager())
133 ············{
134 ················var customer = new Customer()
135 ················{
136 ····················Name = s.CustomerName,
137 ····················City = "City" + this.workerNo,
138 ····················// Some databases don't store fractions of seconds
139 ····················Created = new DateTime( 2026, 1, 1, 12, 0, 0 ).AddMinutes( this.workerNo )
140 ················};
141
142 ················var order = new SalesOrder()
143 ················{
144 ····················OrderNumber = s.OrderNumber,
145 ····················OrderDate = DateTime.Today,
146 ····················Status = "New",
147 ····················Customer = customer
148 ················};
149
150 ················for (int i = 0; i < this.options.LinesPerOrder; i++)
151 ····················order.NewLine( "Product" + i, i + 1, 1.25m * (i + 1) );
152 ················order.Total = order.ComputeTotal();
153
154 ················// FindObject creates hollow objects without database access
155 ················var tagIndexes = PickDistinct( 2 );
156 ················foreach (int index in tagIndexes)
157 ····················order.AddTag( (Tag) pm.FindObject( typeof( Tag ), this.tagIds[index] ) );
158
159 ················pm.MakePersistent( customer );
160 ················pm.MakePersistent( order );
161 ················await this.statistics.MeasureAsync( "SaveAsync (insert)", () => pm.SaveAsync( false, ct ) );
162
163 ················s.OrderId = IdOf( order );
164 ················Check( s.OrderId > 0, $"Order {s.OrderNumber} didn't get an id." );
165 ················Check( order.Lines.All( l => IdOf( l ) > 0 ), $"Not all lines of order {s.OrderNumber} got an id." );
166 ················s.ExpectedTagIds = new HashSet<int>( tagIndexes.Select( i => this.tagIds[i] ) );
167 ············}
168 ········}
169
170 ········/// <summary>
171 ········/// Reads the order, changes fields, lines, tags and the customer and saves the changes.
172 ········/// </summary>
173 ········async Task ChangeAsync( IterationState s, CancellationToken ct )
174 ········{
175 ············await using (var pm = this.db.NewPersistenceManager())
176 ············{
177 ················var order = await this.statistics.MeasureAsync( "VirtualTable.SingleAsync",
178 ····················() => pm.Objects<SalesOrder>().Where( o => o.OrderNumber == s.OrderNumber ).SingleAsync( ct ) );
179 ················Check( IdOf( order ) == s.OrderId, $"Order {s.OrderNumber}: wrong id {IdOf( order )}, expected {s.OrderId}." );
180
181 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "lines", false, ct ) );
182 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "tags", false, ct ) );
183 ················var lines = order.Lines.ToList();
184 ················Check( lines.Count == this.options.LinesPerOrder, $"Order {s.OrderNumber}: {lines.Count} lines read, expected {this.options.LinesPerOrder}." );
185 ················var tagIdsRead = new HashSet<int>( order.Tags.Select( IdOf ) );
186 ················Check( tagIdsRead.SetEquals( s.ExpectedTagIds ), $"Order {s.OrderNumber}: wrong tags [{String.Join( ",", tagIdsRead )}], expected [{String.Join( ",", s.ExpectedTagIds )}]." );
187
188 ················Customer customer = order.Customer;
189 ················Check( customer != null, $"Order {s.OrderNumber} has no customer." );
190 ················await this.statistics.MeasureAsync( "LoadDataAsync", () => pm.LoadDataAsync( customer, ct ) );
191 ················Check( customer.Name == s.CustomerName, $"Order {s.OrderNumber}: wrong customer '{customer.Name}', expected '{s.CustomerName}'." );
192
193 ················// Change fields, change a line, remove a line, add a line
194 ················order.Status = "Changed";
195 ················var first = lines.OrderBy( l => l.Product ).First();
196 ················first.Quantity += 10;
197 ················order.RemoveLine( lines.OrderBy( l => l.Product ).Last() );
198 ················order.NewLine( "Extra", 7, 3.5m );
199 ················order.Total = order.ComputeTotal();
200
201 ················// Replace one tag by another one
202 ················var removedTag = order.Tags.First();
203 ················order.RemoveTag( removedTag );
204 ················int newTagId = this.tagIds.First( id => !s.ExpectedTagIds.Contains( id ) );
205 ················order.AddTag( (Tag) pm.FindObject( typeof( Tag ), newTagId ) );
206
207 ················customer.UpdateCount++;
208
209 ················await this.statistics.MeasureAsync( "SaveAsync (update)", () => pm.SaveAsync( false, ct ) );
210
211 ················s.ExpectedTagIds.Remove( IdOf( removedTag ) );
212 ················s.ExpectedTagIds.Add( newTagId );
213 ················s.ExpectedLineCount = order.Lines.Count();
214 ················s.ExpectedPriceSum = order.Lines.Sum( l => l.Price );
215 ················s.ExpectedTotal = order.Total;
216 ············}
217 ········}
218
219 ········/// <summary>
220 ········/// Checks the changes with a new PersistenceManager.
221 ········/// </summary>
222 ········async Task VerifyAsync( IterationState s, CancellationToken ct )
223 ········{
224 ············await using (var pm = this.db.NewPersistenceManager())
225 ············{
226 ················int orderId = s.OrderId;
227 ················var lineQuery = pm.Objects<OrderLine>().Where( l => l.Order.Oid() == orderId );
228
229 ················var lines = await this.statistics.MeasureAsync( "VirtualTable.ToListAsync", () => lineQuery.ToListAsync( ct ) );
230 ················Check( lines.Count == s.ExpectedLineCount, $"Order {s.OrderNumber}: {lines.Count} lines found, expected {s.ExpectedLineCount}." );
231 ················Check( lines.Any( l => l.Product == "Extra" ), $"Order {s.OrderNumber}: the added line is missing." );
232 ················Check( !lines.Any( l => l.Product == "Product" + (this.options.LinesPerOrder - 1) ), $"Order {s.OrderNumber}: the removed line still exists." );
233
234 ················int count = await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => lineQuery.CountAsync( ct ) );
235 ················Check( count == s.ExpectedLineCount, $"Order {s.OrderNumber}: CountAsync returns {count}, expected {s.ExpectedLineCount}." );
236
237 ················// Note: Sum over an int field doesn't work, because NDO always computes sums as decimal and casts the result to TP
238 ················decimal priceSum = await this.statistics.MeasureAsync( "VirtualTable.SumAsync", () => lineQuery.SumAsync( l => l.Price, ct ) );
239 ················Check( priceSum == s.ExpectedPriceSum, $"Order {s.OrderNumber}: SumAsync returns {priceSum}, expected {s.ExpectedPriceSum}." );
240
241 ················// await foreach over a VirtualTable with a condition on a related object
242 ················string customerName = s.CustomerName;
243 ················var orders = await this.statistics.MeasureAsync( "VirtualTable await foreach", async () =>
244 ················{
245 ····················var result = new List<SalesOrder>();
246 ····················await foreach (var o in pm.Objects<SalesOrder>().Where( o => o.Customer.Name == customerName ).AsAsyncEnumerable( ct ))
247 ························result.Add( o );
248 ····················return result;
249 ················} );
250 ················Check( orders.Count == 1, $"Customer {customerName}: {orders.Count} orders found, expected 1." );
251
252 ················var order = orders[0];
253 ················Check( order.OrderNumber == s.OrderNumber, $"Customer {customerName}: wrong order {order.OrderNumber}, expected {s.OrderNumber}." );
254 ················Check( order.Status == "Changed", $"Order {s.OrderNumber}: status '{order.Status}', expected 'Changed'." );
255 ················Check( order.Total == s.ExpectedTotal, $"Order {s.OrderNumber}: total {order.Total}, expected {s.ExpectedTotal}." );
256 ················decimal linesTotal = lines.Sum( l => l.Quantity * l.Price );
257 ················Check( linesTotal == s.ExpectedTotal, $"Order {s.OrderNumber}: the lines sum up to {linesTotal}, expected {s.ExpectedTotal}." );
258
259 ················await this.statistics.MeasureAsync( "LoadRelationAsync", () => pm.LoadRelationAsync( order, "tags", false, ct ) );
260 ················var tagIdsRead = new HashSet<int>( order.Tags.Select( IdOf ) );
261 ················Check( tagIdsRead.SetEquals( s.ExpectedTagIds ), $"Order {s.OrderNumber}: wrong tags [{String.Join( ",", tagIdsRead )}], expected [{String.Join( ",", s.ExpectedTagIds )}]." );
262
263 ················var customer = await this.statistics.MeasureAsync( "VirtualTable.FirstOrDefaultAsync",
264 ····················() => pm.Objects<Customer>().Where( c => c.Name == customerName ).FirstOrDefaultAsync( ct ) );
265 ················Check( customer != null, $"Customer {customerName} not found." );
266 ················Check( customer.UpdateCount == 1, $"Customer {customerName}: UpdateCount is {customer.UpdateCount}, expected 1." );
267
268 ················// RefreshAsync reads the object again
269 ················await this.statistics.MeasureAsync( "RefreshAsync", () => pm.RefreshAsync( customer, ct ) );
270 ················Check( customer.UpdateCount == 1, $"Customer {customerName}: UpdateCount after RefreshAsync is {customer.UpdateCount}, expected 1." );
271 ············}
272 ········}
273
274 ········/// <summary>
275 ········/// Queries, which read data of other workers. The results can't be checked, because the other workers change the data.
276 ········/// </summary>
277 ········async Task QueryAsync( CancellationToken ct )
278 ········{
279 ············await using (var pm = this.db.NewPersistenceManager())
280 ············{
281 ················await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => pm.Objects<SalesOrder>().Where( o => o.Status == "Changed" ).CountAsync( ct ) );
282 ················var page = await this.statistics.MeasureAsync( "VirtualTable paged",
283 ····················() => pm.Objects<SalesOrder>().OrderByDescending( o => o.OrderNumber ).Take( 10 ).ToListAsync( ct ) );
284 ················Check( page.Count <= 10, $"Take(10) returned {page.Count} objects." );
285 ················int tagCount = await this.statistics.MeasureAsync( "VirtualTable.CountAsync", () => pm.Objects<Tag>().CountAsync( ct ) );
286 ················Check( tagCount == this.tagIds.Length, $"{tagCount} tags found, expected {this.tagIds.Length}." );
287 ············}
288 ········}
289
290 ········/// <summary>
291 ········/// Deletes the order with PersistenceManager.Delete (the composite relation deletes the lines and the mapping table entries)
292 ········/// and the customer with VirtualTable.DeleteDirectlyAsync.
293 ········/// </summary>
294 ········async Task DeleteAsync( IterationState s, CancellationToken ct )
295 ········{
296 ············await using (var pm = this.db.NewPersistenceManager())
297 ············{
298 ················var order = await this.statistics.MeasureAsync( "VirtualTable.SingleAsync",
299 ····················() => pm.Objects<SalesOrder>().Where( o => o.OrderNumber == s.OrderNumber ).SingleAsync( ct ) );
300 ················pm.Delete( order );
301 ················await this.statistics.MeasureAsync( "SaveAsync (delete)", () => pm.SaveAsync( false, ct ) );
302 ············}
303
304 ············await using (var pm = this.db.NewPersistenceManager())
305 ············{
306 ················string customerName = s.CustomerName;
307 ················await this.statistics.MeasureAsync( "VirtualTable.DeleteDirectlyAsync",
308 ····················() => pm.Objects<Customer>().Where( c => c.Name == customerName ).DeleteDirectlyAsync( ct ) );
309 ············}
310 ········}
311
312 ········async Task VerifyDeletionAsync( IterationState s, CancellationToken ct )
313 ········{
314 ············await using (var pm = this.db.NewPersistenceManager())
315 ············{
316 ················string orderNumber = s.OrderNumber;
317 ················string customerName = s.CustomerName;
318 ················int orderId = s.OrderId;
319
320 ················int orders = await pm.Objects<SalesOrder>().Where( o => o.OrderNumber == orderNumber ).CountAsync( ct );
321 ················Check( orders == 0, $"Order {orderNumber} still exists after deletion." );
322 ················int lines = await pm.Objects<OrderLine>().Where( l => l.Order.Oid() == orderId ).CountAsync( ct );
323 ················Check( lines == 0, $"Order {orderNumber}: {lines} lines still exist after deletion." );
324 ················int customers = await pm.Objects<Customer>().Where( c => c.Name == customerName ).CountAsync( ct );
325 ················Check( customers == 0, $"Customer {customerName} still exists after DeleteDirectlyAsync." );
326 ············}
327 ········}
328
329 ········int[] PickDistinct( int count )
330 ········{
331 ············return Enumerable.Range( 0, this.tagIds.Length ).OrderBy( _ => this.random.Next() ).Take( count ).ToArray();
332 ········}
333 ····}
334 }
335