-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_ops.py
More file actions
1263 lines (1097 loc) · 39.7 KB
/
Copy path_ops.py
File metadata and controls
1263 lines (1097 loc) · 39.7 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 base64
import uuid
from collections.abc import AsyncIterator
from datetime import datetime
from typing import Any, AsyncIterable, Self
from urllib.parse import quote
import s2_sdk._generated.s2.v1.s2_pb2 as pb
from s2_sdk import _types as types
from s2_sdk._append_session import AppendSession
from s2_sdk._client import ConnectionPool, HttpClient
from s2_sdk._exceptions import S2ServerError, fallible
from s2_sdk._mappers import (
access_token_info_from_json,
access_token_info_to_json,
append_ack_from_proto,
append_input_to_proto,
basin_config_from_json,
basin_config_to_json,
basin_info_from_json,
basin_reconfiguration_to_json,
ensured_basin_info_from_json_and_headers,
ensured_stream_info_from_json_and_headers,
location_info_from_json,
metric_set_from_json,
read_batch_from_proto,
read_limit_params,
read_start_params,
stream_config_from_json,
stream_config_to_json,
stream_info_from_json,
stream_reconfiguration_to_json,
tail_from_json,
)
from s2_sdk._producer import Producer
from s2_sdk._retrier import Retrier, http_retry_on, is_safe_to_retry_unary
from s2_sdk._s2s._read_session import run_read_session
from s2_sdk._types import (
_S2_ENCRYPTION_KEY_HEADER,
ONE_MIB,
Compression,
Endpoints,
Retry,
Timeout,
metered_bytes,
)
from s2_sdk._validators import (
validate_append_input,
validate_basin,
validate_batching,
validate_encryption_key,
validate_location,
validate_max_unacked,
validate_retry,
)
class S2:
"""Client for S2, an API for unlimited, durable, real-time streams.
Works with both the `cloud <https://s2.dev/docs/intro>`_ and
`open source, self-hosted <https://s2.dev/docs/s2-lite>`_ versions.
Args:
access_token: Access token for authenticating with S2.
endpoints: S2 endpoints. If ``None``, defaults to public cloud
endpoints. See :class:`Endpoints`.
timeout: Timeout configuration. If ``None``, default values are
used. See :class:`Timeout`.
retry: Retry configuration. If ``None``, default values are
used. See :class:`Retry`.
compression: Compression algorithm for requests and responses.
Defaults to ``NONE``. See :class:`Compression`.
Tip:
Use as an async context manager to ensure connections are closed::
async with S2(token) as s2:
...
Warning:
If not using a context manager, call :meth:`close` when done.
"""
__slots__ = (
"_account_client",
"_auth_header",
"_basin_clients",
"_compression",
"_endpoints",
"_pool",
"_request_timeout",
"_retry",
"_retrier",
)
@fallible
def __init__(
self,
access_token: str,
*,
endpoints: Endpoints | None = None,
timeout: Timeout | None = None,
retry: Retry | None = None,
compression: Compression = Compression.NONE,
) -> None:
if endpoints is None:
endpoints = Endpoints.default()
if timeout is None:
timeout = Timeout()
if retry is None:
retry = Retry()
validate_retry(retry.max_attempts)
self._endpoints = endpoints
self._retry = retry
self._compression = compression
self._auth_header = ("authorization", f"Bearer {access_token}")
self._pool = ConnectionPool(
connect_timeout=timeout.connection.total_seconds(),
)
self._request_timeout = timeout.request.total_seconds()
self._account_client = HttpClient(
pool=self._pool,
base_url=endpoints._account_url(),
request_timeout=self._request_timeout,
headers={self._auth_header[0]: self._auth_header[1]},
compression=compression,
)
self._basin_clients: dict[str, HttpClient] = {}
self._retrier = Retrier(
should_retry_on=http_retry_on,
max_retries=retry._max_retries(),
min_base_delay=retry.min_base_delay.total_seconds(),
max_base_delay=retry.max_base_delay.total_seconds(),
)
async def __aenter__(self) -> Self:
return self
async def __aexit__(self, exc_type, exc_value, traceback) -> bool:
await self.close()
return False
def __getitem__(self, name: str) -> "S2Basin":
return self.basin(name)
async def close(self) -> None:
"""Close all open connections to S2 service endpoints."""
await self._pool.close()
def _get_basin_client(self, name: str) -> HttpClient:
if name not in self._basin_clients:
headers = {self._auth_header[0]: self._auth_header[1]}
if self._endpoints._is_direct_basin():
headers["s2-basin"] = name
self._basin_clients[name] = HttpClient(
pool=self._pool,
base_url=self._endpoints._basin_url(name),
request_timeout=self._request_timeout,
headers=headers,
compression=self._compression,
)
return self._basin_clients[name]
@fallible
async def create_basin(
self,
name: str,
*,
config: types.BasinConfig | None = None,
location: str | None = None,
) -> types.BasinInfo:
"""Create a basin.
Args:
name: Name of the basin.
config: Configuration for the basin.
location: Logical location for the basin. If ``None``, the service
uses the account's default location. The location is fixed for
the lifetime of the basin. Use :meth:`list_locations` or
:meth:`get_default_location` to discover valid values.
Returns:
Information about the created basin.
Note:
``name`` must be globally unique, 8--48 characters, comprising lowercase
letters, numbers, and hyphens. It cannot begin or end with a hyphen.
"""
validate_basin(name)
if location is not None:
validate_location(location)
json: dict[str, Any] = {"basin": name}
if config is not None:
json["config"] = basin_config_to_json(config)
if location is not None:
json["location"] = location
response = await self._retrier(
self._account_client.unary_request,
"POST",
"/v1/basins",
json=json,
headers={"s2-request-token": _s2_request_token()},
)
return basin_info_from_json(response.json())
@fallible
async def ensure_basin(
self,
name: str,
*,
config: types.BasinConfig | None = None,
location: str | None = None,
) -> types.EnsuredBasinInfo:
"""Ensure a basin.
If the basin doesn’t exist, creates the basin with specified configuration.
If the basin already exists:
- Its configuration is updated to the specified configuration, if different.
- Its configuration is unchanged, if the specified configuration is same.
Args:
name: Name of the basin.
config: Configuration for the basin.
location: Logical location for the basin. If ``None`` when
creating, the service uses the account's default location. The
location is fixed for the lifetime of the basin.
Returns:
Information about the ensured basin.
Note:
``name`` must be globally unique, 8--48 characters, comprising lowercase
letters, numbers, and hyphens. It cannot begin or end with a hyphen.
"""
validate_basin(name)
json: dict[str, Any] | None = None
if location is not None:
validate_location(location)
if config is not None or location is not None:
json = {}
if config is not None:
json["config"] = basin_config_to_json(config)
if location is not None:
json["location"] = location
response = await self._retrier(
self._account_client.unary_request, "PUT", f"/v1/basins/{name}", json=json
)
return ensured_basin_info_from_json_and_headers(
response.json(), response.headers
)
@fallible
def basin(self, name: str) -> "S2Basin":
"""Get an :class:`S2Basin` for performing basin-level operations.
Args:
name: Name of the basin.
Returns:
An :class:`S2Basin` bound to the given basin name.
Tip:
Also available via subscript: ``s2["my-basin"]``.
"""
validate_basin(name)
return S2Basin(
name,
self._get_basin_client(name),
retry=self._retry,
compression=self._compression,
)
@fallible
async def list_basins(
self,
*,
prefix: str = "",
start_after: str = "",
limit: int = 1000,
) -> types.Page[types.BasinInfo]:
"""List a page of basins.
Args:
prefix: Filter to basins whose name starts with this prefix.
start_after: List basins whose name is lexicographically after this value.
limit: Maximum number of basins to return per page. Capped at 1000.
Returns:
A page of :class:`BasinInfo`.
Tip:
See :meth:`list_all_basins` for automatic pagination.
"""
params: dict[str, Any] = {}
if prefix:
params["prefix"] = prefix
if start_after:
params["start_after"] = start_after
if limit != 1000:
params["limit"] = limit
response = await self._retrier(
self._account_client.unary_request, "GET", "/v1/basins", params=params
)
data = response.json()
return types.Page(
items=[basin_info_from_json(b) for b in data["basins"]],
has_more=data["has_more"],
)
@fallible
async def list_all_basins(
self,
*,
prefix: str = "",
start_after: str = "",
include_deleted: bool = False,
) -> AsyncIterator[types.BasinInfo]:
"""List all basins, paginating automatically.
Args:
prefix: Filter to basins whose name starts with this prefix.
start_after: List basins whose name is lexicographically after this value.
include_deleted: Include basins that are being deleted.
Yields:
:class:`BasinInfo` for each basin.
"""
while True:
page = await self.list_basins(prefix=prefix, start_after=start_after)
for info in page.items:
if not include_deleted and info.deleted_at is not None:
continue
yield info
if not page.has_more or not page.items:
break
start_after = page.items[-1].name
@fallible
async def list_locations(self) -> list[types.LocationInfo]:
"""List locations available to the account.
Returns:
Locations available to the account.
"""
response = await self._retrier(
self._account_client.unary_request, "GET", "/v1/locations"
)
return [location_info_from_json(loc) for loc in response.json()]
@fallible
async def get_default_location(self) -> types.LocationInfo:
"""Get the account's default location.
Returns:
The account's default location.
"""
response = await self._retrier(
self._account_client.unary_request, "GET", "/v1/locations/default"
)
return location_info_from_json(response.json())
@fallible
async def set_default_location(self, location: str) -> types.LocationInfo:
"""Set the account's default location.
Args:
location: Location name.
Returns:
The account's updated default location.
"""
validate_location(location)
response = await self._retrier(
self._account_client.unary_request,
"PUT",
"/v1/locations/default",
json=location,
)
return location_info_from_json(response.json())
@fallible
async def delete_basin(self, name: str, *, ignore_not_found: bool = False) -> None:
"""Delete a basin.
Args:
name: Name of the basin to delete.
ignore_not_found: If ``True``, do not raise on 404.
Note:
Basin deletion is asynchronous and may take several minutes to complete.
"""
await _maybe_not_found(
self._retrier(
self._account_client.unary_request, "DELETE", f"/v1/basins/{name}"
),
ignore=ignore_not_found,
)
@fallible
async def get_basin_config(self, name: str) -> types.BasinConfig:
"""Get basin configuration.
Args:
name: Name of the basin.
Returns:
Current configuration of the basin.
"""
response = await self._retrier(
self._account_client.unary_request, "GET", f"/v1/basins/{name}"
)
return basin_config_from_json(response.json())
@fallible
async def reconfigure_basin(
self,
name: str,
*,
config: types.BasinConfig,
) -> types.BasinConfig:
"""Reconfigure a basin.
Args:
name: Name of the basin.
config: New configuration. Only provided fields are updated.
Returns:
Updated basin configuration.
Note:
Modifying ``default_stream_config`` only affects newly created streams.
"""
json = basin_reconfiguration_to_json(config)
response = await self._retrier(
self._account_client.unary_request,
"PATCH",
f"/v1/basins/{name}",
json=json,
)
return basin_config_from_json(response.json())
@fallible
async def issue_access_token(
self,
id: str,
*,
scope: types.AccessTokenScope,
expires_at: datetime | None = None,
auto_prefix_streams: bool = False,
) -> str:
"""Issue an access token.
Args:
id: Unique identifier for the token (1--96 bytes).
scope: Permissions scope for the token.
expires_at: Optional expiration time.
auto_prefix_streams: Automatically prefix stream names during
creation and strip the prefix during listing.
Returns:
The access token string.
"""
json = access_token_info_to_json(id, scope, auto_prefix_streams, expires_at)
response = await self._retrier(
self._account_client.unary_request,
"POST",
"/v1/access-tokens",
json=json,
)
return response.json()["access_token"]
@fallible
async def list_access_tokens(
self,
*,
prefix: str = "",
start_after: str = "",
limit: int = 1000,
) -> types.Page[types.AccessTokenInfo]:
"""List a page of access tokens.
Args:
prefix: Filter to tokens whose ID starts with this prefix.
start_after: List tokens whose ID is lexicographically after this value.
limit: Maximum number of tokens to return per page. Capped at 1000.
Returns:
A page of :class:`AccessTokenInfo`.
Tip:
See :meth:`list_all_access_tokens` for automatic pagination.
"""
params: dict[str, Any] = {}
if prefix:
params["prefix"] = prefix
if start_after:
params["start_after"] = start_after
if limit != 1000:
params["limit"] = limit
response = await self._retrier(
self._account_client.unary_request,
"GET",
"/v1/access-tokens",
params=params,
)
data = response.json()
return types.Page(
items=[access_token_info_from_json(info) for info in data["access_tokens"]],
has_more=data["has_more"],
)
@fallible
async def list_all_access_tokens(
self,
*,
prefix: str = "",
start_after: str = "",
) -> AsyncIterator[types.AccessTokenInfo]:
"""List all access tokens, paginating automatically.
Args:
prefix: Filter to tokens whose ID starts with this prefix.
start_after: List tokens whose ID is lexicographically after this value.
Yields:
:class:`AccessTokenInfo` for each token.
"""
while True:
page = await self.list_access_tokens(prefix=prefix, start_after=start_after)
for info in page.items:
yield info
if not page.has_more or not page.items:
break
start_after = page.items[-1].id
@fallible
async def revoke_access_token(self, id: str) -> None:
"""Revoke an access token.
Args:
id: Identifier of the token to revoke.
"""
await self._retrier(
self._account_client.unary_request, "DELETE", _access_token_path(id)
)
@fallible
async def account_metrics(
self,
*,
set: types.AccountMetricSet,
start: int | None = None,
end: int | None = None,
interval: types.TimeseriesInterval | None = None,
) -> list[types.Scalar | types.Accumulation | types.Gauge | types.Label]:
"""Get account metrics.
Args:
set: Metric set to query.
start: Start of the time range (epoch seconds).
end: End of the time range (epoch seconds).
interval: Accumulation interval for timeseries metrics.
Returns:
List of metric values.
"""
response = await self._retrier(
self._account_client.unary_request,
"GET",
"/v1/metrics",
params=_metrics_params(set.value, start, end, interval),
)
return metric_set_from_json(response.json())
@fallible
async def basin_metrics(
self,
basin: str,
*,
set: types.BasinMetricSet,
start: int | None = None,
end: int | None = None,
interval: types.TimeseriesInterval | None = None,
) -> list[types.Scalar | types.Accumulation | types.Gauge | types.Label]:
"""Get basin metrics.
Args:
basin: Name of the basin.
set: Metric set to query.
start: Start of the time range (epoch seconds).
end: End of the time range (epoch seconds).
interval: Accumulation interval for timeseries metrics.
Returns:
List of metric values.
"""
response = await self._retrier(
self._account_client.unary_request,
"GET",
f"/v1/metrics/{_encode_path_segment(basin)}",
params=_metrics_params(set.value, start, end, interval),
)
return metric_set_from_json(response.json())
@fallible
async def stream_metrics(
self,
basin: str,
stream: str,
*,
set: types.StreamMetricSet,
start: int | None = None,
end: int | None = None,
interval: types.TimeseriesInterval | None = None,
) -> list[types.Scalar | types.Accumulation | types.Gauge | types.Label]:
"""Get stream metrics.
Args:
basin: Name of the basin.
stream: Name of the stream.
set: Metric set to query.
start: Start of the time range (epoch seconds).
end: End of the time range (epoch seconds).
interval: Accumulation interval for timeseries metrics.
Returns:
List of metric values.
"""
response = await self._retrier(
self._account_client.unary_request,
"GET",
(
f"/v1/metrics/{_encode_path_segment(basin)}"
f"/{_encode_path_segment(stream)}"
),
params=_metrics_params(set.value, start, end, interval),
)
return metric_set_from_json(response.json())
class S2Basin:
"""
Caution:
Returned by :meth:`S2.basin`. Do not instantiate directly.
"""
__slots__ = (
"_name",
"_client",
"_compression",
"_retry",
"_retrier",
)
@fallible
def __init__(
self,
name: str,
client: HttpClient,
*,
retry: Retry,
compression: Compression,
) -> None:
self._name = name
self._client = client
self._retry = retry
self._compression = compression
self._retrier = Retrier(
should_retry_on=http_retry_on,
max_retries=retry._max_retries(),
min_base_delay=retry.min_base_delay.total_seconds(),
max_base_delay=retry.max_base_delay.total_seconds(),
)
def __repr__(self) -> str:
return f"S2Basin(name={self.name})"
def __getitem__(self, name: str) -> "S2Stream":
return self.stream(name)
@property
def name(self) -> str:
"""Basin name."""
return self._name
@fallible
async def create_stream(
self,
name: str,
*,
config: types.StreamConfig | None = None,
) -> types.StreamInfo:
"""Create a stream.
Args:
name: Name of the stream.
config: Configuration for the stream.
Returns:
Information about the created stream.
Note:
``name`` must be unique within the basin. It can be an arbitrary string
up to 512 characters. ``/`` is recommended as a delimiter for
hierarchical naming.
"""
json: dict[str, Any] = {"stream": name}
if config is not None:
json["config"] = stream_config_to_json(config)
response = await self._retrier(
self._client.unary_request,
"POST",
"/v1/streams",
json=json,
headers={"s2-request-token": _s2_request_token()},
)
return stream_info_from_json(response.json())
@fallible
async def ensure_stream(
self,
name: str,
*,
config: types.StreamConfig | None = None,
) -> types.EnsuredStreamInfo:
"""Ensure a stream.
If the stream doesn’t exist, creates the stream with specified configuration.
If the stream already exists:
- Its configuration is updated to the specified configuration, if different.
- Its configuration is unchanged, if the specified configuration is same.
Args:
name: Name of the stream.
config: Configuration for the stream.
Returns:
Information about the ensured stream.
Note:
``name`` must be unique within the basin. It can be an arbitrary string
up to 512 characters. ``/`` is recommended as a delimiter for
hierarchical naming.
"""
json = stream_config_to_json(config)
response = await self._retrier(
self._client.unary_request, "PUT", _stream_path(name), json=json
)
return ensured_stream_info_from_json_and_headers(
response.json(), response.headers
)
@fallible
def stream(
self,
name: str,
*,
encryption_key: bytes | str | None = None,
) -> "S2Stream":
"""Get an :class:`S2Stream` for performing stream-level operations.
Args:
name: Name of the stream.
encryption_key: Key for encrypting records on append and decrypting
them on read. Required when encryption is enabled via
:attr:`BasinConfig.stream_cipher` (see :class:`Encryption`
for supported algorithms).
If ``bytes``, it will get converted to a base64 encoded str.
If ``str``, it must be base64 encoded.
Returns:
An :class:`S2Stream` bound to the given stream name.
Tip:
Also available via subscript: ``s2["my-basin"]["my-stream"]``.
"""
if isinstance(encryption_key, str):
validate_encryption_key(encryption_key)
elif isinstance(encryption_key, bytes):
encryption_key = base64.b64encode(encryption_key).decode()
return S2Stream(
name,
self._client,
retry=self._retry,
compression=self._compression,
encryption_key=encryption_key,
)
@fallible
async def list_streams(
self,
*,
prefix: str = "",
start_after: str = "",
limit: int = 1000,
) -> types.Page[types.StreamInfo]:
"""List a page of streams.
Args:
prefix: Filter to streams whose name starts with this prefix.
start_after: List streams whose name is lexicographically after this value.
limit: Maximum number of streams to return per page. Capped at 1000.
Returns:
A page of :class:`StreamInfo`.
Tip:
See :meth:`list_all_streams` for automatic pagination.
"""
params: dict[str, Any] = {}
if prefix:
params["prefix"] = prefix
if start_after:
params["start_after"] = start_after
if limit != 1000:
params["limit"] = limit
response = await self._retrier(
self._client.unary_request, "GET", "/v1/streams", params=params
)
data = response.json()
return types.Page(
items=[stream_info_from_json(s) for s in data["streams"]],
has_more=data["has_more"],
)
@fallible
async def list_all_streams(
self,
*,
prefix: str = "",
start_after: str = "",
include_deleted: bool = False,
) -> AsyncIterator[types.StreamInfo]:
"""List all streams, paginating automatically.
Args:
prefix: Filter to streams whose name starts with this prefix.
start_after: List streams whose name is lexicographically after this value.
include_deleted: Include streams that are being deleted.
Yields:
:class:`StreamInfo` for each stream.
"""
while True:
page = await self.list_streams(prefix=prefix, start_after=start_after)
for info in page.items:
if not include_deleted and info.deleted_at is not None:
continue
yield info
if not page.has_more or not page.items:
break
start_after = page.items[-1].name
@fallible
async def delete_stream(self, name: str, *, ignore_not_found: bool = False) -> None:
"""Delete a stream.
Args:
name: Name of the stream to delete.
ignore_not_found: If ``True``, do not raise on 404.
Note:
Stream deletion is asynchronous and may take several minutes to complete.
"""
await _maybe_not_found(
self._retrier(self._client.unary_request, "DELETE", _stream_path(name)),
ignore=ignore_not_found,
)
@fallible
async def get_stream_config(self, name: str) -> types.StreamConfig:
"""Get stream configuration.
Args:
name: Name of the stream.
Returns:
Current configuration of the stream.
"""
response = await self._retrier(
self._client.unary_request, "GET", _stream_path(name)
)
return stream_config_from_json(response.json())
@fallible
async def reconfigure_stream(
self,
name: str,
*,
config: types.StreamConfig,
) -> types.StreamConfig:
"""Reconfigure a stream.
Args:
name: Name of the stream.
config: New configuration. Only provided fields are updated.
Returns:
Updated stream configuration.
"""
json = stream_reconfiguration_to_json(config)
response = await self._retrier(
self._client.unary_request, "PATCH", _stream_path(name), json=json
)
return stream_config_from_json(response.json())
class S2Stream:
"""
Caution:
Returned by :meth:`S2Basin.stream`. Do not instantiate directly.
"""
__slots__ = (
"_name",
"_client",
"_compression",
"_encryption_key",
"_retry",
"_retrier",
"_append_retrier",
)
def __init__(
self,
name: str,
client: HttpClient,
*,
retry: Retry,
compression: Compression,
encryption_key: str | None = None,
) -> None:
self._name = name
self._client = client
self._retry = retry
self._compression = compression
self._encryption_key = encryption_key
self._retrier = Retrier(
should_retry_on=http_retry_on,
max_retries=retry._max_retries(),
min_base_delay=retry.min_base_delay.total_seconds(),
max_base_delay=retry.max_base_delay.total_seconds(),
)
self._append_retrier = Retrier(
should_retry_on=lambda e: is_safe_to_retry_unary(
e, retry.append_retry_policy
),
max_retries=retry._max_retries(),
min_base_delay=retry.min_base_delay.total_seconds(),
max_base_delay=retry.max_base_delay.total_seconds(),
)
def __repr__(self) -> str:
return f"S2Stream(name={self.name})"
@property
def name(self) -> str:
"""Stream name."""
return self._name
def _request_headers(
self, headers: dict[str, str] | None = None
) -> dict[str, str] | None:
if self._encryption_key is None:
return headers
merged = dict(headers or {})
merged[_S2_ENCRYPTION_KEY_HEADER] = self._encryption_key
return merged
@fallible
async def check_tail(self) -> types.StreamPosition:
"""Check the tail of a stream.
Returns:
The tail position — the next sequence number to be assigned and the
timestamp of the last record on the stream.
"""
response = await self._retrier(
self._client.unary_request,
"GET",
_stream_path(self.name, "/records/tail"),
)
return tail_from_json(response.json())
@fallible
async def append(self, inp: types.AppendInput) -> types.AppendAck:
"""Append a batch of records to a stream.
Args: