-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
154 lines (141 loc) · 5.42 KB
/
Program.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
using System;
using System.Data.Common;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Newtonsoft.Json;
using Npgsql;
using StackExchange.Redis;
namespace Worker
{
public class Program
{
public static int Main(string[] args)
{
try
{
var pgsql = OpenDbConnection("Server=db;Username=postgres;Password=postgres;");
var redisConn = OpenRedisConnection("redis");
var redis = redisConn.GetDatabase();
// Keep alive is not implemented in Npgsql yet. This workaround was recommended:
// https://github.com/npgsql/npgsql/issues/1214#issuecomment-235828359
var keepAliveCommand = pgsql.CreateCommand();
keepAliveCommand.CommandText = "SELECT 1";
var definition = new { vote = "", voter_id = "" };
while (true)
{
// Slow down to prevent CPU spike, only query each 100ms
Thread.Sleep(100);
// Reconnect redis if down
if (redisConn == null || !redisConn.IsConnected) {
Console.WriteLine("Reconnecting Redis");
redisConn = OpenRedisConnection("redis");
redis = redisConn.GetDatabase();
}
string json = redis.ListLeftPopAsync("votes").Result;
if (json != null)
{
var vote = JsonConvert.DeserializeAnonymousType(json, definition);
Console.WriteLine($"Processing vote for '{vote.vote}' by '{vote.voter_id}'");
// Reconnect DB if down
if (!pgsql.State.Equals(System.Data.ConnectionState.Open))
{
Console.WriteLine("Reconnecting DB");
pgsql = OpenDbConnection("Server=db;Username=postgres;Password=postgres;");
}
else
{ // Normal +1 vote requested
UpdateVote(pgsql, vote.voter_id, vote.vote);
}
}
else
{
keepAliveCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
return 1;
}
}
private static NpgsqlConnection OpenDbConnection(string connectionString)
{
NpgsqlConnection connection;
while (true)
{
try
{
connection = new NpgsqlConnection(connectionString);
connection.Open();
break;
}
catch (SocketException)
{
Console.Error.WriteLine("Waiting for db");
Thread.Sleep(1000);
}
catch (DbException)
{
Console.Error.WriteLine("Waiting for db");
Thread.Sleep(1000);
}
}
Console.Error.WriteLine("Connected to db");
var command = connection.CreateCommand();
command.CommandText = @"CREATE TABLE IF NOT EXISTS votes (
id VARCHAR(255) NOT NULL UNIQUE,
vote VARCHAR(255) NOT NULL
)";
command.ExecuteNonQuery();
return connection;
}
private static ConnectionMultiplexer OpenRedisConnection(string hostname)
{
// Use IP address to workaround https://github.com/StackExchange/StackExchange.Redis/issues/410
var ipAddress = GetIp(hostname);
Console.WriteLine($"Found redis at {ipAddress}");
while (true)
{
try
{
Console.Error.WriteLine("Connecting to redis");
return ConnectionMultiplexer.Connect(ipAddress);
}
catch (RedisConnectionException)
{
Console.Error.WriteLine("Waiting for redis");
Thread.Sleep(1000);
}
}
}
private static string GetIp(string hostname)
=> Dns.GetHostEntryAsync(hostname)
.Result
.AddressList
.First(a => a.AddressFamily == AddressFamily.InterNetwork)
.ToString();
private static void UpdateVote(NpgsqlConnection connection, string voterId, string vote)
{
var command = connection.CreateCommand();
try
{
command.CommandText = "INSERT INTO votes (id, vote) VALUES (@id, @vote)";
command.Parameters.AddWithValue("@id", voterId);
command.Parameters.AddWithValue("@vote", vote);
command.ExecuteNonQuery();
}
catch (DbException)
{
command.CommandText = "UPDATE votes SET vote = @vote WHERE id = @id";
command.ExecuteNonQuery();
}
finally
{
command.Dispose();
}
}
}
}