-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathfeldera_client.py
More file actions
1435 lines (1163 loc) · 49.5 KB
/
feldera_client.py
File metadata and controls
1435 lines (1163 loc) · 49.5 KB
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import pathlib
import time
from decimal import Decimal
from typing import Any, Dict, Generator, Mapping, Optional
from urllib.parse import quote
import requests
from feldera.enums import BootstrapPolicy, PipelineFieldSelector, PipelineStatus
from feldera.rest._helpers import determine_client_version
from feldera.rest._httprequests import HttpRequests
from feldera.rest.config import Config
from feldera.rest.errors import FelderaAPIError, FelderaTimeoutError
from feldera.rest.feldera_config import FelderaConfig
from feldera.rest.pipeline import Pipeline
logger = logging.getLogger(__name__)
def _validate_no_none_keys_in_map(data):
def validate_no_none_keys(d: Dict[Any, Any]) -> None:
for k, v in d.items():
if isinstance(v, dict) and any(k is None for k in v.keys()):
raise ValueError("keys of SQL MAP objects cannot be NULL")
if isinstance(data, list):
for datum in data:
validate_no_none_keys(datum)
elif isinstance(data, dict):
validate_no_none_keys(data)
else:
return
def _prepare_boolean_input(value: bool) -> str:
return "true" if value else "false"
class FelderaClient:
"""
A client for the Feldera HTTP API.
The client is initialized with the configuration needed for interacting with the
Feldera HTTP API, which it uses in its calls. Its methods are implemented
by issuing one or more HTTP requests to the API, and as such can provide higher
level operations (e.g., support waiting for the success of asynchronous HTTP API
functionality).
"""
def __init__(
self,
url: Optional[str] = None,
api_key: Optional[str] = None,
timeout: Optional[float] = None,
connection_timeout: Optional[float] = None,
requests_verify: Optional[bool | str] = None,
) -> None:
"""
Constructs a Feldera client.
:param url: (Optional) URL to the Feldera API.
The default is read from the `FELDERA_HOST` environment variable;
if the variable is not set, the default is `"http://localhost:8080"`.
:param api_key: (Optional) API key to access Feldera (format: `"apikey:..."`).
The default is read from the `FELDERA_API_KEY` environment variable;
if the variable is not set, the default is `None` (no API key is provided).
:param timeout: (Optional) Duration in seconds that the client will wait to receive
a response of an HTTP request, after which it times out.
The default is `None` (wait indefinitely; no timeout is enforced).
:param connection_timeout: (Optional) Duration in seconds that the client will wait
to establish the connection of an HTTP request, after which it times out.
The default is `None` (wait indefinitely; no timeout is enforced).
:param requests_verify: (Optional) The `verify` parameter passed to the `requests` library,
which is used internally to perform HTTP requests.
See also: https://requests.readthedocs.io/en/latest/user/advanced/#ssl-cert-verification .
The default is based on the `FELDERA_HTTPS_TLS_CERT` or the `FELDERA_TLS_INSECURE` environment variable.
By setting `FELDERA_HTTPS_TLS_CERT` to a path, the default becomes the CA bundle it points to.
By setting `FELDERA_TLS_INSECURE` to `"1"`, `"true"` or `"yes"` (all case-insensitive), the default becomes
`False` which means to disable TLS verification by default. If both variables are set, the former takes
priority over the latter. If neither variable is set, the default is `True`.
"""
self.config = Config(
url=url,
api_key=api_key,
timeout=timeout,
connection_timeout=connection_timeout,
requests_verify=requests_verify,
)
self.http = HttpRequests(self.config)
try:
client_version = determine_client_version()
server_config = self.get_config()
if client_version != server_config.version:
logger.warning(
f"Feldera client is on version {client_version} while server is at "
f"{server_config.version}. There could be incompatibilities."
)
except Exception as e:
logger.error(f"Failed to connect to Feldera API: {e}")
raise e
@staticmethod
def localhost(port: int = 8080) -> "FelderaClient":
"""
Create a FelderaClient that connects to the local Feldera instance
"""
return FelderaClient(f"http://127.0.0.1:{port}")
def get_pipeline(
self, pipeline_name: str, field_selector: PipelineFieldSelector
) -> Pipeline:
"""
Get a pipeline by name
:param pipeline_name: The name of the pipeline
:param field_selector: Choose what pipeline information to refresh; see PipelineFieldSelector enum definition.
"""
resp = self.http.get(
f"/pipelines/{pipeline_name}?selector={field_selector.value}"
)
return Pipeline.from_dict(resp)
def get_runtime_config(self, pipeline_name) -> Mapping[str, Any]:
"""
Get the runtime config of a pipeline by name
:param pipeline_name: The name of the pipeline
"""
resp: Mapping[str, Any] = self.http.get(f"/pipelines/{pipeline_name}")
runtime_config: Mapping[str, Any] | None = resp.get("runtime_config")
if runtime_config is None:
raise ValueError(f"Pipeline {pipeline_name} has no runtime config")
return runtime_config
def pipelines(
self, selector: PipelineFieldSelector = PipelineFieldSelector.STATUS
) -> list[Pipeline]:
"""
Get all pipelines
"""
resp = self.http.get(
path=f"/pipelines?selector={selector.value}",
)
return [Pipeline.from_dict(pipeline) for pipeline in resp]
def _wait_for_compilation(
self,
name: str,
expected_program_version: int | None = None,
timeout_s: float | None = None,
poll_interval_s: float = 1.0,
) -> Pipeline:
"""Wait for pipeline compilation -- internal use only."""
wait = ["Pending", "CompilingSql", "SqlCompiled", "CompilingRust"]
start_time = time.monotonic()
while True:
elapsed = time.monotonic() - start_time
if timeout_s is not None and elapsed > timeout_s:
raise TimeoutError(
f"Timed out waiting for pipeline '{name}' to compile "
f"(expected program_version >= {expected_program_version})"
)
p = self.get_pipeline(name, PipelineFieldSelector.STATUS)
status = p.program_status
if status == "Success":
if expected_program_version is None:
return self.get_pipeline(name, PipelineFieldSelector.ALL)
current_version = p.program_version or 0
if current_version == expected_program_version:
return self.get_pipeline(name, PipelineFieldSelector.ALL)
else:
raise RuntimeError(
f"program version ({current_version}) != expected program version ({expected_program_version})"
)
elif status not in wait:
p = self.get_pipeline(name, PipelineFieldSelector.ALL)
# error handling for SQL compilation errors
if status == "SqlError":
sql_errors = p.program_error["sql_compilation"]["messages"]
if sql_errors:
err_msg = f"Pipeline {name} failed to compile:\n"
for sql_error in sql_errors:
err_msg += (
f"{sql_error['error_type']}\n{sql_error['message']}\n"
)
err_msg += f"Code snippet:\n{sql_error['snippet']}"
raise RuntimeError(err_msg)
error_message = f"The program failed to compile: {status}\n"
rust_error = p.program_error.get("rust_compilation")
if rust_error is not None:
error_message += f"Rust Error: {rust_error}\n"
system_error = p.program_error.get("system_error")
if system_error is not None:
error_message += f"System Error: {system_error}"
raise RuntimeError(error_message)
logger.debug(
"still compiling %s, waiting for %.1f more seconds",
name,
poll_interval_s,
)
time.sleep(poll_interval_s)
def __wait_for_pipeline_state(
self,
pipeline_name: str,
state: str,
timeout_s: Optional[float] = None,
start: bool = True,
poll_interval_s: float = 0.5,
):
start_time = time.monotonic()
while True:
if timeout_s is not None:
elapsed = time.monotonic() - start_time
if elapsed > timeout_s:
raise TimeoutError(
f"Timed out waiting for pipeline {pipeline_name} to "
f"transition to '{state}' state"
)
resp = self.get_pipeline(pipeline_name, PipelineFieldSelector.STATUS)
status = resp.deployment_status
if status.lower() == state.lower():
break
elif (
status == "Stopped"
and len(resp.deployment_error or {}) > 0
and resp.deployment_desired_status == "Stopped"
):
err_msg = "Unable to START the pipeline:\n" if start else ""
raise RuntimeError(
f"""{err_msg}Unable to transition the pipeline to '{state}'.
Reason: The pipeline is in a STOPPED state due to the following error:
{resp.deployment_error.get("message", "")}"""
)
logger.debug(
"still starting %s, waiting for %.1f more seconds",
pipeline_name,
poll_interval_s,
)
time.sleep(poll_interval_s)
def __wait_for_pipeline_state_one_of(
self,
pipeline_name: str,
states: list[str],
timeout_s: float | None = None,
start: bool = True,
poll_interval_s: float = 0.5,
) -> PipelineStatus:
start_time = time.monotonic()
states = [state.lower() for state in states]
while True:
if timeout_s is not None:
elapsed = time.monotonic() - start_time
if elapsed > timeout_s:
raise TimeoutError(
f"Timed out waiting for pipeline {pipeline_name} to"
f"transition to one of the states: {states}"
)
resp = self.get_pipeline(pipeline_name, PipelineFieldSelector.STATUS)
status = resp.deployment_status
if status.lower() in states:
return PipelineStatus.from_str(status)
elif (
status == "Stopped"
and len(resp.deployment_error or {}) > 0
and resp.deployment_desired_status == "Stopped"
):
err_msg = "Unable to START the pipeline:\n" if start else ""
raise RuntimeError(
f"""{err_msg}Unable to transition the pipeline to one of the states: {states}.
Reason: The pipeline is in a STOPPED state due to the following error:
{resp.deployment_error.get("message", "")}"""
)
logger.debug(
"still starting %s, waiting for %.1f more seconds",
pipeline_name,
poll_interval_s,
)
time.sleep(poll_interval_s)
def create_pipeline(self, pipeline: Pipeline, wait: bool = True) -> Pipeline:
"""
Create a pipeline if it doesn't exist and wait for it to compile
:param pipeline: The pipeline to create
:param wait: Whether to wait for the pipeline to compile. True by default
"""
body = {
"name": pipeline.name,
"program_code": pipeline.program_code,
"udf_rust": pipeline.udf_rust,
"udf_toml": pipeline.udf_toml,
"program_config": pipeline.program_config,
"runtime_config": pipeline.runtime_config,
"description": pipeline.description or "",
}
self.http.post(
path="/pipelines",
body=body,
)
if not wait:
return pipeline
return self._wait_for_compilation(pipeline.name)
def create_or_update_pipeline(
self, pipeline: Pipeline, wait: bool = True
) -> Pipeline:
"""
Create a pipeline if it doesn't exist or update a pipeline and wait for
it to compile
:param pipeline: The pipeline to create or update
:param wait: Whether to wait for the pipeline to compile. True by default
:return: The created or updated pipeline
"""
body = {
"name": pipeline.name,
"program_code": pipeline.program_code,
"udf_rust": pipeline.udf_rust,
"udf_toml": pipeline.udf_toml,
"program_config": pipeline.program_config,
"runtime_config": pipeline.runtime_config,
"description": pipeline.description or "",
}
self.http.put(
path=f"/pipelines/{pipeline.name}",
body=body,
)
if not wait:
return pipeline
return self._wait_for_compilation(pipeline.name)
def patch_pipeline(
self,
name: str,
sql: Optional[str] = None,
udf_rust: Optional[str] = None,
udf_toml: Optional[str] = None,
program_config: Optional[Mapping[str, Any]] = None,
runtime_config: Optional[Mapping[str, Any]] = None,
description: Optional[str] = None,
):
"""
Incrementally update pipeline
:param name: The name of the pipeline
"""
self.http.patch(
path=f"/pipelines/{name}",
body={
"program_code": sql,
"udf_rust": udf_rust,
"udf_toml": udf_toml,
"program_config": program_config,
"runtime_config": runtime_config,
"description": description,
},
)
def testing_force_update_platform_version(self, name: str, platform_version: str):
self.http.post(
path=f"/pipelines/{name}/testing",
params={"set_platform_version": platform_version},
)
def update_pipeline_runtime(self, name: str):
"""
Recompile a pipeline with the Feldera runtime version included in the currently installed Feldera platform.
:param name: The name of the pipeline
"""
self.http.post(path=f"/pipelines/{name}/update_runtime")
def delete_pipeline(self, name: str):
"""
Deletes a pipeline by name
:param name: The name of the pipeline
"""
self.http.delete(
path=f"/pipelines/{name}",
)
def get_pipeline_stats(self, name: str) -> dict:
"""
Get the pipeline metrics and performance counters
:param name: The name of the pipeline
"""
resp = self.http.get(
path=f"/pipelines/{name}/stats",
)
return resp
def get_pipeline_logs(self, pipeline_name: str) -> Generator[str, None, None]:
"""
Get the pipeline logs
:param name: The name of the pipeline
:return: A generator yielding the logs, one line at a time.
"""
chunk: bytes
with self.http.get(
path=f"/pipelines/{pipeline_name}/logs",
stream=True,
) as resp:
for chunk in resp.iter_lines(chunk_size=50000000):
if chunk:
yield chunk.decode("utf-8")
def activate_pipeline(
self, pipeline_name: str, wait: bool = True, timeout_s: Optional[float] = None
) -> Optional[PipelineStatus]:
"""
:param pipeline_name: The name of the pipeline to activate
:param wait: Set True to wait for the pipeline to activate. True by
default
:param timeout_s: The amount of time in seconds to wait for the
pipeline to activate.
"""
self.http.post(
path=f"/pipelines/{pipeline_name}/activate",
)
if not wait:
return None
return self.__wait_for_pipeline_state_one_of(
pipeline_name, ["running", "AwaitingApproval"], timeout_s
)
def _inner_start_pipeline(
self,
pipeline_name: str,
initial: str = "running",
bootstrap_policy: Optional[BootstrapPolicy] = None,
wait: bool = True,
timeout_s: Optional[float] = None,
dismiss_error: bool = True,
) -> Optional[PipelineStatus]:
"""
:param pipeline_name: The name of the pipeline to start
:param initial: The initial state to start the pipeline in. "running"
by default.
:param wait: Set True to wait for the pipeline to start. True by default
:param timeout_s: The amount of time in seconds to wait for the
pipeline to start.
:param dismiss_error: Set True to dismiss any deployment error before starting;
set False to make it fail in that case. True by default.
"""
start_params = {}
# Any error is dismissed separately in order to make sure we only dismiss any error
# BEFORE it was started, not after it has been started by this call
if dismiss_error:
self.http.post(path=f"/pipelines/{pipeline_name}/dismiss_error")
start_params["dismiss_error"] = "false"
start_params["initial"] = initial
if bootstrap_policy is not None:
start_params["bootstrap_policy"] = bootstrap_policy.value
self.http.post(
path=f"/pipelines/{pipeline_name}/start",
params=start_params,
)
if not wait:
return None
return self.__wait_for_pipeline_state_one_of(
pipeline_name,
[initial, "AwaitingApproval"],
timeout_s,
)
def start_pipeline(
self,
pipeline_name: str,
bootstrap_policy: Optional[BootstrapPolicy] = None,
wait: bool = True,
timeout_s: Optional[float] = None,
dismiss_error: bool = True,
) -> Optional[PipelineStatus]:
"""
:param pipeline_name: The name of the pipeline to start
:param wait: Set True to wait for the pipeline to start.
True by default
:param timeout_s: The amount of time in seconds to wait for the
pipeline to start.
:param dismiss_error: Set True to dismiss any deployment error before starting;
set False to make it fail in that case. True by default.
"""
return self._inner_start_pipeline(
pipeline_name,
"running",
bootstrap_policy,
wait,
timeout_s,
dismiss_error,
)
def start_pipeline_as_paused(
self,
pipeline_name: str,
bootstrap_policy: Optional[BootstrapPolicy] = None,
wait: bool = True,
timeout_s: float | None = None,
dismiss_error: bool = True,
) -> Optional[PipelineStatus]:
"""
:param pipeline_name: The name of the pipeline to start as paused.
:param wait: Set True to wait for the pipeline to start as pause.
True by default
:param timeout_s: The amount of time in seconds to wait for the
pipeline to start.
:param dismiss_error: Set True to dismiss any deployment error before starting;
set False to make it fail in that case. True by default.
"""
return self._inner_start_pipeline(
pipeline_name,
"paused",
bootstrap_policy,
wait,
timeout_s,
dismiss_error,
)
def start_pipeline_as_standby(
self,
pipeline_name: str,
bootstrap_policy: Optional[BootstrapPolicy] = None,
wait: bool = True,
timeout_s: Optional[float] = None,
dismiss_error: bool = True,
):
"""
:param pipeline_name: The name of the pipeline to start as standby.
:param wait: Set True to wait for the pipeline to start as standby.
True by default
:param timeout_s: The amount of time in seconds to wait for the
pipeline to start.
:param dismiss_error: Set True to dismiss any deployment error before starting;
set False to make it fail in that case. True by default.
"""
self._inner_start_pipeline(
pipeline_name,
"standby",
bootstrap_policy,
wait,
timeout_s,
dismiss_error,
)
def resume_pipeline(
self,
pipeline_name: str,
wait: bool = True,
timeout_s: Optional[float] = None,
):
"""
Resume a pipeline
:param pipeline_name: The name of the pipeline to stop
:param wait: Set True to wait for the pipeline to pause. True by default
:param timeout_s: The amount of time in seconds to wait for the pipeline
to pause.
"""
self.http.post(
path=f"/pipelines/{pipeline_name}/resume",
)
if not wait:
return
self.__wait_for_pipeline_state(pipeline_name, "running", timeout_s)
def pause_pipeline(
self,
pipeline_name: str,
wait: bool = True,
timeout_s: Optional[float] = None,
):
"""
Pause a pipeline
:param pipeline_name: The name of the pipeline to stop
:param error_message: The error message to show if the pipeline is in
STOPPED state due to a failure.
:param wait: Set True to wait for the pipeline to pause. True by default
:param timeout_s: The amount of time in seconds to wait for the pipeline
to pause.
"""
self.http.post(
path=f"/pipelines/{pipeline_name}/pause",
)
if not wait:
return
self.__wait_for_pipeline_state(pipeline_name, "paused", timeout_s)
def approve_pipeline(
self,
pipeline_name: str,
):
self.http.post(
path=f"/pipelines/{pipeline_name}/approve",
)
def stop_pipeline(
self,
pipeline_name: str,
force: bool,
wait: bool = True,
timeout_s: Optional[float] = None,
):
"""
Stop a pipeline
:param pipeline_name: The name of the pipeline to stop
:param force: Set True to immediately scale compute resources to zero.
Set False to automatically checkpoint before stopping.
:param wait: Set True to wait for the pipeline to stop. True by default
:param timeout_s: The amount of time in seconds to wait for the pipeline
to stop.
"""
params = {"force": str(force).lower()}
self.http.post(
path=f"/pipelines/{pipeline_name}/stop",
params=params,
)
if not wait:
return
start = time.monotonic()
while True:
if timeout_s is not None and time.monotonic() - start > timeout_s:
raise FelderaTimeoutError(
f"timeout error: pipeline '{pipeline_name}' did not stop in {timeout_s} seconds"
)
status = self.get_pipeline(
pipeline_name, PipelineFieldSelector.STATUS
).deployment_status
if status == "Stopped":
return
logger.debug(
"still stopping %s, waiting for 100 more milliseconds",
pipeline_name,
)
time.sleep(0.1)
def dismiss_error_pipeline(
self,
pipeline_name: str,
):
"""
Dismisses the deployment error of a pipeline.
:param pipeline_name: The name of the pipeline for which to dismiss the deployment error
"""
self.http.post(path=f"/pipelines/{pipeline_name}/dismiss_error")
def clear_storage(self, pipeline_name: str, timeout_s: Optional[float] = None):
"""
Clears the storage from the pipeline.
This operation cannot be canceled.
:param pipeline_name: The name of the pipeline
:param timeout_s: The amount of time in seconds to wait for the storage
to clear.
"""
self.http.post(
path=f"/pipelines/{pipeline_name}/clear",
)
start = time.monotonic()
while True:
if timeout_s is not None and time.monotonic() - start > timeout_s:
raise FelderaTimeoutError(
f"timeout error: pipeline '{pipeline_name}' did not clear storage in {timeout_s} seconds"
)
status = self.get_pipeline(
pipeline_name, PipelineFieldSelector.STATUS
).storage_status
if status == "Cleared":
return
logging.debug(
"still clearing %s, waiting for 100 more milliseconds",
pipeline_name,
)
time.sleep(0.1)
def start_transaction(self, pipeline_name: str) -> int:
"""
Start a new transaction.
Transaction ID.
:param pipeline_name: The name of the pipeline.
"""
resp = self.http.post(
path=f"/pipelines/{pipeline_name}/start_transaction",
)
return int(resp.get("transaction_id"))
def commit_transaction(
self,
pipeline_name: str,
transaction_id: Optional[int] = None,
wait: bool = True,
timeout_s: Optional[float] = None,
):
"""
Commits the currently active transaction.
:param pipeline_name: The name of the pipeline.
:param transaction_id: If provided, the function verifies that the currently active transaction matches this ID.
If the active transaction ID does not match, the function raises an error.
:param wait: If True, the function blocks until the transaction either commits successfully or the timeout is reached.
If False, the function initiates the commit and returns immediately without waiting for completion. The default value is True.
:param timeout_s: Maximum time (in seconds) to wait for the transaction to commit when `wait` is True.
If None, the function will wait indefinitely.
:raises RuntimeError: If there is currently no transaction in progress.
:raises ValueError: If the provided `transaction_id` does not match the current transaction.
:raises TimeoutError: If the transaction does not commit within the specified timeout (when `wait` is True).
:raises FelderaAPIError: If the pipeline fails to commit a transaction.
"""
# TODO: implement this without using /stats when we have a better pipeline status reporting API.
stats = self.get_pipeline_stats(pipeline_name)
current_transaction_id = stats["global_metrics"]["transaction_id"]
if current_transaction_id == 0:
raise RuntimeError(
"Attempting to commit a transaction, but there is no transaction in progress"
)
if transaction_id and current_transaction_id != transaction_id:
raise ValueError(
f"Specified transaction id {transaction_id} doesn't match current active transaction id {current_transaction_id}"
)
transaction_id = current_transaction_id
self.http.post(
path=f"/pipelines/{pipeline_name}/commit_transaction",
)
start_time = time.monotonic()
if not wait:
return
while True:
if timeout_s is not None:
elapsed = time.monotonic() - start_time
if elapsed > timeout_s:
raise TimeoutError("Timed out waiting for transaction to commit")
stats = self.get_pipeline_stats(pipeline_name)
if stats["global_metrics"]["transaction_id"] != transaction_id:
return
logging.debug("commit hasn't completed, waiting for 1 more second")
time.sleep(1.0)
def checkpoint_pipeline(self, pipeline_name: str) -> int:
"""
Checkpoint a pipeline.
:param pipeline_name: The name of the pipeline to checkpoint
"""
resp = self.http.post(
path=f"/pipelines/{pipeline_name}/checkpoint",
)
return int(resp.get("checkpoint_sequence_number"))
def checkpoint_pipeline_status(self, pipeline_name: str) -> dict:
"""
Gets the checkpoint status
:param pipeline_name: The name of the pipeline to check the checkpoint status of.
"""
return self.http.get(path=f"/pipelines/{pipeline_name}/checkpoint_status")
def sync_checkpoint(self, pipeline_name: str) -> str:
"""
Triggers a checkpoint synchronization for the specified pipeline.
Check the status by calling `pipeline_sync_checkpoint_status`.
:param pipeline_name: Name of the pipeline whose checkpoint should be synchronized.
"""
resp = self.http.post(
path=f"/pipelines/{pipeline_name}/checkpoint/sync",
)
return resp.get("checkpoint_uuid")
def sync_checkpoint_status(self, pipeline_name: str) -> dict:
"""
Gets the checkpoint sync status of the pipeline
:param pipeline_name: The name of the pipeline to check the checkpoint synchronization status of.
"""
return self.http.get(
path=f"/pipelines/{pipeline_name}/checkpoint/sync_status",
)
def push_to_pipeline(
self,
pipeline_name: str,
table_name: str,
format: str,
data: list[list | str | dict] | dict | str,
array: bool = False,
force: bool = False,
update_format: str = "raw",
json_flavor: Optional[str] = None,
serialize: bool = True,
wait: bool = True,
wait_timeout_s: Optional[float] = None,
) -> str:
"""
Insert data into a pipeline
:param pipeline_name: The name of the pipeline
:param table_name: The name of the table
:param format: The format of the data, either "json" or "csv"
:param array: True if updates in this stream are packed into JSON arrays, used in conjunction with the
"json" format
:param force: If True, the data will be inserted even if the pipeline is paused
:param update_format: JSON data change event format, used in conjunction with the "json" format,
the default value is "insert_delete", other supported formats: "weighted", "debezium", "snowflake", "raw"
:param json_flavor: JSON encoding used for individual table records, the default value is "default", other supported encodings:
"debezium_mysql", "snowflake", "kafka_connect_json_converter", "pandas"
:param data: The data to insert
:param serialize: If True, the data will be serialized to JSON. True by default
:param wait: If True, blocks until this input has been processed by the pipeline
:param wait_timeout_s: The timeout in seconds to wait for this set of
inputs to be processed by the pipeline. None by default
:returns: The completion token to this input.
"""
if format not in ["json", "csv"]:
raise ValueError("format must be either 'json' or 'csv'")
if update_format not in [
"insert_delete",
"weighted",
"debezium",
"snowflake",
"raw",
]:
raise ValueError(
"update_format must be one of 'insert_delete', 'weighted', 'debezium', 'snowflake', 'raw'"
)
if json_flavor is not None and json_flavor not in [
"default",
"debezium_mysql",
"snowflake",
"kafka_connect_json_converter",
"pandas",
]:
raise ValueError(
"json_flavor must be one of 'default', 'debezium_mysql', 'snowflake', 'kafka_connect_json_converter', 'pandas'"
)
if update_format == "insert_delete":
if array:
for datum in data:
_validate_no_none_keys_in_map(datum.get("insert", {}))
_validate_no_none_keys_in_map(datum.get("delete", {}))
else:
data: Mapping[str, Any] = data
_validate_no_none_keys_in_map(data.get("insert", {}))
_validate_no_none_keys_in_map(data.get("delete", {}))
else:
_validate_no_none_keys_in_map(data)
# python sends `True` which isn't accepted by the backend
array: str = _prepare_boolean_input(array)
force: str = _prepare_boolean_input(force)
params = {
"force": force,
"format": format,
}
if format == "json":
params["array"] = array
params["update_format"] = update_format
if json_flavor is not None:
params["json_flavor"] = json_flavor
content_type = "application/json"
if format == "csv":
content_type = "text/csv"
data = bytes(str(data), "utf-8")
resp = self.http.post(
path=f"/pipelines/{quote(pipeline_name, safe='')}/ingress/{quote(table_name, safe='')}",
params=params,
content_type=content_type,
body=data,
serialize=serialize,
)
token = resp.get("token")
if token is None:
raise FelderaAPIError("response did not contain a completion token", resp)
if not wait:
return token
self.wait_for_token(pipeline_name, token, timeout_s=wait_timeout_s)
return token
def completion_token_processed(self, pipeline_name: str, token: str) -> bool:
"""
Check whether the pipeline has finished processing all inputs received from the connector before
the token was generated.