Skip to content

Commit 1bcd3e6

Browse files
committed
Type information added and other nit fixes
1 parent b7bcd98 commit 1bcd3e6

File tree

11 files changed

+55
-50
lines changed

11 files changed

+55
-50
lines changed

azure_functions_worker/_thirdparty/aio_compat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Backport of asyncio.run() function from Python 3.7.
22
33
Source: https://github.com/python/cpython/blob/
4-
bd093355a6aaf2f4ca3ed153e195da57870a55eb/Lib/asyncio/runners.py
4+
bd093355a6aaf2f4ca3ed153e195da57870a55eb/Lib/asyncio/runners.py
55
"""
66

77

@@ -13,7 +13,7 @@ def get_running_loop():
1313
1414
This function is thread-specific.
1515
"""
16-
loop = asyncio._get_running_loop()
16+
loop = asyncio.events.get_running_loop()
1717
if loop is None:
1818
raise RuntimeError('no running event loop')
1919
return loop

azure_functions_worker/bindings/generic.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import typing
44

55
from . import datumdef
6+
from azure_functions_worker.bindings.datumdef import Datum
7+
from typing import Any, Optional
68

79

810
class GenericBinding:
@@ -20,8 +22,7 @@ def check_output_type_annotation(cls, pytype: type) -> bool:
2022
return issubclass(pytype, (str, bytes, bytearray))
2123

2224
@classmethod
23-
def encode(cls, obj: typing.Any, *,
24-
expected_type: typing.Optional[type]) -> datumdef.Datum:
25+
def encode(cls, obj: typing.Any, *, expected_type: typing.Optional[type]) -> datumdef.Datum:
2526
if isinstance(obj, str):
2627
return datumdef.Datum(type='string', value=obj)
2728

azure_functions_worker/bindings/out.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44

55
class Out:
66

7-
def __init__(self):
7+
def __init__(self) -> None:
88
self.__value = None
99

1010
def set(self, val):
1111
self.__value = val
1212

13-
def get(self):
13+
def get(self) -> str:
1414
return self.__value

azure_functions_worker/dispatcher.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,17 @@
2828
from .logging import enable_console_logging, disable_console_logging
2929
from .utils.tracing import marshall_exception_trace
3030
from .utils.wrappers import disable_feature_by
31+
from asyncio.unix_events import _UnixSelectorEventLoop
32+
from logging import LogRecord
33+
from typing import Any, Dict, Optional
3134

3235

3336
class DispatcherMeta(type):
3437

3538
__current_dispatcher__ = None
3639

3740
@property
38-
def current(mcls):
41+
def current(mcls) -> Dispatcher:
3942
disp = mcls.__current_dispatcher__
4043
if disp is None:
4144
raise RuntimeError('no currently running Dispatcher is found')
@@ -46,8 +49,8 @@ class Dispatcher(metaclass=DispatcherMeta):
4649

4750
_GRPC_STOP_RESPONSE = object()
4851

49-
def __init__(self, loop, host, port: int, worker_id: str, request_id: str,
50-
grpc_connect_timeout: float, grpc_max_msg_len: int = -1):
52+
def __init__(self, loop: _UnixSelectorEventLoop, host: str, port: int, worker_id: str, request_id: str,
53+
grpc_connect_timeout: float, grpc_max_msg_len: int = -1) -> None:
5154
self._loop = loop
5255
self._host = host
5356
self._port = port
@@ -78,7 +81,7 @@ def __init__(self, loop, host, port: int, worker_id: str, request_id: str,
7881
name='grpc-thread', target=self.__poll_grpc)
7982

8083
@staticmethod
81-
def load_bindings():
84+
def load_bindings() -> Dict[Any, Any]:
8285
"""Load out-of-tree binding implementations."""
8386
services = {}
8487

@@ -89,8 +92,8 @@ def load_bindings():
8992
return services
9093

9194
@classmethod
92-
async def connect(cls, host, port, worker_id, request_id,
93-
connect_timeout):
95+
async def connect(cls, host: str, port: int, worker_id: str, request_id: str,
96+
connect_timeout: float) -> Dispatcher:
9497
loop = asyncio.events.get_event_loop()
9598
disp = cls(loop, host, port, worker_id, request_id, connect_timeout)
9699
disp._grpc_thread.start()
@@ -144,7 +147,7 @@ async def dispatch_forever(self):
144147
self._loop.set_task_factory(self._old_task_factory)
145148
self.stop()
146149

147-
def stop(self):
150+
def stop(self) -> None:
148151
if self._grpc_thread is not None:
149152
self._grpc_resp_queue.put_nowait(self._GRPC_STOP_RESPONSE)
150153
self._grpc_thread.join()
@@ -154,7 +157,7 @@ def stop(self):
154157
self._sync_call_tp.shutdown()
155158
self._sync_call_tp = None
156159

