Skip to content

Commit 453e18c

Browse files
committed
chore: (WIP - 2 failing test) use kwargs in batching mode.
1 parent d584301 commit 453e18c

5 files changed

Lines changed: 56 additions & 50 deletions

File tree

influxdb_client_3/__init__.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,6 @@ def write(self, record=None, database=None, **kwargs):
377377
:type database: str
378378
:param kwargs: Additional arguments to pass to the write API.
379379
"""
380-
print("DEBUG InfluxDBClient3.write")
381-
print(f"DEBUG kwargs {kwargs} ")
382380
if database is None:
383381
database = self._database
384382

influxdb_client_3/write_client/client/write_api.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,11 @@ def add_default_tag(self, key, value) -> None:
164164

165165

166166
class _BatchItemKey(object):
167-
def __init__(self, bucket, org, precision=DEFAULT_WRITE_PRECISION) -> None:
167+
def __init__(self, bucket, org, precision=DEFAULT_WRITE_PRECISION, **kwargs) -> None:
168168
self.bucket = bucket
169169
self.org = org
170170
self.precision = precision
171+
self.kwargs = kwargs
171172
pass
172173

173174
def __hash__(self) -> int:
@@ -178,8 +179,8 @@ def __eq__(self, o: object) -> bool:
178179
and self.bucket == o.bucket and self.org == o.org and self.precision == o.precision
179180

180181
def __str__(self) -> str:
181-
return '_BatchItemKey[bucket:\'{}\', org:\'{}\', precision:\'{}\']' \
182-
.format(str(self.bucket), str(self.org), str(self.precision))
182+
return '_BatchItemKey[bucket:\'{}\', org:\'{}\', precision:\'{}\', kwargs: \'{}\']' \
183+
.format(str(self.bucket), str(self.org), str(self.precision), str(self.kwargs))
183184

184185

185186
class _BatchItem(object):
@@ -378,8 +379,6 @@ def write(self, bucket: str, org: str = None,
378379
data_frame.index = pd.to_datetime(data_frame.index, unit='s')
379380
380381
""" # noqa: E501
381-
print("DEBUG WriteApi.write")
382-
print(f"DEBUG kwargs {kwargs}")
383382
org = get_org_query_param(org=org, client=self._influxdb_client)
384383

385384
self._append_default_tags(record)
@@ -477,7 +476,7 @@ def _write_batching(self, bucket, org, data,
477476
precision = self._write_options.write_precision
478477

479478
if isinstance(data, bytes):
480-
_key = _BatchItemKey(bucket, org, precision)
479+
_key = _BatchItemKey(bucket, org, precision, **kwargs)
481480
self._subject.on_next(_BatchItem(key=_key, data=data))
482481

483482
elif isinstance(data, str):
@@ -527,9 +526,8 @@ def _write_batching(self, bucket, org, data,
527526

528527
return None
529528

530-
def _http(self, batch_item: _BatchItem):
529+
def _http(self, batch_item: _BatchItem, **kwargs):
531530
logger.debug("Write time series data into InfluxDB: %s", batch_item)
532-
print("DEBUG _http")
533531

534532
if self._retry_callback:
535533
def _retry_callback_delegate(exception):
@@ -542,29 +540,28 @@ def _retry_callback_delegate(exception):
542540
retry = self._write_options.to_retry_strategy(retry_callback=_retry_callback_delegate)
543541

544542
self._post_write(False, batch_item.key.bucket, batch_item.key.org, batch_item.data,
545-
batch_item.key.precision, no_sync, urlopen_kw={'retries': retry})
543+
batch_item.key.precision, no_sync, urlopen_kw={'retries': retry}, **kwargs)
546544

547545
logger.debug("Write request finished %s", batch_item)
548546

549547
return _BatchResponse(data=batch_item)
550548

551549
def _post_write(self, _async_req, bucket, org, body, precision, no_sync, **kwargs):
552-
print("DEBUG WriteApi._post_write")
553-
print(f"DEBUG kwargs {kwargs} ")
554-
return self._write_service.post_write(org=org, bucket=bucket, body=body, precision=precision,
550+
return self._write_service.post_write(org=org, bucket=bucket, body=body, precision=precision,
555551
no_sync=no_sync,
556552
async_req=_async_req,
557553
content_type="text/plain; charset=utf-8",
558554
**kwargs)
559555

556+
560557
def _to_response(self, data: _BatchItem, delay: timedelta):
561558

562559
return rx.of(data).pipe(
563560
ops.subscribe_on(self._write_options.write_scheduler),
564561
# use delay if its specified
565562
ops.delay(duetime=delay, scheduler=self._write_options.write_scheduler),
566563
# invoke http call
567-
ops.map(lambda x: self._http(x)),
564+
ops.map(lambda x: self._http(x, **x.key.kwargs)),
568565
# catch exception to fail batch response
569566
ops.catch(handler=lambda exception, source: rx.just(_BatchResponse(exception=exception, data=data))),
570567
)

influxdb_client_3/write_client/service/write_service.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,6 @@ def post_write(self, org, bucket, body, **kwargs): # noqa: E501,D401,D403
4242
returns the request thread.
4343
""" # noqa: E501
4444

45-
print("DEBUG WriteService.post_write")
46-
print(f"DEBUG kwargs {kwargs}")
47-
4845
kwargs['_return_http_data_only'] = True
4946
if kwargs.get('async_req'):
5047
thread = self.post_write_with_http_info(org, bucket, body, **kwargs) # noqa: E501
@@ -139,8 +136,6 @@ def post_write_with_http_info(self, org, bucket, body, **kwargs): # noqa: E501,
139136
If the method is called asynchronously,
140137
returns the request thread.
141138
""" # noqa: E501
142-
print("DEBUG WriteService.post_write_with_http_info()")
143-
print(f"DEBUG kwargs {kwargs}")
144139
# noqa: E501
145140
local_var_params, path, path_params, query_params, header_params, body_params = \
146141
self._post_write_prepare(org, bucket, body, **kwargs) # noqa: E501

tests/test_influxdb_client_3_integration.py

Lines changed: 44 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -317,11 +317,12 @@ def set_error_result(rt, rd, rx):
317317
host=self.host,
318318
database=self.database,
319319
token=self.token,
320+
write_timeout=20,
320321
write_client_options=write_client_options(
321322
error_callback=set_error_result,
322323
write_options=WriteOptions(
323324
max_retry_time=0, # disable retries
324-
timeout=20,
325+
# timeout=20,
325326
write_type=WriteType.batching,
326327
max_retries=0,
327328
batch_size=1,
@@ -363,11 +364,12 @@ def retry_cb(args, data, excp):
363364
write_client_options=write_client_options(
364365
error_callback=set_error_result,
365366
retry_callback=retry_cb,
367+
write_timeout=20,
366368
write_options=WriteOptions(
367369
max_retry_time=10000,
368370
max_retry_delay=100,
369371
retry_interval=100,
370-
timeout=20,
372+
# timeout=20,
371373
max_retries=3,
372374
batch_size=1,
373375
)
@@ -387,32 +389,6 @@ def retry_cb(args, data, excp):
387389
self.assertIsInstance(ErrorResult["rx"], MaxRetryError)
388390
self.assertIsInstance(ErrorResult["rx"].reason, Url3TimeoutError)
389391

390-
def test_write_timeout_argument(self):
391-
with self.assertRaises(Url3TimeoutError):
392-
localClient = InfluxDBClient3(
393-
host=self.host,
394-
database=self.database,
395-
token=self.token,
396-
write_client_options=write_client_options(
397-
# error_callback=set_error_result,
398-
# retry_callback=retry_cb,
399-
# write_options=WriteOptions(
400-
# max_retry_time=10000,
401-
# max_retry_delay=0,
402-
# retry_interval=0,
403-
# timeout=20,
404-
# max_retries=0,
405-
# batch_size=1,
406-
# )
407-
)
408-
)
409-
410-
print(f"DEBUG client.write_options {localClient._write_client_options['write_options'].__dict__}")
411-
412-
lp = "test_write_timeout,location=harfa fVal=3.14,iVal=42i"
413-
# TODO investigate how the kwarg below can work with WriteType.batching...
414-
localClient.write(lp, _request_timeout=1)
415-
416392
@pytest.mark.skip(reason="flaky in CircleCI - server often responds in less than 1 millisecond.")
417393
def test_query_timeout(self):
418394
localClient = InfluxDBClient3(
@@ -435,3 +411,43 @@ def test_query_timeout_per_call_override(self):
435411

436412
with self.assertRaisesRegex(InfluxDB3ClientQueryError, ".*Deadline Exceeded.*"):
437413
localClient.query("SELECT * FROM data", timeout=0.0001)
414+
415+
def test_write_timeout_per_call_override(self):
416+
417+
ErrorResult = {"rt": None, "rd": None, "rx": None}
418+
419+
def set_error_result(rt, rd, rx):
420+
nonlocal ErrorResult
421+
ErrorResult = {"rt": rt, "rd": rd, "rx": rx}
422+
423+
retry_ct = 0
424+
425+
def retry_cb(args, data, excp):
426+
nonlocal retry_ct
427+
retry_ct += 1
428+
if excp is not None:
429+
raise excp
430+
431+
localClient = InfluxDBClient3(
432+
host=self.host,
433+
token=self.token,
434+
database=self.database,
435+
# write_timeout=3000,
436+
write_client_options=write_client_options(
437+
error_callback=set_error_result,
438+
retry_callback=retry_cb,
439+
write_options=WriteOptions(
440+
batch_size=1,
441+
),
442+
443+
)
444+
)
445+
446+
lp = "test_write_timeout,location=harfa fVal=3.14,iVal=42i"
447+
# with self.assertRaises(Url3TimeoutError):
448+
localClient.write(lp, _request_timeout=1)
449+
450+
# wait for batcher attempt last write retry
451+
time.sleep(0.1)
452+
453+
print(f"DEBUG ErrorResult {ErrorResult}, retry_ct {retry_ct}")

tests/test_write_local_server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def assert_request_made(httpserver, matcher):
2323
httpserver.check_assertions()
2424

2525
@staticmethod
26-
def delay_response(httpserver, delay=1.0):
26+
def delay_response(httpserver: HTTPServer, delay=1.0):
2727
httpserver.expect_request(re.compile(".*")).respond_with_handler(lambda request: time.sleep(delay))
2828

2929
def test_write_default_params(self, httpserver: HTTPServer):
@@ -169,7 +169,7 @@ def test_write_with_write_timeout(self, httpserver: HTTPServer):
169169
).write(self.SAMPLE_RECORD)
170170

171171
def test_write_with_timeout_arg(self, httpserver: HTTPServer):
172-
self.set_response_status(httpserver, 200)
172+
self.delay_response(httpserver, 0.5)
173173

174174
with pytest.raises(urllib3_TimeoutError):
175175
InfluxDBClient3(

0 commit comments

Comments
 (0)