-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathasgi.py
More file actions
executable file
·2137 lines (1842 loc) · 70.7 KB
/
asgi.py
File metadata and controls
executable file
·2137 lines (1842 loc) · 70.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
#!/usr/bin/env python3
"""
Web application for SingleStoreDB external functions.
This module supplies a function that can create web apps intended for use
with the external function feature of SingleStoreDB. The application
function is a standard ASGI <https://asgi.readthedocs.io/en/latest/index.html>
request handler for use with servers such as Uvicorn <https://www.uvicorn.org>.
An external function web application can be created using the `create_app`
function. By default, the exported Python functions are specified by
environment variables starting with SINGLESTOREDB_EXT_FUNCTIONS. See the
documentation in `create_app` for the full syntax. If the application is
created in Python code rather than from the command-line, exported
functions can be specified in the parameters.
An example of starting a server is shown below.
Example
-------
> SINGLESTOREDB_EXT_FUNCTIONS='myfuncs.[percentile_90,percentile_95]' \
python3 -m singlestoredb.functions.ext.asgi
"""
import argparse
import asyncio
import contextvars
import dataclasses
import datetime
import functools
import importlib.util
import inspect
import io
import itertools
import json
import logging
import os
import re
import secrets
import sys
import tempfile
import textwrap
import threading
import time
import typing
import urllib
import uuid
import zipfile
import zipimport
from types import ModuleType
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import List
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Union
from . import arrow
from . import json as jdata
from . import rowdat_1
from . import utils
from ... import connection
from ... import manage_workspaces
from ...config import get_option
from ...mysql.constants import FIELD_TYPE as ft
from ..signature import get_signature
from ..signature import signature_to_sql
from ..typing import Masked
from ..typing import Table
from .timer import Timer
from singlestoredb.docstring.parser import parse
from singlestoredb.functions.dtypes import escape_name
try:
import cloudpickle
has_cloudpickle = True
except ImportError:
has_cloudpickle = False
try:
from pydantic import BaseModel
has_pydantic = True
except ImportError:
has_pydantic = False
logger = utils.get_logger('singlestoredb.functions.ext.asgi')
# If a number of processes is specified, create a pool of workers
num_processes = max(0, int(os.environ.get('SINGLESTOREDB_EXT_NUM_PROCESSES', 0)))
if num_processes > 1:
try:
from ray.util.multiprocessing import Pool
except ImportError:
from multiprocessing import Pool
func_map = Pool(num_processes).starmap
else:
func_map = itertools.starmap
async def to_thread(
func: Any, /, *args: Any, **kwargs: Dict[str, Any],
) -> Any:
loop = asyncio.get_running_loop()
ctx = contextvars.copy_context()
func_call = functools.partial(ctx.run, func, *args, **kwargs)
return await loop.run_in_executor(None, func_call)
# Use negative values to indicate unsigned ints / binary data / usec time precision
rowdat_1_type_map = {
'bool': ft.LONGLONG,
'int8': ft.LONGLONG,
'int16': ft.LONGLONG,
'int32': ft.LONGLONG,
'int64': ft.LONGLONG,
'uint8': -ft.LONGLONG,
'uint16': -ft.LONGLONG,
'uint32': -ft.LONGLONG,
'uint64': -ft.LONGLONG,
'float32': ft.DOUBLE,
'float64': ft.DOUBLE,
'str': ft.STRING,
'bytes': -ft.STRING,
}
def get_func_names(funcs: str) -> List[Tuple[str, str]]:
"""
Parse all function names from string.
Parameters
----------
func_names : str
String containing one or more function names. The syntax is
as follows: [func-name-1@func-alias-1,func-name-2@func-alias-2,...].
The optional '@name' portion is an alias if you want the function
to be renamed.
Returns
-------
List[Tuple[str]] : a list of tuples containing the names and aliases
of each function.
"""
if funcs.startswith('['):
func_names = funcs.replace('[', '').replace(']', '').split(',')
func_names = [x.strip() for x in func_names]
else:
func_names = [funcs]
out = []
for name in func_names:
alias = name
if '@' in name:
name, alias = name.split('@', 1)
out.append((name, alias))
return out
def as_tuple(x: Any) -> Any:
"""Convert object to tuple."""
if has_pydantic and isinstance(x, BaseModel):
return tuple(x.model_dump().values())
if dataclasses.is_dataclass(x):
return dataclasses.astuple(x) # type: ignore
if isinstance(x, dict):
return tuple(x.values())
return tuple(x)
def as_list_of_tuples(x: Any) -> Any:
"""Convert object to a list of tuples."""
if isinstance(x, Table):
x = x[0]
if isinstance(x, (list, tuple)) and len(x) > 0:
if isinstance(x[0], (list, tuple)):
return x
if has_pydantic and isinstance(x[0], BaseModel):
return [tuple(y.model_dump().values()) for y in x]
if dataclasses.is_dataclass(x[0]):
return [dataclasses.astuple(y) for y in x]
if isinstance(x[0], dict):
return [tuple(y.values()) for y in x]
return [(y,) for y in x]
return x
def get_dataframe_columns(df: Any) -> List[Any]:
"""Return columns of data from a dataframe/table."""
if isinstance(df, Table):
if len(df) == 1:
df = df[0]
else:
return list(df)
if isinstance(df, Masked):
return [df]
if isinstance(df, tuple):
return list(df)
rtype = str(type(df)).lower()
if 'dataframe' in rtype:
return [df[x] for x in df.columns]
elif 'table' in rtype:
return df.columns
elif 'series' in rtype:
return [df]
elif 'array' in rtype:
return [df]
elif 'tuple' in rtype:
return list(df)
raise TypeError(
'Unsupported data type for dataframe columns: '
f'{rtype}',
)
def get_array_class(data_format: str) -> Callable[..., Any]:
"""
Get the array class for the current data format.
"""
if data_format == 'polars':
import polars as pl
array_cls = pl.Series
elif data_format == 'arrow':
import pyarrow as pa
array_cls = pa.array
elif data_format == 'pandas':
import pandas as pd
array_cls = pd.Series
else:
import numpy as np
array_cls = np.array
return array_cls
def get_masked_params(func: Callable[..., Any]) -> List[bool]:
"""
Get the list of masked parameters for the function.
Parameters
----------
func : Callable
The function to call as the endpoint
Returns
-------
List[bool]
Boolean list of masked parameters
"""
params = inspect.signature(func).parameters
return [typing.get_origin(x.annotation) is Masked for x in params.values()]
def build_tuple(x: Any) -> Any:
"""Convert object to tuple."""
return tuple(x) if isinstance(x, Masked) else (x, None)
def cancel_on_event(
cancel_event: threading.Event,
) -> None:
"""
Cancel the function call if the cancel event is set.
Parameters
----------
cancel_event : threading.Event
The event to check for cancellation
Raises
------
asyncio.CancelledError
If the cancel event is set
"""
if cancel_event.is_set():
task = asyncio.current_task()
if task is not None:
task.cancel()
raise asyncio.CancelledError(
'Function call was cancelled by client',
)
def build_udf_endpoint(
func: Callable[..., Any],
returns_data_format: str,
) -> Callable[..., Any]:
"""
Build a UDF endpoint for scalar / list types (row-based).
Parameters
----------
func : Callable
The function to call as the endpoint
returns_data_format : str
The format of the return values
Returns
-------
Callable
The function endpoint
"""
if returns_data_format in ['scalar', 'list']:
is_async = asyncio.iscoroutinefunction(func)
async def do_func(
cancel_event: threading.Event,
timer: Timer,
row_ids: Sequence[int],
rows: Sequence[Sequence[Any]],
) -> Tuple[Sequence[int], List[Tuple[Any, ...]]]:
'''Call function on given rows of data.'''
out = []
async with timer('call_function'):
for row in rows:
cancel_on_event(cancel_event)
if is_async:
out.append(await func(*row))
else:
out.append(func(*row))
return row_ids, list(zip(out))
return do_func
return build_vector_udf_endpoint(func, returns_data_format)
def build_vector_udf_endpoint(
func: Callable[..., Any],
returns_data_format: str,
) -> Callable[..., Any]:
"""
Build a UDF endpoint for vector formats (column-based).
Parameters
----------
func : Callable
The function to call as the endpoint
returns_data_format : str
The format of the return values
Returns
-------
Callable
The function endpoint
"""
masks = get_masked_params(func)
array_cls = get_array_class(returns_data_format)
is_async = asyncio.iscoroutinefunction(func)
async def do_func(
cancel_event: threading.Event,
timer: Timer,
row_ids: Sequence[int],
cols: Sequence[Tuple[Sequence[Any], Optional[Sequence[bool]]]],
) -> Tuple[
Sequence[int],
List[Tuple[Sequence[Any], Optional[Sequence[bool]]]],
]:
'''Call function on given columns of data.'''
row_ids = array_cls(row_ids)
# Call the function with `cols` as the function parameters
async with timer('call_function'):
if cols and cols[0]:
if is_async:
out = await func(*[x if m else x[0] for x, m in zip(cols, masks)])
else:
out = func(*[x if m else x[0] for x, m in zip(cols, masks)])
else:
if is_async:
out = await func()
else:
out = func()
cancel_on_event(cancel_event)
# Single masked value
if isinstance(out, Masked):
return row_ids, [tuple(out)]
# Multiple return values
if isinstance(out, tuple):
return row_ids, [build_tuple(x) for x in out]
# Single return value
return row_ids, [(out, None)]
return do_func
def build_tvf_endpoint(
func: Callable[..., Any],
returns_data_format: str,
) -> Callable[..., Any]:
"""
Build a TVF endpoint for scalar / list types (row-based).
Parameters
----------
func : Callable
The function to call as the endpoint
returns_data_format : str
The format of the return values
Returns
-------
Callable
The function endpoint
"""
if returns_data_format in ['scalar', 'list']:
is_async = asyncio.iscoroutinefunction(func)
async def do_func(
cancel_event: threading.Event,
timer: Timer,
row_ids: Sequence[int],
rows: Sequence[Sequence[Any]],
) -> Tuple[Sequence[int], List[Tuple[Any, ...]]]:
'''Call function on given rows of data.'''
out_ids: List[int] = []
out = []
# Call function on each row of data
async with timer('call_function'):
for i, row in zip(row_ids, rows):
cancel_on_event(cancel_event)
if is_async:
res = await func(*row)
else:
res = func(*row)
out.extend(as_list_of_tuples(res))
out_ids.extend([row_ids[i]] * (len(out)-len(out_ids)))
return out_ids, out
return do_func
return build_vector_tvf_endpoint(func, returns_data_format)
def build_vector_tvf_endpoint(
func: Callable[..., Any],
returns_data_format: str,
) -> Callable[..., Any]:
"""
Build a TVF endpoint for vector formats (column-based).
Parameters
----------
func : Callable
The function to call as the endpoint
returns_data_format : str
The format of the return values
Returns
-------
Callable
The function endpoint
"""
masks = get_masked_params(func)
array_cls = get_array_class(returns_data_format)
async def do_func(
cancel_event: threading.Event,
timer: Timer,
row_ids: Sequence[int],
cols: Sequence[Tuple[Sequence[Any], Optional[Sequence[bool]]]],
) -> Tuple[
Sequence[int],
List[Tuple[Sequence[Any], Optional[Sequence[bool]]]],
]:
'''Call function on given columns of data.'''
# NOTE: There is no way to determine which row ID belongs to
# each result row, so we just have to use the same
# row ID for all rows in the result.
is_async = asyncio.iscoroutinefunction(func)
# Call function on each column of data
async with timer('call_function'):
if cols and cols[0]:
if is_async:
func_res = await func(
*[x if m else x[0] for x, m in zip(cols, masks)],
)
else:
func_res = func(
*[x if m else x[0] for x, m in zip(cols, masks)],
)
else:
if is_async:
func_res = await func()
else:
func_res = func()
res = get_dataframe_columns(func_res)
cancel_on_event(cancel_event)
# Generate row IDs
if isinstance(res[0], Masked):
row_ids = array_cls([row_ids[0]] * len(res[0][0]))
else:
row_ids = array_cls([row_ids[0]] * len(res[0]))
return row_ids, [build_tuple(x) for x in res]
return do_func
def make_func(
name: str,
func: Callable[..., Any],
) -> Tuple[Callable[..., Any], Dict[str, Any]]:
"""
Make a function endpoint.
Parameters
----------
name : str
Name of the function to create
func : Callable
The function to call as the endpoint
database : str, optional
The database to use for the function definition
Returns
-------
(Callable, Dict[str, Any])
"""
info: Dict[str, Any] = {}
sig = get_signature(func, func_name=name)
function_type = sig.get('function_type', 'udf')
args_data_format = sig.get('args_data_format', 'scalar')
returns_data_format = sig.get('returns_data_format', 'scalar')
timeout = (
func._singlestoredb_attrs.get('timeout') or # type: ignore
get_option('external_function.timeout')
)
if function_type == 'tvf':
do_func = build_tvf_endpoint(func, returns_data_format)
else:
do_func = build_udf_endpoint(func, returns_data_format)
do_func.__name__ = name
do_func.__doc__ = func.__doc__
# Store signature for generating CREATE FUNCTION calls
info['signature'] = sig
# Set data format
info['args_data_format'] = args_data_format
info['returns_data_format'] = returns_data_format
# Set function type
info['function_type'] = function_type
# Set timeout
info['timeout'] = max(timeout, 1)
# Set async flag
info['is_async'] = asyncio.iscoroutinefunction(func)
# Setup argument types for rowdat_1 parser
colspec = []
for x in sig['args']:
dtype = x['dtype'].replace('?', '')
if dtype not in rowdat_1_type_map:
raise TypeError(f'no data type mapping for {dtype}')
colspec.append((x['name'], rowdat_1_type_map[dtype]))
info['colspec'] = colspec
# Setup return type
returns = []
for x in sig['returns']:
dtype = x['dtype'].replace('?', '')
if dtype not in rowdat_1_type_map:
raise TypeError(f'no data type mapping for {dtype}')
returns.append((x['name'], rowdat_1_type_map[dtype]))
info['returns'] = returns
return do_func, info
async def cancel_on_timeout(timeout: int) -> None:
"""Cancel request if it takes too long."""
await asyncio.sleep(timeout)
raise asyncio.CancelledError(
'Function call was cancelled due to timeout',
)
async def cancel_on_disconnect(
receive: Callable[..., Awaitable[Any]],
) -> None:
"""Cancel request if client disconnects."""
while True:
message = await receive()
if message.get('type', '') == 'http.disconnect':
raise asyncio.CancelledError(
'Function call was cancelled by client',
)
async def cancel_all_tasks(tasks: Iterable[asyncio.Task[Any]]) -> None:
"""Cancel all tasks."""
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
def start_counter() -> float:
"""Start a timer and return the start time."""
return time.perf_counter()
def end_counter(start: float) -> float:
"""End a timer and return the elapsed time."""
return time.perf_counter() - start
class Application(object):
"""
Create an external function application.
If `functions` is None, the environment is searched for function
specifications in variables starting with `SINGLESTOREDB_EXT_FUNCTIONS`.
Any number of environment variables can be specified as long as they
have this prefix. The format of the environment variable value is the
same as for the `functions` parameter.
Parameters
----------
functions : str or Iterable[str], optional
Python functions are specified using a string format as follows:
* Single function : <pkg1>.<func1>
* Multiple functions : <pkg1>.[<func1-name,func2-name,...]
* Function aliases : <pkg1>.[<func1@alias1,func2@alias2,...]
* Multiple packages : <pkg1>.<func1>:<pkg2>.<func2>
app_mode : str, optional
The mode of operation for the application: remote, managed, or collocated
url : str, optional
The URL of the function API
data_format : str, optional
The format of the data rows: 'rowdat_1' or 'json'
data_version : str, optional
The version of the call format to expect: '1.0'
link_name : str, optional
The link name to use for the external function application. This is
only for pre-existing links, and can only be used without
``link_config`` and ``link_credentials``.
link_config : Dict[str, Any], optional
The CONFIG section of a LINK definition. This dictionary gets
converted to JSON for the CREATE LINK call.
link_credentials : Dict[str, Any], optional
The CREDENTIALS section of a LINK definition. This dictionary gets
converted to JSON for the CREATE LINK call.
name_prefix : str, optional
Prefix to add to function names when registering with the database
name_suffix : str, optional
Suffix to add to function names when registering with the database
function_database : str, optional
The database to use for external function definitions.
log_file : str, optional
File path to write logs to instead of console. If None, logs are
written to console. When specified, application logger handlers
are replaced with a file handler.
log_level : str, optional
Logging level for the application logger. Valid values are 'info',
'debug', 'warning', 'error'. Defaults to 'info'.
disable_metrics : bool, optional
Disable logging of function call metrics. Defaults to False.
app_name : str, optional
Name for the application instance. Used to create a logger-specific
name. If not provided, a random name will be generated.
"""
# Plain text response start
text_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=200,
headers=[(b'content-type', b'text/plain')],
)
# Error response start
error_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=500,
headers=[(b'content-type', b'application/json')],
)
# Timeout response start
timeout_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=504,
headers=[(b'content-type', b'application/json')],
)
# Cancel response start
cancel_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=503,
headers=[(b'content-type', b'application/json')],
)
# JSON response start
json_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=200,
headers=[(b'content-type', b'application/json')],
)
# ROWDAT_1 response start
rowdat_1_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=200,
headers=[(b'content-type', b'x-application/rowdat_1')],
)
# Apache Arrow response start
arrow_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=200,
headers=[(b'content-type', b'application/vnd.apache.arrow.file')],
)
# Path not found response start
path_not_found_response_dict: Dict[str, Any] = dict(
type='http.response.start',
status=404,
)
# Response body template
body_response_dict: Dict[str, Any] = dict(
type='http.response.body',
)
# Data format + version handlers
handlers = {
(b'application/octet-stream', b'1.0', 'scalar'): dict(
load=rowdat_1.load,
dump=rowdat_1.dump,
response=rowdat_1_response_dict,
),
(b'application/octet-stream', b'1.0', 'list'): dict(
load=rowdat_1.load,
dump=rowdat_1.dump,
response=rowdat_1_response_dict,
),
(b'application/octet-stream', b'1.0', 'pandas'): dict(
load=rowdat_1.load_pandas,
dump=rowdat_1.dump_pandas,
response=rowdat_1_response_dict,
),
(b'application/octet-stream', b'1.0', 'numpy'): dict(
load=rowdat_1.load_numpy,
dump=rowdat_1.dump_numpy,
response=rowdat_1_response_dict,
),
(b'application/octet-stream', b'1.0', 'polars'): dict(
load=rowdat_1.load_polars,
dump=rowdat_1.dump_polars,
response=rowdat_1_response_dict,
),
(b'application/octet-stream', b'1.0', 'arrow'): dict(
load=rowdat_1.load_arrow,
dump=rowdat_1.dump_arrow,
response=rowdat_1_response_dict,
),
(b'application/json', b'1.0', 'scalar'): dict(
load=jdata.load,
dump=jdata.dump,
response=json_response_dict,
),
(b'application/json', b'1.0', 'list'): dict(
load=jdata.load,
dump=jdata.dump,
response=json_response_dict,
),
(b'application/json', b'1.0', 'pandas'): dict(
load=jdata.load_pandas,
dump=jdata.dump_pandas,
response=json_response_dict,
),
(b'application/json', b'1.0', 'numpy'): dict(
load=jdata.load_numpy,
dump=jdata.dump_numpy,
response=json_response_dict,
),
(b'application/json', b'1.0', 'polars'): dict(
load=jdata.load_polars,
dump=jdata.dump_polars,
response=json_response_dict,
),
(b'application/json', b'1.0', 'arrow'): dict(
load=jdata.load_arrow,
dump=jdata.dump_arrow,
response=json_response_dict,
),
(b'application/vnd.apache.arrow.file', b'1.0', 'scalar'): dict(
load=arrow.load,
dump=arrow.dump,
response=arrow_response_dict,
),
(b'application/vnd.apache.arrow.file', b'1.0', 'pandas'): dict(
load=arrow.load_pandas,
dump=arrow.dump_pandas,
response=arrow_response_dict,
),
(b'application/vnd.apache.arrow.file', b'1.0', 'numpy'): dict(
load=arrow.load_numpy,
dump=arrow.dump_numpy,
response=arrow_response_dict,
),
(b'application/vnd.apache.arrow.file', b'1.0', 'polars'): dict(
load=arrow.load_polars,
dump=arrow.dump_polars,
response=arrow_response_dict,
),
(b'application/vnd.apache.arrow.file', b'1.0', 'arrow'): dict(
load=arrow.load_arrow,
dump=arrow.dump_arrow,
response=arrow_response_dict,
),
}
# Valid URL paths
invoke_path = ('invoke',)
show_create_function_path = ('show', 'create_function')
show_function_info_path = ('show', 'function_info')
status = ('status',)
def __init__(
self,
functions: Optional[
Union[
str,
Iterable[str],
Callable[..., Any],
Iterable[Callable[..., Any]],
ModuleType,
Iterable[ModuleType],
]
] = None,
app_mode: str = get_option('external_function.app_mode'),
url: str = get_option('external_function.url'),
data_format: str = get_option('external_function.data_format'),
data_version: str = get_option('external_function.data_version'),
link_name: Optional[str] = get_option('external_function.link_name'),
link_config: Optional[Dict[str, Any]] = None,
link_credentials: Optional[Dict[str, Any]] = None,
name_prefix: str = get_option('external_function.name_prefix'),
name_suffix: str = get_option('external_function.name_suffix'),
function_database: Optional[str] = None,
log_file: Optional[str] = get_option('external_function.log_file'),
log_level: str = get_option('external_function.log_level'),
disable_metrics: bool = get_option('external_function.disable_metrics'),
app_name: Optional[str] = get_option('external_function.app_name'),
) -> None:
if link_name and (link_config or link_credentials):
raise ValueError(
'`link_name` can not be used with `link_config` or `link_credentials`',
)
if link_config is None:
link_config = json.loads(
get_option('external_function.link_config') or '{}',
) or None
if link_credentials is None:
link_credentials = json.loads(
get_option('external_function.link_credentials') or '{}',
) or None
# Generate application name if not provided
if app_name is None:
app_name = f'udf_app_{secrets.token_hex(4)}'
self.name = app_name
# Create logger instance specific to this application
self.logger = utils.get_logger(f'singlestoredb.functions.ext.asgi.{self.name}')
# List of functions specs
specs: List[Union[str, Callable[..., Any], ModuleType]] = []
# Look up Python function specifications
if functions is None:
env_vars = [
x for x in os.environ.keys()
if x.startswith('SINGLESTOREDB_EXT_FUNCTIONS')
]
if env_vars:
specs = [os.environ[x] for x in env_vars]
else:
import __main__
specs = [__main__]
elif isinstance(functions, ModuleType):
specs = [functions]
elif isinstance(functions, str):
specs = [functions]
elif callable(functions):
specs = [functions]
else:
specs = list(functions)
# Add functions to application
endpoints = dict()
external_functions = dict()
for funcs in itertools.chain(specs):
if isinstance(funcs, str):
# Module name
if importlib.util.find_spec(funcs) is not None:
items = importlib.import_module(funcs)
for x in vars(items).values():
if not hasattr(x, '_singlestoredb_attrs'):
continue
name = x._singlestoredb_attrs.get('name', x.__name__)
name = f'{name_prefix}{name}{name_suffix}'
external_functions[x.__name__] = x
func, info = make_func(name, x)
endpoints[name.encode('utf-8')] = func, info
# Fully qualified function name
elif '.' in funcs:
pkg_path, func_names = funcs.rsplit('.', 1)
pkg = importlib.import_module(pkg_path)
if pkg is None:
raise RuntimeError(f'Could not locate module: {pkg}')
# Add endpoint for each exported function
for name, alias in get_func_names(func_names):
item = getattr(pkg, name)
alias = f'{name_prefix}{name}{name_suffix}'
external_functions[name] = item
func, info = make_func(alias, item)
endpoints[alias.encode('utf-8')] = func, info
else:
raise RuntimeError(f'Could not locate module: {funcs}')
elif isinstance(funcs, ModuleType):
for x in vars(funcs).values():
if not hasattr(x, '_singlestoredb_attrs'):
continue
name = x._singlestoredb_attrs.get('name', x.__name__)
name = f'{name_prefix}{name}{name_suffix}'
external_functions[x.__name__] = x
func, info = make_func(name, x)
endpoints[name.encode('utf-8')] = func, info
else:
alias = funcs.__name__
external_functions[funcs.__name__] = funcs
alias = f'{name_prefix}{alias}{name_suffix}'
func, info = make_func(alias, funcs)
endpoints[alias.encode('utf-8')] = func, info
self.app_mode = app_mode
self.url = url
self.data_format = data_format
self.data_version = data_version
self.link_name = link_name
self.link_config = link_config
self.link_credentials = link_credentials
self.endpoints = endpoints
self.external_functions = external_functions
self.function_database = function_database
self.log_file = log_file
self.log_level = log_level
self.disable_metrics = disable_metrics