forked from influxdata/influxdb-client-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractQueryClient.cs
355 lines (291 loc) · 11.7 KB
/
AbstractQueryClient.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using InfluxDB.Client.Core.Exceptions;
using InfluxDB.Client.Core.Flux.Domain;
using InfluxDB.Client.Core.Flux.Internal;
using Newtonsoft.Json.Linq;
using RestSharp;
namespace InfluxDB.Client.Core.Internal
{
public abstract class AbstractQueryClient
{
protected static readonly Action EmptyAction = () => { };
protected static readonly Action<Exception> ErrorConsumer = e => throw e;
private readonly FluxCsvParser _csvParser = new FluxCsvParser();
protected readonly RestClient RestClient;
protected readonly IFluxResultMapper Mapper;
protected AbstractQueryClient(RestClient restClient, IFluxResultMapper mapper)
{
Arguments.CheckNotNull(restClient, nameof(restClient));
Arguments.CheckNotNull(mapper, nameof(mapper));
RestClient = restClient;
Mapper = mapper;
}
protected Task Query(RestRequest query, FluxCsvParser.IFluxResponseConsumer responseConsumer,
Action<Exception> onError,
Action onComplete)
{
void Consumer(ICancellable cancellable, Stream bufferedStream)
{
try
{
_csvParser.ParseFluxResponse(bufferedStream, cancellable, responseConsumer);
}
catch (IOException e)
{
onError(e);
}
}
return Query(query, Consumer, onError, onComplete);
}
protected Task QueryRaw(RestRequest query,
Action<ICancellable, string> onResponse,
Action<Exception> onError,
Action onComplete)
{
void Consumer(ICancellable cancellable, Stream bufferedStream)
{
try
{
ParseFluxResponseToLines(line => onResponse(cancellable, line), cancellable, bufferedStream);
}
catch (IOException e)
{
CatchOrPropagateException(e, onError);
}
}
return Query(query, Consumer, onError, onComplete);
}
protected void QuerySync(RestRequest query, FluxCsvParser.IFluxResponseConsumer responseConsumer,
Action<Exception> onError,
Action onComplete)
{
void Consumer(ICancellable cancellable, Stream bufferedStream)
{
try
{
_csvParser.ParseFluxResponse(bufferedStream, cancellable, responseConsumer);
}
catch (IOException e)
{
onError(e);
}
}
QuerySync(query, Consumer, onError, onComplete);
}
private async Task Query(RestRequest query, Action<ICancellable, Stream> consumer,
Action<Exception> onError, Action onComplete)
{
Arguments.CheckNotNull(query, "query");
Arguments.CheckNotNull(consumer, "consumer");
Arguments.CheckNotNull(onError, "onError");
Arguments.CheckNotNull(onComplete, "onComplete");
try
{
var cancellable = new DefaultCancellable();
BeforeIntercept(query);
query.AdvancedResponseWriter = (responseStream, response) =>
{
responseStream = AfterIntercept((int)response.StatusCode, () => response.Headers, responseStream);
RaiseForInfluxError(response, responseStream);
consumer(cancellable, responseStream);
};
var restResponse = await RestClient.ExecuteAsync(query, Method.POST).ConfigureAwait(false);
if (restResponse.ErrorException != null)
{
throw restResponse.ErrorException;
}
if (!cancellable.IsCancelled())
{
onComplete();
}
}
catch (Exception e)
{
onError(e);
}
}
private void QuerySync(RestRequest query, Action<ICancellable, Stream> consumer,
Action<Exception> onError, Action onComplete)
{
Arguments.CheckNotNull(query, "query");
Arguments.CheckNotNull(consumer, "consumer");
Arguments.CheckNotNull(onError, "onError");
Arguments.CheckNotNull(onComplete, "onComplete");
try
{
var cancellable = new DefaultCancellable();
BeforeIntercept(query);
query.AdvancedResponseWriter = (responseStream, response) =>
{
responseStream = AfterIntercept((int)response.StatusCode, () => response.Headers, responseStream);
RaiseForInfluxError(response, responseStream);
consumer(cancellable, responseStream);
};
var restResponse = RestClient.Execute(query, Method.POST);
if (restResponse.ErrorException != null)
{
throw restResponse.ErrorException;
}
if (!cancellable.IsCancelled())
{
onComplete();
}
}
catch (Exception e)
{
onError(e);
}
}
protected async IAsyncEnumerable<T> QueryEnumerable<T>(RestRequest query, [EnumeratorCancellation] CancellationToken cancellationToken)
{
Arguments.CheckNotNull(query, nameof(query));
BeforeIntercept(query);
var response = await RestClient.ExecuteAsync(query, cancellationToken).ConfigureAwait(false);
response.Content = AfterIntercept((int)response.StatusCode, () => LoggingHandler.ToHeaders(response.Headers), response.Content);
RaiseForInfluxError(response, response.Content);
await foreach(var (_, record) in _csvParser.ParseFluxResponseAsync(new StringReader(response.Content), cancellationToken).ConfigureAwait(false))
{
if (!(record is null))
yield return Mapper.ConvertToEntity<T>(record);
}
}
protected abstract void BeforeIntercept(RestRequest query);
protected abstract T AfterIntercept<T>(int statusCode, Func<IList<HttpHeader>> headers, T body);
protected void ParseFluxResponseToLines(Action<String> onResponse,
ICancellable cancellable,
Stream bufferedStream)
{
using (var sr = new StreamReader(bufferedStream))
{
string line;
while ((line = sr.ReadLine()) != null && !cancellable.IsCancelled())
{
onResponse(line);
}
}
}
public class FluxResponseConsumerPoco : FluxCsvParser.IFluxResponseConsumer
{
private readonly Action<ICancellable, object> _onNext;
private readonly IFluxResultMapper _converter;
private readonly Type _type;
public FluxResponseConsumerPoco(Action<ICancellable, object> onNext, IFluxResultMapper converter, Type type)
{
_onNext = onNext;
_converter = converter;
_type = type;
}
public void Accept(int index, ICancellable cancellable, FluxTable table)
{
}
public void Accept(int index, ICancellable cancellable, FluxRecord record)
{
_onNext(cancellable, _converter.ConvertToEntity(record,_type));
}
}
public class FluxResponseConsumerPoco<T> : FluxCsvParser.IFluxResponseConsumer
{
private readonly Action<ICancellable, T> _onNext;
private readonly IFluxResultMapper _converter;
public FluxResponseConsumerPoco(Action<ICancellable, T> onNext, IFluxResultMapper converter)
{
_onNext = onNext;
_converter = converter;
}
public void Accept(int index, ICancellable cancellable, FluxTable table)
{
}
public void Accept(int index, ICancellable cancellable, FluxRecord record)
{
_onNext(cancellable, _converter.ConvertToEntity<T>(record));
}
}
public static string GetDefaultDialect()
{
var json = new JObject();
json.Add("header", true);
json.Add("delimiter", ",");
json.Add("quoteChar", "\"");
json.Add("commentPrefix", "#");
json.Add("annotations", new JArray("datatype", "group", "default"));
return json.ToString();
}
public static string CreateBody(string dialect, string query)
{
Arguments.CheckNonEmptyString(query, "Flux query");
var json = new JObject();
json.Add("query", query);
if (!string.IsNullOrEmpty(dialect))
{
json.Add("dialect", JObject.Parse(dialect));
}
return json.ToString();
}
protected void CatchOrPropagateException(Exception exception,
Action<Exception> onError)
{
Arguments.CheckNotNull(exception, "exception");
Arguments.CheckNotNull(onError, "onError");
//
// Socket closed by remote server or end of data
//
if (IsCloseException(exception))
{
Trace.WriteLine("Socket closed by remote server or end of data");
Trace.WriteLine(exception);
}
else
{
onError(exception);
}
}
private bool IsCloseException(Exception exception)
{
Arguments.CheckNotNull(exception, "exception");
return exception is EndOfStreamException;
}
protected void RaiseForInfluxError(object result, object body)
{
if (result is IRestResponse restResponse)
{
if (restResponse.IsSuccessful) return;
if (restResponse.ErrorException is InfluxException)
{
throw restResponse.ErrorException;
}
throw HttpException.Create(restResponse, body);
}
var httpResponse = (IHttpResponse) result;
if ((int) httpResponse.StatusCode >= 200 && (int) httpResponse.StatusCode < 300)
{
return;
}
if (httpResponse.ErrorException is InfluxException)
{
throw httpResponse.ErrorException;
}
throw HttpException.Create(httpResponse, body);
}
protected class FluxResponseConsumerRecord : FluxCsvParser.IFluxResponseConsumer
{
private readonly Action<ICancellable, FluxRecord> _onNext;
public FluxResponseConsumerRecord(Action<ICancellable, FluxRecord> onNext)
{
_onNext = onNext;
}
public void Accept(int index, ICancellable cancellable, FluxTable table)
{
}
public void Accept(int index, ICancellable cancellable, FluxRecord record)
{
_onNext(cancellable, record);
}
}
}
}