157-
def on_logging(self, record: logging.LogRecord, formatted_msg: str):
160+
def on_logging(self, record: logging.LogRecord, formatted_msg: str) -> None:
158161
if record.levelno >= logging.CRITICAL:
159162
log_level = protos.RpcLog.Critical
160163
elif record.levelno >= logging.ERROR:
@@ -196,11 +199,11 @@ def on_logging(self, record: logging.LogRecord, formatted_msg: str):
196199
rpc_log=protos.RpcLog(**log)))
197200

198201
@property
199-
def request_id(self):
202+
def request_id(self) -> str:
200203
return self._request_id
201204

202205
@property
203-
def worker_id(self):
206+
def worker_id(self) -> str:
204207
return self._worker_id
205208

206209
# noinspection PyBroadException
@@ -524,7 +527,7 @@ def gen(resp_queue):
524527

525528
class AsyncLoggingHandler(logging.Handler):
526529

527-
def emit(self, record):
530+
def emit(self, record: LogRecord) -> None:
528531
# Since we disable console log after gRPC channel is initiated
529532
# We should redirect all the messages into dispatcher
530533
msg = self.format(record)
@@ -545,12 +548,12 @@ def __init__(self, coro, loop):
545548
if invocation_id is not None:
546549
self.set_azure_invocation_id(invocation_id)
547550

548-
def set_azure_invocation_id(self, invocation_id):
551+
def set_azure_invocation_id(self, invocation_id: str) -> None:
549552
setattr(self, self._AZURE_INVOCATION_ID, invocation_id)
550553

551554

552-
def get_current_invocation_id():
553-
loop = asyncio._get_running_loop()
555+
def get_current_invocation_id() -> Optional[str]:
556+
loop = asyncio.events.get_running_loop()
554557
if loop is not None:
555558
current_task = asyncio.Task.current_task(loop)
556559
if current_task is not None:

azure_functions_worker/functions.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class FunctionInfo(typing.NamedTuple):
3232

3333
class FunctionLoadError(RuntimeError):
3434

35-
def __init__(self, function_name, msg):
35+
def __init__(self, function_name: str, msg: str) -> None:
3636
super().__init__(
3737
f'cannot load the {function_name} function: {msg}')
3838

@@ -41,10 +41,10 @@ class Registry:
4141

4242
_functions: typing.MutableMapping[str, FunctionInfo]
4343

44-
def __init__(self):
44+
def __init__(self) -> None:
4545
self._functions = {}
4646

47-
def get_function(self, function_id: str):
47+
def get_function(self, function_id: str) -> FunctionInfo:
4848
try:
4949
return self._functions[function_id]
5050
except KeyError:

azure_functions_worker/loader.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,19 @@
1414

1515
from .constants import MODULE_NOT_FOUND_TS_URL
1616
from .utils.wrappers import attach_message_to_exception
17+
from os import PathLike
1718

1819

1920
_AZURE_NAMESPACE = '__app__'
2021

2122
_submodule_dirs = []
2223

2324

24-
def register_function_dir(path: os.PathLike):
25+
def register_function_dir(path: os.PathLike) -> None:
2526
_submodule_dirs.append(os.fspath(path))
2627

2728

28-
def install():
29+
def install() -> None:
2930
if _AZURE_NAMESPACE not in sys.modules:
3031
# Create and register the __app__ namespace package.
3132
ns_spec = importlib.machinery.ModuleSpec(_AZURE_NAMESPACE, None)
@@ -34,7 +35,7 @@ def install():
3435
sys.modules[_AZURE_NAMESPACE] = ns_pkg
3536

3637

37-
def uninstall():
38+
def uninstall() -> None:
3839
pass
3940

4041

azure_functions_worker/logging.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,23 +50,23 @@ def setup(log_level, log_destination):
5050
error_logger.setLevel(getattr(logging, log_level))
5151

5252

53-
def disable_console_logging():
53+
def disable_console_logging() -> None:
5454
if logger and handler:
5555
logger.removeHandler(handler)
5656

5757
if error_logger and error_handler:
5858
error_logger.removeHandler(error_handler)
5959

6060

61-
def enable_console_logging():
61+
def enable_console_logging() -> None:
6262
if logger and handler:
6363
logger.addHandler(handler)
6464

6565
if error_logger and error_handler:
6666
error_logger.addHandler(error_handler)
6767

6868

