-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy path_flight.pyx
3188 lines (2568 loc) · 108 KB
/
_flight.pyx
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# cython: language_level = 3
import collections
import enum
import re
import time
import warnings
import weakref
from cython.operator cimport dereference as deref
from cython.operator cimport postincrement
from libcpp cimport bool as c_bool
from pyarrow.lib cimport *
from pyarrow.lib import (ArrowCancelled, ArrowException, ArrowInvalid,
SignalStopHandler)
from pyarrow.lib import as_buffer, frombytes, tobytes
from pyarrow.includes.libarrow_flight cimport *
from pyarrow.ipc import _get_legacy_format_default, _ReadPandasMixin
import pyarrow.lib as lib
cdef CFlightCallOptions DEFAULT_CALL_OPTIONS
cdef int check_flight_status(const CStatus& status) except -1 nogil:
cdef shared_ptr[FlightStatusDetail] detail
if status.ok():
return 0
detail = FlightStatusDetail.UnwrapStatus(status)
if detail:
with gil:
message = frombytes(status.message(), safe=True)
detail_msg = detail.get().extra_info()
if detail.get().code() == CFlightStatusInternal:
raise FlightInternalError(message, detail_msg)
elif detail.get().code() == CFlightStatusFailed:
message = _munge_grpc_python_error(message)
raise FlightServerError(message, detail_msg)
elif detail.get().code() == CFlightStatusTimedOut:
raise FlightTimedOutError(message, detail_msg)
elif detail.get().code() == CFlightStatusCancelled:
raise FlightCancelledError(message, detail_msg)
elif detail.get().code() == CFlightStatusUnauthenticated:
raise FlightUnauthenticatedError(message, detail_msg)
elif detail.get().code() == CFlightStatusUnauthorized:
raise FlightUnauthorizedError(message, detail_msg)
elif detail.get().code() == CFlightStatusUnavailable:
raise FlightUnavailableError(message, detail_msg)
size_detail = FlightWriteSizeStatusDetail.UnwrapStatus(status)
if size_detail:
with gil:
message = frombytes(status.message(), safe=True)
raise FlightWriteSizeExceededError(
message,
size_detail.get().limit(), size_detail.get().actual())
return check_status(status)
_FLIGHT_SERVER_ERROR_REGEX = re.compile(
r'Flight RPC failed with message: (.*). Detail: '
r'Python exception: (.*)',
re.DOTALL
)
def _munge_grpc_python_error(message):
m = _FLIGHT_SERVER_ERROR_REGEX.match(message)
if m:
return ('Flight RPC failed with Python exception \"{}: {}\"'
.format(m.group(2), m.group(1)))
else:
return message
cdef IpcWriteOptions _get_options(options):
return <IpcWriteOptions> _get_legacy_format_default(
use_legacy_format=None, options=options)
cdef class FlightCallOptions(_Weakrefable):
"""RPC-layer options for a Flight call."""
cdef:
CFlightCallOptions options
def __init__(self, timeout=None, write_options=None, headers=None,
IpcReadOptions read_options=None):
"""Create call options.
Parameters
----------
timeout : float, None
A timeout for the call, in seconds. None means that the
timeout defaults to an implementation-specific value.
write_options : pyarrow.ipc.IpcWriteOptions, optional
IPC write options. The default options can be controlled
by environment variables (see pyarrow.ipc).
headers : List[Tuple[str, str]], optional
A list of arbitrary headers as key, value tuples
read_options : pyarrow.ipc.IpcReadOptions, optional
Serialization options for reading IPC format.
"""
cdef IpcWriteOptions c_write_options
if timeout is not None:
self.options.timeout = CTimeoutDuration(timeout)
if write_options is not None:
c_write_options = _get_options(write_options)
self.options.write_options = c_write_options.c_options
if read_options is not None:
if not isinstance(read_options, IpcReadOptions):
raise TypeError("expected IpcReadOptions, got {}"
.format(type(read_options)))
self.options.read_options = read_options.c_options
if headers is not None:
self.options.headers = headers
@staticmethod
cdef CFlightCallOptions* unwrap(obj):
if not obj:
return &DEFAULT_CALL_OPTIONS
elif isinstance(obj, FlightCallOptions):
return &((<FlightCallOptions> obj).options)
raise TypeError("Expected a FlightCallOptions object, not "
"'{}'".format(type(obj)))
_CertKeyPair = collections.namedtuple('_CertKeyPair', ['cert', 'key'])
class CertKeyPair(_CertKeyPair):
"""A TLS certificate and key for use in Flight."""
cdef class FlightError(Exception):
"""
The base class for Flight-specific errors.
A server may raise this class or one of its subclasses to provide
a more detailed error to clients.
Parameters
----------
message : str, optional
The error message.
extra_info : bytes, optional
Extra binary error details that were provided by the
server/will be sent to the client.
Attributes
----------
extra_info : bytes
Extra binary error details that were provided by the
server/will be sent to the client.
"""
cdef dict __dict__
def __init__(self, message='', extra_info=b''):
super().__init__(message)
self.extra_info = tobytes(extra_info)
cdef CStatus to_status(self):
message = tobytes("Flight error: {}".format(str(self)))
return CStatus_UnknownError(message)
cdef class FlightInternalError(FlightError, ArrowException):
"""An error internal to the Flight server occurred."""
cdef CStatus to_status(self):
return MakeFlightError(CFlightStatusInternal,
tobytes(str(self)), self.extra_info)
cdef class FlightTimedOutError(FlightError, ArrowException):
"""The Flight RPC call timed out."""
cdef CStatus to_status(self):
return MakeFlightError(CFlightStatusTimedOut,
tobytes(str(self)), self.extra_info)
cdef class FlightCancelledError(FlightError, ArrowCancelled):
"""The operation was cancelled."""
cdef CStatus to_status(self):
return MakeFlightError(CFlightStatusCancelled, tobytes(str(self)),
self.extra_info)
cdef class FlightServerError(FlightError, ArrowException):
"""A server error occurred."""
cdef CStatus to_status(self):
return MakeFlightError(CFlightStatusFailed, tobytes(str(self)),
self.extra_info)
cdef class FlightUnauthenticatedError(FlightError, ArrowException):
"""The client is not authenticated."""
cdef CStatus to_status(self):
return MakeFlightError(
CFlightStatusUnauthenticated, tobytes(str(self)), self.extra_info)
cdef class FlightUnauthorizedError(FlightError, ArrowException):
"""The client is not authorized to perform the given operation."""
cdef CStatus to_status(self):
return MakeFlightError(CFlightStatusUnauthorized, tobytes(str(self)),
self.extra_info)
cdef class FlightUnavailableError(FlightError, ArrowException):
"""The server is not reachable or available."""
cdef CStatus to_status(self):
return MakeFlightError(CFlightStatusUnavailable, tobytes(str(self)),
self.extra_info)
class FlightWriteSizeExceededError(ArrowInvalid):
"""A write operation exceeded the client-configured limit."""
def __init__(self, message, limit, actual):
super().__init__(message)
self.limit = limit
self.actual = actual
cdef class Action(_Weakrefable):
"""An action executable on a Flight service."""
cdef:
CAction action
def __init__(self, action_type, buf):
"""Create an action from a type and a buffer.
Parameters
----------
action_type : bytes or str
buf : Buffer or bytes-like object
"""
self.action.type = tobytes(action_type)
self.action.body = pyarrow_unwrap_buffer(as_buffer(buf))
@property
def type(self):
"""The action type."""
return frombytes(self.action.type)
@property
def body(self):
"""The action body (arguments for the action)."""
return pyarrow_wrap_buffer(self.action.body)
@staticmethod
cdef CAction unwrap(action) except *:
if not isinstance(action, Action):
raise TypeError("Must provide Action, not '{}'".format(
type(action)))
return (<Action> action).action
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.action.SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef Action action = Action.__new__(Action)
action.action = GetResultValue(
CAction.Deserialize(tobytes(serialized)))
return action
def __eq__(self, Action other):
return self.action == other.action
def __repr__(self):
return (f"<pyarrow.flight.Action type={self.type!r} "
f"body=({self.body.size} bytes)>")
_ActionType = collections.namedtuple('_ActionType', ['type', 'description'])
class ActionType(_ActionType):
"""A type of action that is executable on a Flight service."""
def make_action(self, buf):
"""Create an Action with this type.
Parameters
----------
buf : obj
An Arrow buffer or Python bytes or bytes-like object.
"""
return Action(self.type, buf)
cdef class Result(_Weakrefable):
"""A result from executing an Action."""
cdef:
unique_ptr[CFlightResult] result
def __init__(self, buf):
"""Create a new result.
Parameters
----------
buf : Buffer or bytes-like object
"""
self.result.reset(new CFlightResult())
self.result.get().body = pyarrow_unwrap_buffer(as_buffer(buf))
@property
def body(self):
"""Get the Buffer containing the result."""
return pyarrow_wrap_buffer(self.result.get().body)
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.result.get().SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef Result result = Result.__new__(Result)
result.result.reset(new CFlightResult(GetResultValue(
CFlightResult.Deserialize(tobytes(serialized)))))
return result
def __eq__(self, Result other):
return deref(self.result.get()) == deref(other.result.get())
def __repr__(self):
return f"<pyarrow.flight.Result body=({self.body.size} bytes)>"
cdef class BasicAuth(_Weakrefable):
"""A container for basic auth."""
cdef:
unique_ptr[CBasicAuth] basic_auth
def __init__(self, username=None, password=None):
"""Create a new basic auth object.
Parameters
----------
username : string
password : string
"""
self.basic_auth.reset(new CBasicAuth())
if username:
self.basic_auth.get().username = tobytes(username)
if password:
self.basic_auth.get().password = tobytes(password)
@property
def username(self):
"""Get the username."""
return self.basic_auth.get().username
@property
def password(self):
"""Get the password."""
return self.basic_auth.get().password
@staticmethod
def deserialize(serialized):
auth = BasicAuth()
auth.basic_auth.reset(new CBasicAuth(GetResultValue(
CBasicAuth.Deserialize(tobytes(serialized)))))
return auth
def serialize(self):
return GetResultValue(self.basic_auth.get().SerializeToString())
def __eq__(self, BasicAuth other):
return deref(self.basic_auth.get()) == deref(other.basic_auth.get())
def __repr__(self):
return (f"<pyarrow.flight.BasicAuth username={self.username!r} "
"password=(redacted)>")
class DescriptorType(enum.Enum):
"""
The type of a FlightDescriptor.
Attributes
----------
UNKNOWN
An unknown descriptor type.
PATH
A Flight stream represented by a path.
CMD
A Flight stream represented by an application-defined command.
"""
UNKNOWN = 0
PATH = 1
CMD = 2
class FlightMethod(enum.Enum):
"""The implemented methods in Flight."""
INVALID = 0
HANDSHAKE = 1
LIST_FLIGHTS = 2
GET_FLIGHT_INFO = 3
GET_SCHEMA = 4
DO_GET = 5
DO_PUT = 6
DO_ACTION = 7
LIST_ACTIONS = 8
DO_EXCHANGE = 9
cdef wrap_flight_method(CFlightMethod method):
if method == CFlightMethodHandshake:
return FlightMethod.HANDSHAKE
elif method == CFlightMethodListFlights:
return FlightMethod.LIST_FLIGHTS
elif method == CFlightMethodGetFlightInfo:
return FlightMethod.GET_FLIGHT_INFO
elif method == CFlightMethodGetSchema:
return FlightMethod.GET_SCHEMA
elif method == CFlightMethodDoGet:
return FlightMethod.DO_GET
elif method == CFlightMethodDoPut:
return FlightMethod.DO_PUT
elif method == CFlightMethodDoAction:
return FlightMethod.DO_ACTION
elif method == CFlightMethodListActions:
return FlightMethod.LIST_ACTIONS
elif method == CFlightMethodDoExchange:
return FlightMethod.DO_EXCHANGE
return FlightMethod.INVALID
cdef class FlightDescriptor(_Weakrefable):
"""A description of a data stream available from a Flight service."""
cdef:
CFlightDescriptor descriptor
def __init__(self):
raise TypeError("Do not call {}'s constructor directly, use "
"`pyarrow.flight.FlightDescriptor.for_{path,command}` "
"function instead."
.format(self.__class__.__name__))
@staticmethod
def for_path(*path):
"""Create a FlightDescriptor for a resource path."""
cdef FlightDescriptor result = \
FlightDescriptor.__new__(FlightDescriptor)
result.descriptor.type = CDescriptorTypePath
result.descriptor.path = [tobytes(p) for p in path]
return result
@staticmethod
def for_command(command):
"""Create a FlightDescriptor for an opaque command."""
cdef FlightDescriptor result = \
FlightDescriptor.__new__(FlightDescriptor)
result.descriptor.type = CDescriptorTypeCmd
result.descriptor.cmd = tobytes(command)
return result
@property
def descriptor_type(self):
"""Get the type of this descriptor."""
if self.descriptor.type == CDescriptorTypeUnknown:
return DescriptorType.UNKNOWN
elif self.descriptor.type == CDescriptorTypePath:
return DescriptorType.PATH
elif self.descriptor.type == CDescriptorTypeCmd:
return DescriptorType.CMD
raise RuntimeError("Invalid descriptor type!")
@property
def command(self):
"""Get the command for this descriptor."""
if self.descriptor_type != DescriptorType.CMD:
return None
return self.descriptor.cmd
@property
def path(self):
"""Get the path for this descriptor."""
if self.descriptor_type != DescriptorType.PATH:
return None
return self.descriptor.path
def __repr__(self):
if self.descriptor_type == DescriptorType.PATH:
return f"<pyarrow.flight.FlightDescriptor path={self.path!r}>"
elif self.descriptor_type == DescriptorType.CMD:
return f"<pyarrow.flight.FlightDescriptor cmd={self.command!r}>"
else:
return "<pyarrow.flight.FlightDescriptor UNKNOWN>"
@staticmethod
cdef CFlightDescriptor unwrap(descriptor) except *:
if not isinstance(descriptor, FlightDescriptor):
raise TypeError("Must provide a FlightDescriptor, not '{}'".format(
type(descriptor)))
return (<FlightDescriptor> descriptor).descriptor
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.descriptor.SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef FlightDescriptor descriptor = \
FlightDescriptor.__new__(FlightDescriptor)
descriptor.descriptor = GetResultValue(
CFlightDescriptor.Deserialize(tobytes(serialized)))
return descriptor
def __eq__(self, FlightDescriptor other):
return self.descriptor == other.descriptor
cdef class Ticket(_Weakrefable):
"""A ticket for requesting a Flight stream."""
cdef:
CTicket c_ticket
def __init__(self, ticket):
self.c_ticket.ticket = tobytes(ticket)
@property
def ticket(self):
return self.c_ticket.ticket
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.c_ticket.SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef Ticket ticket = Ticket.__new__(Ticket)
ticket.c_ticket = GetResultValue(
CTicket.Deserialize(tobytes(serialized)))
return ticket
def __eq__(self, Ticket other):
return self.c_ticket == other.c_ticket
def __repr__(self):
return f"<pyarrow.flight.Ticket ticket={self.ticket!r}>"
cdef class Location(_Weakrefable):
"""The location of a Flight service."""
cdef:
CLocation location
def __init__(self, uri):
check_flight_status(CLocation.Parse(tobytes(uri)).Value(&self.location))
def __repr__(self):
return f'<pyarrow.flight.Location {self.location.ToString()}>'
@property
def uri(self):
return self.location.ToString()
def equals(self, Location other):
return self == other
def __eq__(self, other):
if not isinstance(other, Location):
return NotImplemented
return self.location.Equals((<Location> other).location)
@staticmethod
def for_grpc_tcp(host, port):
"""Create a Location for a TCP-based gRPC service."""
cdef:
c_string c_host = tobytes(host)
int c_port = port
Location result = Location.__new__(Location)
check_flight_status(
CLocation.ForGrpcTcp(c_host, c_port).Value(&result.location))
return result
@staticmethod
def for_grpc_tls(host, port):
"""Create a Location for a TLS-based gRPC service."""
cdef:
c_string c_host = tobytes(host)
int c_port = port
Location result = Location.__new__(Location)
check_flight_status(
CLocation.ForGrpcTls(c_host, c_port).Value(&result.location))
return result
@staticmethod
def for_grpc_unix(path):
"""Create a Location for a domain socket-based gRPC service."""
cdef:
c_string c_path = tobytes(path)
Location result = Location.__new__(Location)
check_flight_status(CLocation.ForGrpcUnix(c_path).Value(&result.location))
return result
@staticmethod
cdef Location wrap(CLocation location):
cdef Location result = Location.__new__(Location)
result.location = location
return result
@staticmethod
cdef CLocation unwrap(object location) except *:
cdef CLocation c_location
if isinstance(location, str):
check_flight_status(
CLocation.Parse(tobytes(location)).Value(&c_location))
return c_location
elif not isinstance(location, Location):
raise TypeError("Must provide a Location, not '{}'".format(
type(location)))
return (<Location> location).location
cdef class FlightEndpoint(_Weakrefable):
"""A Flight stream, along with the ticket and locations to access it."""
cdef:
CFlightEndpoint endpoint
def __init__(self, ticket, locations):
"""Create a FlightEndpoint from a ticket and list of locations.
Parameters
----------
ticket : Ticket or bytes
the ticket needed to access this flight
locations : list of string URIs
locations where this flight is available
Raises
------
ArrowException
If one of the location URIs is not a valid URI.
"""
cdef:
CLocation c_location
if isinstance(ticket, Ticket):
self.endpoint.ticket.ticket = tobytes(ticket.ticket)
else:
self.endpoint.ticket.ticket = tobytes(ticket)
for location in locations:
if isinstance(location, Location):
c_location = (<Location> location).location
else:
c_location = CLocation()
check_flight_status(
CLocation.Parse(tobytes(location)).Value(&c_location))
self.endpoint.locations.push_back(c_location)
@property
def ticket(self):
"""Get the ticket in this endpoint."""
return Ticket(self.endpoint.ticket.ticket)
@property
def locations(self):
return [Location.wrap(location)
for location in self.endpoint.locations]
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.endpoint.SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef FlightEndpoint endpoint = FlightEndpoint.__new__(FlightEndpoint)
endpoint.endpoint = GetResultValue(
CFlightEndpoint.Deserialize(tobytes(serialized)))
return endpoint
def __repr__(self):
return (f"<pyarrow.flight.FlightEndpoint ticket={self.ticket!r} "
f"locations={self.locations!r}>")
def __eq__(self, FlightEndpoint other):
return self.endpoint == other.endpoint
cdef class SchemaResult(_Weakrefable):
"""The serialized schema returned from a GetSchema request."""
cdef:
unique_ptr[CSchemaResult] result
def __init__(self, Schema schema):
"""Create a SchemaResult from a schema.
Parameters
----------
schema: Schema
the schema of the data in this flight.
"""
cdef:
shared_ptr[CSchema] c_schema = pyarrow_unwrap_schema(schema)
check_flight_status(CreateSchemaResult(c_schema, &self.result))
@property
def schema(self):
"""The schema of the data in this flight."""
cdef:
shared_ptr[CSchema] schema
CDictionaryMemo dummy_memo
check_flight_status(self.result.get().GetSchema(&dummy_memo).Value(&schema))
return pyarrow_wrap_schema(schema)
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.result.get().SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef SchemaResult result = SchemaResult.__new__(SchemaResult)
result.result.reset(new CSchemaResult(GetResultValue(
CSchemaResult.Deserialize(tobytes(serialized)))))
return result
def __eq__(self, SchemaResult other):
return deref(self.result.get()) == deref(other.result.get())
def __repr__(self):
return f"<pyarrow.flight.SchemaResult schema=({self.schema})>"
cdef class FlightInfo(_Weakrefable):
"""A description of a Flight stream."""
cdef:
unique_ptr[CFlightInfo] info
@staticmethod
cdef wrap(CFlightInfo c_info):
cdef FlightInfo obj = FlightInfo.__new__(FlightInfo)
obj.info.reset(new CFlightInfo(move(c_info)))
return obj
def __init__(self, Schema schema, FlightDescriptor descriptor, endpoints,
total_records, total_bytes):
"""Create a FlightInfo object from a schema, descriptor, and endpoints.
Parameters
----------
schema : Schema
the schema of the data in this flight.
descriptor : FlightDescriptor
the descriptor for this flight.
endpoints : list of FlightEndpoint
a list of endpoints where this flight is available.
total_records : int
the total records in this flight, or -1 if unknown
total_bytes : int
the total bytes in this flight, or -1 if unknown
"""
cdef:
shared_ptr[CSchema] c_schema = pyarrow_unwrap_schema(schema)
vector[CFlightEndpoint] c_endpoints
for endpoint in endpoints:
if isinstance(endpoint, FlightEndpoint):
c_endpoints.push_back((<FlightEndpoint> endpoint).endpoint)
else:
raise TypeError('Endpoint {} is not instance of'
' FlightEndpoint'.format(endpoint))
check_flight_status(CreateFlightInfo(c_schema,
descriptor.descriptor,
c_endpoints,
total_records,
total_bytes, &self.info))
@property
def total_records(self):
"""The total record count of this flight, or -1 if unknown."""
return self.info.get().total_records()
@property
def total_bytes(self):
"""The size in bytes of the data in this flight, or -1 if unknown."""
return self.info.get().total_bytes()
@property
def schema(self):
"""The schema of the data in this flight."""
cdef:
shared_ptr[CSchema] schema
CDictionaryMemo dummy_memo
check_flight_status(self.info.get().GetSchema(&dummy_memo).Value(&schema))
return pyarrow_wrap_schema(schema)
@property
def descriptor(self):
"""The descriptor of the data in this flight."""
cdef FlightDescriptor result = \
FlightDescriptor.__new__(FlightDescriptor)
result.descriptor = self.info.get().descriptor()
return result
@property
def endpoints(self):
"""The endpoints where this flight is available."""
# TODO: get Cython to iterate over reference directly
cdef:
vector[CFlightEndpoint] endpoints = self.info.get().endpoints()
FlightEndpoint py_endpoint
result = []
for endpoint in endpoints:
py_endpoint = FlightEndpoint.__new__(FlightEndpoint)
py_endpoint.endpoint = endpoint
result.append(py_endpoint)
return result
def serialize(self):
"""Get the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
return GetResultValue(self.info.get().SerializeToString())
@classmethod
def deserialize(cls, serialized):
"""Parse the wire-format representation of this type.
Useful when interoperating with non-Flight systems (e.g. REST
services) that may want to return Flight types.
"""
cdef FlightInfo info = FlightInfo.__new__(FlightInfo)
info.info = move(GetResultValue(
CFlightInfo.Deserialize(tobytes(serialized))))
return info
def __eq__(self, FlightInfo other):
return deref(self.info.get()) == deref(other.info.get())
def __repr__(self):
return (f"<pyarrow.flight.FlightInfo schema={self.schema} "
f"descriptor={self.descriptor} "
f"endpoints={self.endpoints} "
f"total_records={self.total_records} "
f"total_bytes={self.total_bytes}>")
cdef class FlightStreamChunk(_Weakrefable):
"""A RecordBatch with application metadata on the side."""
cdef:
CFlightStreamChunk chunk
@property
def data(self):
if self.chunk.data == NULL:
return None
return pyarrow_wrap_batch(self.chunk.data)
@property
def app_metadata(self):
if self.chunk.app_metadata == NULL:
return None
return pyarrow_wrap_buffer(self.chunk.app_metadata)
def __iter__(self):
return iter((self.data, self.app_metadata))
def __repr__(self):
return "<FlightStreamChunk with data: {} with metadata: {}>".format(
self.chunk.data != NULL, self.chunk.app_metadata != NULL)
cdef class _MetadataRecordBatchReader(_Weakrefable, _ReadPandasMixin):
"""A reader for Flight streams."""
# Needs to be separate class so the "real" class can subclass the
# pure-Python mixin class
cdef dict __dict__
cdef shared_ptr[CMetadataRecordBatchReader] reader
def __iter__(self):
return self
def __next__(self):
return self.read_chunk()
@property
def schema(self):
"""Get the schema for this reader."""
cdef shared_ptr[CSchema] c_schema
with nogil: