forked from influxdata/influxdb-client-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWriteApiTest.cs
485 lines (389 loc) · 17.7 KB
/
WriteApiTest.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core;
using InfluxDB.Client.Core.Exceptions;
using InfluxDB.Client.Core.Test;
using InfluxDB.Client.Writes;
using NUnit.Framework;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
namespace InfluxDB.Client.Test
{
[TestFixture]
public class WriteApiTest : AbstractMockServerTest
{
[SetUp]
public new void SetUp()
{
_influxDbClient = InfluxDBClientFactory.Create(MockServerUrl, "token");
_writeApi = _influxDbClient.GetWriteApi(WriteOptions.CreateNew().RetryInterval(1_000).Build());
}
[TearDown]
public new void ResetServer()
{
_influxDbClient.Dispose();
_writeApi.Dispose();
}
private WriteApi _writeApi;
private InfluxDBClient _influxDbClient;
private IResponseBuilder CreateResponse(string error, int status)
{
return CreateResponse($"{{\"error\":\"{error}\"}}",
"application/json")
.WithHeader("X-Influx-Error", error)
.WithStatusCode(status);
}
internal class EventListener
{
private readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
private readonly List<EventArgs> _events = new List<EventArgs>();
internal EventListener(WriteApi writeApi)
{
writeApi.EventHandler += (sender, args) =>
{
_events.Add(args);
_autoResetEvent.Set();
};
}
internal T Get<T>() where T : EventArgs
{
if (_events.Count == 0)
{
_autoResetEvent.Reset();
var timeout = TimeSpan.FromSeconds(10);
var waitOne = _autoResetEvent.WaitOne(timeout);
if (!waitOne) Assert.Fail($"The event {typeof(T)} didn't arrive in {timeout}.");
}
var args = _events[0];
_events.RemoveAt(0);
Trace.WriteLine(args);
if (args is T result)
{
return result;
}
throw new InvalidCastException($"{args.GetType().FullName} cannot be cast to {typeof(T).FullName}");
}
internal int EventCount()
{
return _events.Count;
}
internal EventListener WaitToSuccess()
{
Get<WriteSuccessEvent>();
return this;
}
}
[Test]
public void DisposeCallFromInfluxDbClientToWriteApi()
{
var writeApi = _influxDbClient.GetWriteApi();
Assert.False(writeApi.Disposed);
_influxDbClient.Dispose();
Assert.True(writeApi.Disposed);
}
[Test]
public void DisposedClientRemovedFromApis()
{
var writeApi = _influxDbClient.GetWriteApi();
Assert.False(writeApi.Disposed);
writeApi.Dispose();
Assert.True(writeApi.Disposed);
_influxDbClient.Dispose();
// nothing bad happens
}
[Test]
public void Retry()
{
var listener = new EventListener(_writeApi);
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.InScenario("Retry")
.WillSetStateTo("Retry Started")
.RespondWith(CreateResponse("token is temporarily over quota", 429));
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.InScenario("Retry")
.WhenStateIs("Retry Started")
.WillSetStateTo("Retry Finished")
.RespondWith(CreateResponse("{}"));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
//
// First request got Retry exception
//
var retriableErrorEvent = listener.Get<WriteRetriableErrorEvent>();
Assert.AreEqual("token is temporarily over quota", retriableErrorEvent.Exception.Message);
Assert.AreEqual(429, ((HttpException) retriableErrorEvent.Exception).Status);
Assert.GreaterOrEqual(retriableErrorEvent.RetryInterval, 1000);
Assert.LessOrEqual(retriableErrorEvent.RetryInterval, 2000);
//
// Second request success
//
var writeSuccessEvent = listener.Get<WriteSuccessEvent>();
Assert.AreEqual("h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1",
writeSuccessEvent.LineProtocol);
Assert.AreEqual(2, MockServer.LogEntries.Count());
Assert.AreEqual($"{MockServer.Urls[0]}/api/v2/write?org=org1&bucket=b1&precision=ns",
MockServer.LogEntries.ToList()[0].RequestMessage.Url);
Assert.AreEqual("h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1",
MockServer.LogEntries.ToList()[0].RequestMessage.Body);
Assert.AreEqual($"{MockServer.Urls[0]}/api/v2/write?org=org1&bucket=b1&precision=ns",
MockServer.LogEntries.ToList()[1].RequestMessage.Url);
Assert.AreEqual("h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1",
MockServer.LogEntries.ToList()[1].RequestMessage.Body);
}
[Test]
public void RetryNotApplied()
{
var listener = new EventListener(_writeApi);
//
// 400
//
MockServer.Reset();
MockServer
.Given(Request.Create().UsingPost())
.RespondWith(CreateResponse("line protocol poorly formed and no points were written", 400));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
_writeApi.Flush();
var error = listener.Get<WriteErrorEvent>();
Assert.IsNotNull(error);
Assert.AreEqual(typeof(BadRequestException), error.Exception.GetType());
Assert.AreEqual("line protocol poorly formed and no points were written", error.Exception.Message);
Assert.AreEqual(400, ((HttpException) error.Exception).Status);
//
// 401
//
MockServer.Reset();
MockServer
.Given(Request.Create().UsingPost())
.RespondWith(CreateResponse(
"token does not have sufficient permissions to write to this organization and bucket or the organization and bucket do not exist",
401));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
_writeApi.Flush();
error = listener.Get<WriteErrorEvent>();
Assert.IsNotNull(error);
Assert.AreEqual(typeof(UnauthorizedException), error.Exception.GetType());
Assert.AreEqual(
"token does not have sufficient permissions to write to this organization and bucket or the organization and bucket do not exist",
error.Exception.Message);
Assert.AreEqual(401, ((UnauthorizedException) error.Exception).Status);
//
// 403
//
MockServer.Reset();
MockServer
.Given(Request.Create().UsingPost())
.RespondWith(CreateResponse("no token was sent and they are required", 403));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
_writeApi.Flush();
error = listener.Get<WriteErrorEvent>();
Assert.IsNotNull(error);
Assert.AreEqual(typeof(ForbiddenException), error.Exception.GetType());
Assert.AreEqual("no token was sent and they are required", error.Exception.Message);
Assert.AreEqual(403, ((ForbiddenException) error.Exception).Status);
//
// 413
//
MockServer.Reset();
MockServer
.Given(Request.Create().UsingPost())
.RespondWith(CreateResponse(
"write has been rejected because the payload is too large. Error message returns max size supported. All data in body was rejected and not written",
413));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
_writeApi.Flush();
error = listener.Get<WriteErrorEvent>();
Assert.IsNotNull(error);
Assert.AreEqual(typeof(RequestEntityTooLargeException), error.Exception.GetType());
Assert.AreEqual(
"write has been rejected because the payload is too large. Error message returns max size supported. All data in body was rejected and not written",
error.Exception.Message);
Assert.AreEqual(413, ((RequestEntityTooLargeException) error.Exception).Status);
}
[Test]
public void RetryWithRetryAfter()
{
var listener = new EventListener(_writeApi);
MockServer.Reset();
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.InScenario("RetryWithRetryAfter")
.WillSetStateTo("RetryWithRetryAfter Started")
.RespondWith(CreateResponse("token is temporarily over quota", 429).WithHeader("Retry-After", "5"));
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.InScenario("RetryWithRetryAfter")
.WhenStateIs("RetryWithRetryAfter Started")
.WillSetStateTo("RetryWithRetryAfter Finished")
.RespondWith(CreateResponse("{}"));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
// Retry response
listener.Get<WriteRetriableErrorEvent>();
// Success response
listener.Get<WriteSuccessEvent>();
var requests = MockServer.LogEntries.ToList();
Assert.AreEqual(2, requests.Count);
var request1 = requests[0].RequestMessage.DateTime;
var request2 = requests[1].RequestMessage.DateTime;
var timeSpan = request2 - request1;
Assert.That(timeSpan, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(5)));
}
[Test]
public void RetryOnNetworkError()
{
MockServer.Stop();
_writeApi.Dispose();
var options = WriteOptions.CreateNew()
.BatchSize(1)
.MaxRetryDelay(2_000)
.MaxRetries(3)
.Build();
_writeApi = _influxDbClient.GetWriteApi(options);
var listener = new EventListener(_writeApi);
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
// Three attempts
listener.Get<WriteRetriableErrorEvent>();
listener.Get<WriteRetriableErrorEvent>();
listener.Get<WriteRetriableErrorEvent>();
}
[Test]
public void RetryContainsMessage()
{
MockServer.Reset();
_writeApi.Dispose();
const string json = "{\"code\":\"too many requests\"," +
"\"message\":\"org 04014de4ed590000 has exceeded limited_write plan limit\"}";
var response = CreateResponse(
json,
"application/json")
.WithHeader("Retry-After", "5")
.WithStatusCode(429);
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.InScenario("RetryWithRetryAfter")
.WillSetStateTo("RetryWithRetryAfter Started")
.RespondWith(response);
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.InScenario("RetryWithRetryAfter")
.WhenStateIs("RetryWithRetryAfter Started")
.WillSetStateTo("RetryWithRetryAfter Finished")
.RespondWith(CreateResponse("{}"));
var options = WriteOptions.CreateNew()
.BatchSize(1)
.RetryInterval(100)
.MaxRetries(1)
.Build();
_writeApi = _influxDbClient.GetWriteApi(options);
var listener = new EventListener(_writeApi);
var writer = new StringWriter();
Trace.Listeners.Add(new TextWriterTraceListener(writer));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
// One attempt
listener.Get<WriteRetriableErrorEvent>();
const string message = "The retriable error occurred during writing of data. " +
"Reason: 'org 04014de4ed590000 has exceeded limited_write plan limit'. " +
"Retry in: 5s.";
StringAssert.Contains(message, writer.ToString());
}
[Test]
public void TwiceDispose()
{
_writeApi.Dispose();
_writeApi.Dispose();
_influxDbClient.Dispose();
_influxDbClient.Dispose();
}
[Test]
public void WaitToCondition()
{
var writer = new StringWriter();
Trace.Listeners.Add(new TextWriterTraceListener(writer));
WriteApi.WaitToCondition(() => true, 30000);
WriteApi.WaitToCondition(() => false, 1);
WriteApi.WaitToCondition(() => false, 1000);
StringAssert.Contains("The WriteApi can't be gracefully dispose! - 1ms", writer.ToString());
StringAssert.DoesNotContain("The WriteApi can't be gracefully dispose! - 30000ms", writer.ToString());
StringAssert.Contains("The WriteApi can't be gracefully dispose! - 1000ms", writer.ToString());
}
[Test]
public void UserAgentHeader()
{
var listener = new EventListener(_writeApi);
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.RespondWith(CreateResponse("{}"));
_writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
"h2o_feet,location=coyote_creek level\\ description=\"feet 1\",water_level=1.0 1");
listener.Get<WriteSuccessEvent>();
var request= MockServer.LogEntries.Last();
StringAssert.StartsWith("influxdb-client-csharp/3.", request.RequestMessage.Headers["User-Agent"].First());
StringAssert.EndsWith(".0.0", request.RequestMessage.Headers["User-Agent"].First());
}
[Test]
public void WriteOptionsDefaults()
{
var options = WriteOptions.CreateNew().Build();
Assert.AreEqual(5_000, options.RetryInterval);
Assert.AreEqual(5, options.MaxRetries);
Assert.AreEqual(125_000, options.MaxRetryDelay);
Assert.AreEqual(2, options.ExponentialBase);
}
[Test]
public void WriteOptionsCustom()
{
var options = WriteOptions.CreateNew()
.RetryInterval(1_250)
.MaxRetries(25)
.MaxRetryDelay(1_800_000)
.ExponentialBase(2)
.Build();
Assert.AreEqual(1_250, options.RetryInterval);
Assert.AreEqual(25, options.MaxRetries);
Assert.AreEqual(1_800_000, options.MaxRetryDelay);
Assert.AreEqual(2, options.ExponentialBase);
}
[Test]
public void WriteRuntimeException()
{
var listener = new EventListener(_writeApi);
MockServer
.Given(Request.Create().WithPath("/api/v2/write").UsingPost())
.RespondWith(CreateResponse("{}"));
var measurement = new SimpleModel
{
Time = new DateTime(2020, 11, 15, 8, 20, 15),
Device = "id-1",
Value = 15
};
_writeApi.WriteMeasurement("b1", "org1", WritePrecision.S, measurement);
var error = listener.Get<WriteRuntimeExceptionEvent>();
Assert.IsNotNull(error);
StringAssert.StartsWith("Timestamps must be specified as UTC", error.Exception.Message);
Assert.AreEqual(0, MockServer.LogEntries.Count());
}
}
[Measurement("m")]
public class SimpleModel
{
[Column(IsTimestamp = true)]
public DateTime Time { get; set; }
[Column("device", IsTag = true)]
public string Device { get; set; }
[Column("value")]
public int Value { get; set; }
}
}