-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.cs
186 lines (150 loc) · 6.51 KB
/
Worker.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
using Npgsql;
using RinhaPessimisticLockingApi;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Sharding
{
public class Worker : BackgroundService
{
public static ConcurrentDictionary<int, ConcurrentQueue<Transaction>> queue = new ConcurrentDictionary<int, ConcurrentQueue<Transaction>>();
public static ConcurrentDictionary<Transaction, Account> result = new ConcurrentDictionary<Transaction, Account>();
public Worker()
{
for (int i = 1; i < 6; i++)
queue[i] = new ConcurrentQueue<Transaction>();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
NpgsqlConnectionStringBuilder b = new NpgsqlConnectionStringBuilder();
b.Host = "db";
b.Port = 5432;
b.Database = "rinha";
b.Username = "theuser";
b.Password = "TheP@ssw0rd!";
b.Pooling = true;
b.MinPoolSize = 6;
b.MaxPoolSize = 25;
//b.MaxAutoPrepare = 50;
//b.AutoPrepareMinUsages = 1;
var dataSourceBuilder = new NpgsqlDataSourceBuilder(b.ToString());
var dataSource = dataSourceBuilder.Build();
var tasks = Enumerable.Range(1, queue.Count)
.Select(x => Task.Run(async () =>
{
await QueueProcessor(x, dataSource);
})).ToList();
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(500);
}
tasks.ToList().ForEach(x => x.Dispose());
}
private async Task QueueProcessor(int accountId, NpgsqlDataSource dataSource)
{
Account account = await GetAccount(accountId, dataSource);
var originalBalance = account.Saldo;
ConcurrentQueue<Transaction> processor;
while (!queue.TryGetValue(accountId, out processor))
{
await Task.Delay(20);
}
List<Transaction> transactions = new List<Transaction>(20);
while (true)
{
await Task.Delay(3);
Transaction t = null;
while (transactions.Count < 500
&& processor.TryDequeue(out t))
{
transactions.Add(t);
}
if (!transactions.Any()) continue;
List<Transaction> unprocesable = new List<Transaction>();
var transactionAccVal = account.Saldo;
foreach (var x in transactions)
{
var fixedTransactionValue = x.Tipo == "c" ? (int)x.Valor.Value : (int)-x.Valor.Value;
if (transactionAccVal + fixedTransactionValue > -account.Limite)
{
transactionAccVal += fixedTransactionValue;
}
else
unprocesable.Add(x);
}
transactions = transactions.Except(unprocesable).ToList();
if(transactions.Any())
await ProcessTransactions(accountId, account, transactions, dataSource);
transactions.ForEach(x =>
{
account.Saldo += x.Tipo == "c" ? (int)x.Valor.Value : (int)-x.Valor.Value;
result.TryAdd(x, new Account(account.Limite, account.Saldo));
});
unprocesable.ForEach(x => result.TryAdd(x, null));
transactions.Clear();
unprocesable.Clear();
}
}
async Task<bool> ProcessTransactions(int accountId, Account account, List<Transaction> transactions, NpgsqlDataSource dataSource)
{
if (transactions.Count > 1)
await Console.Out.WriteLineAsync("virsinator " + transactions.Count);
int index = 0;
var finalBalance = account.Saldo + transactions.Sum(x => x.Tipo == "c" ? x.Valor.Value : -x.Valor.Value);
string accQuery = "update accounts set balance = @balance where id = @accountId";
string query = @"
insert into transactions(accountid, amount, transactiontype, description)
VALUES " + String.Join(",\n", transactions.Select(x => $"(@v{++index}, @v{++index}, @v{++index}, @v{++index})"));
await using (var conn = await dataSource.OpenConnectionAsync())
await using (var cmd = conn.CreateCommand())
{
Stopwatch s = new Stopwatch();
s.Start();
cmd.CommandText = accQuery;
cmd.Parameters.AddWithValue("@balance", finalBalance);
cmd.Parameters.AddWithValue("@accountId", accountId);
cmd.ExecuteNonQuery();
cmd.CommandText = query;
index = 0;
transactions.ForEach(x =>
{
cmd.Parameters.AddWithValue($"@v{++index}", accountId);
cmd.Parameters.AddWithValue($"@v{++index}", x.Valor);
cmd.Parameters.AddWithValue($"@v{++index}", x.Tipo);
cmd.Parameters.AddWithValue($"@v{++index}", x.Descricao);
});
var result = await cmd.ExecuteNonQueryAsync();
s.Stop();
await Console.Out.WriteLineAsync("db: " + s.ElapsedMilliseconds.ToString());
return true;
}
}
async Task<Account> GetAccount(int accountId, NpgsqlDataSource dataSource)
{
try
{
var query = "select * from accounts where id = @accountId limit 1";
await using (var conn = await dataSource.OpenConnectionAsync())
await using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@accountId", accountId);
var r = await cmd.ExecuteReaderAsync();
if (r.Read())
{
var limit = r.GetInt32(2);
var balance = r.GetInt32(3);
return new Account(limit, balance);
}
}
return null;
}
catch (Exception e)
{
await Task.Delay(1000);
return await GetAccount(accountId, dataSource);
}
}
}
}