69-
def is_system_log_category(ctg: str):
69+
def is_system_log_category(ctg: str) -> bool:
7070
return any(
7171
[ctg.lower().startswith(c) for c in (
7272
'azure_functions_worker',

azure_functions_worker/testutils.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515
import json
1616
import logging
1717
import os
18-
import queue
1918
import pathlib
2019
import platform
20+
import queue
21+
import re
2122
import shutil
2223
import socket
2324
import subprocess
@@ -27,17 +28,15 @@
2728
import typing
2829
import unittest
2930
import uuid
30-
import re
3131

3232
import grpc
3333
import requests
3434

3535
from azure_functions_worker._thirdparty import aio_compat
3636
from . import dispatcher
3737
from . import protos
38-
from .utils.common import is_envvar_true
3938
from .constants import PYAZURE_WEBHOST_DEBUG
40-
39+
from .utils.common import is_envvar_true
4140

4241
PROJECT_ROOT = pathlib.Path(__file__).parent.parent
4342
TESTS_ROOT = PROJECT_ROOT / 'tests'
@@ -410,10 +409,10 @@ async def communicate(self, message, *, wait_for):
410409
self._in_queue.put_nowait((message, wait_for))
411410
return await self._out_aqueue.get()
412411

413-
async def _start(self):
412+
async def start(self):
414413
self._server.start()
415414

416-
async def _close(self):
415+
async def close(self):
417416
self._in_queue.put_nowait((_MockWebHostServicer._STOP, None))
418417
self._server.stop(1)
419418

@@ -457,20 +456,19 @@ async def __aenter__(self):
457456
loop = aio_compat.get_running_loop()
458457
self._host = _MockWebHost(loop, self._scripts_dir)
459458

460-
await self._host._start()
459+
await self._host.start()
461460

462-
self._worker = await dispatcher.Dispatcher.connect(
463-
'127.0.0.1', self._host._port,
464-
self._host.worker_id, self._host.request_id,
465-
connect_timeout=5.0)
461+
self._worker = await dispatcher.Dispatcher.connect('127.0.0.1',
462+
self._host._port, self._host.worker_id,
463+
self._host.request_id, connect_timeout=5.0)
466464

467465
self._worker.load_bindings()
468466

469467
self._worker_task = loop.create_task(self._worker.dispatch_forever())
470468

471-
done, pending = await asyncio.wait(
472-
[self._host._connected_fut, self._worker_task],
473-
return_when=asyncio.FIRST_COMPLETED)
469+
done, pending = await asyncio.wait([self._host._connected_fut,
470+
self._worker_task],
471+
return_when=asyncio.FIRST_COMPLETED)
474472

475473
try:
476474
if self._worker_task in done:
@@ -480,7 +478,7 @@ async def __aenter__(self):
480478
raise RuntimeError('could not start a worker thread')
481479
except Exception:
482480
try:
483-
self._host._close()
481+
await self._host.close()
484482
self._worker.stop()
485483
finally:
486484
raise
@@ -498,7 +496,7 @@ async def __aexit__(self, *exc):
498496
self._worker_task = None
499497
self._worker = None
500498

501-
await self._host._close()
499+
await self._host.close()
502500
self._host = None
503501

504502

azure_functions_worker/utils/common.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
import os
44

55

6-
def is_true_like(setting: str):
6+
def is_true_like(setting: str) -> bool:
77
if setting is None:
88
return False
99

1010
return setting.lower().strip() in ['1', 'true', 't', 'yes', 'y']
1111

1212

13-
def is_envvar_true(env_key: str):
13+
def is_envvar_true(env_key: str) -> bool:
1414
if os.getenv(env_key) is None:
1515
return False
1616

azure_functions_worker/utils/tracing.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# Licensed under the MIT License.
33
from typing import List
44
import traceback
5+
from traceback import StackSummary
56

67

78
def extend_exception_message(exc: Exception, msg: str) -> Exception:

azure_functions_worker/utils/wrappers.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
# Licensed under the MIT License.
33
from .common import is_envvar_true
44
from .tracing import extend_exception_message
5+
from typing import Callable, Optional
56

67

7-
def enable_feature_by(flag: str, default=None):
8+
def enable_feature_by(flag: str, default: Optional[int]=None) -> Callable:
89
def decorate(func):
910
def call(*args, **kwargs):
1011
if is_envvar_true(flag):
@@ -14,7 +15,7 @@ def call(*args, **kwargs):
1415
return decorate
1516

1617

17-
def disable_feature_by(flag: str, default=None):
18+
def disable_feature_by(flag: str, default: None=None) -> Callable:
1819
def decorate(func):
1920
def call(*args, **kwargs):
2021
if not is_envvar_true(flag):
@@ -24,7 +25,7 @@ def call(*args, **kwargs):
2425
return decorate
2526

2627

27-
def attach_message_to_exception(expt_type: Exception, message: str):
28+
def attach_message_to_exception(expt_type: Exception, message: str) -> Callable:
2829
def decorate(func):
2930
def call(*args, **kwargs):
3031
try:

0 commit comments

Comments
 (0)