From d36fcc39622efd40cf86cdfcd49341dc3910e371 Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Sat, 26 Jun 2021 13:13:43 +1000 Subject: [PATCH 01/33] wip: rework clients to support async Removed proto packages, which can be autogenerated --- makefile | 4 +- nitric/api/__init__.py | 5 +- nitric/api/_base_client.py | 72 -------------- nitric/api/_utils.py | 17 ++++ nitric/api/event.py | 84 ---------------- nitric/api/events.py | 96 +++++++++++++++++++ nitric/api/kv.py | 53 +++++----- nitric/api/models.py | 52 ---------- nitric/api/queue.py | 141 --------------------------- nitric/api/queues.py | 144 ++++++++++++++++++++++++++++ nitric/api/storage.py | 43 +++++---- nitric/proto/__init__.py | 37 ------- nitric/proto/event/__init__.py | 18 ---- nitric/proto/event/v1/__init__.py | 18 ---- nitric/proto/faas/__init__.py | 18 ---- nitric/proto/faas/v1/__init__.py | 18 ---- nitric/proto/kv/__init__.py | 18 ---- nitric/proto/kv/v1/__init__.py | 18 ---- nitric/proto/queue/__init__.py | 18 ---- nitric/proto/queue/v1/__init__.py | 18 ---- nitric/proto/storage/__init__.py | 18 ---- nitric/proto/storage/v1/__init__.py | 18 ---- setup.py | 4 +- tools/fix_grpc_imports.py | 45 --------- 24 files changed, 311 insertions(+), 666 deletions(-) delete mode 100644 nitric/api/_base_client.py create mode 100644 nitric/api/_utils.py delete mode 100644 nitric/api/event.py create mode 100644 nitric/api/events.py delete mode 100644 nitric/api/models.py delete mode 100644 nitric/api/queue.py create mode 100644 nitric/api/queues.py delete mode 100644 nitric/proto/__init__.py delete mode 100644 nitric/proto/event/__init__.py delete mode 100644 nitric/proto/event/v1/__init__.py delete mode 100644 nitric/proto/faas/__init__.py delete mode 100644 nitric/proto/faas/v1/__init__.py delete mode 100644 nitric/proto/kv/__init__.py delete mode 100644 nitric/proto/kv/v1/__init__.py delete mode 100644 nitric/proto/queue/__init__.py delete mode 100644 nitric/proto/queue/v1/__init__.py delete mode 100644 nitric/proto/storage/__init__.py delete mode 100644 nitric/proto/storage/v1/__init__.py delete mode 100644 tools/fix_grpc_imports.py diff --git a/makefile b/makefile index 4440ded..ca15143 100644 --- a/makefile +++ b/makefile @@ -12,9 +12,7 @@ grpc-client: @echo Generating Proto Sources @echo $(OUTPUT) @mkdir -p $(OUTPUT) - @python3 -m grpc_tools.protoc -I $(CONTRACTS) --python_out=$(OUTPUT) --grpc_python_out=$(OUTPUT) ./contracts/proto/**/**/*.proto - @python3 ./tools/fix_grpc_imports.py - @find $(OUTPUT) -type d -exec touch {}/__init__.py \; + @python3 -m grpc_tools.protoc -I $(CONTRACTS) --python_betterproto_out=$(OUTPUT) ./contracts/proto/**/**/*.proto docs: @echo Generating SDK Documentation diff --git a/nitric/api/__init__.py b/nitric/api/__init__.py index 25e39a9..ad88325 100644 --- a/nitric/api/__init__.py +++ b/nitric/api/__init__.py @@ -17,11 +17,10 @@ # limitations under the License. # """Nitric API SDK.""" -from nitric.api.event import EventClient, TopicClient +from nitric.api.events import EventClient, TopicClient, Event, Topic from nitric.api.kv import KeyValueClient -from nitric.api.queue import QueueClient +from nitric.api.queues import QueueClient, Task, FailedTask from nitric.api.storage import StorageClient -from nitric.api.models import Event, Task, FailedTask, Topic __all__ = [ "EventClient", diff --git a/nitric/api/_base_client.py b/nitric/api/_base_client.py deleted file mode 100644 index a9b95e5..0000000 --- a/nitric/api/_base_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from abc import ABC -import grpc -from google.protobuf.struct_pb2 import Struct -from grpc._channel import _InactiveRpcError -from nitric.config import settings -from nitric.api.exception import ( - UnimplementedException, - AlreadyExistsException, - UnavailableException, -) - - -class BaseClient(ABC): - """Abstract base class for GRPC based Nitric client classes.""" - - _stub = None - - def __init__(self): - """Construct a base nitric gRPC client.""" - self._channel = grpc.insecure_channel(settings.SERVICE_BIND) - - def _get_method_function(self, method): - return getattr(self._stub, method) - - def _exec(self, method: str, request: object = None): - """ - Execute a gRPC request. - - :param method: gRPC method to execute. - :param request: payload for the request. - :return: gRPC reply class, based on method. - """ - if request is None: - request = Struct() - grpc_method = self._get_method_function(method) - try: - response = grpc_method(request) - except _InactiveRpcError as ire: - method_name = str(grpc_method._method, "utf-8").replace("/", "", 1) - ex_message = "Failed to call {method}\n\tCode: {code}\n\tDetails: {details}".format( - method=method_name, code=ire.code(), details=ire.details() - ) - - # handle specific status codes - if ire.code() == grpc.StatusCode.UNIMPLEMENTED: - raise UnimplementedException(ex_message) from None - elif ire.code() == grpc.StatusCode.ALREADY_EXISTS: - raise AlreadyExistsException(ex_message) from None - elif ire.code() == grpc.StatusCode.UNAVAILABLE: - raise UnavailableException(ex_message) from None - - raise Exception(ex_message) from None - - return response diff --git a/nitric/api/_utils.py b/nitric/api/_utils.py new file mode 100644 index 0000000..abd0380 --- /dev/null +++ b/nitric/api/_utils.py @@ -0,0 +1,17 @@ +import re +from nitric.config import settings +from urllib.parse import urlparse +from grpclib.client import Channel + + +def format_url(url: str): + """Add the default http scheme prefix to urls without one.""" + if not re.match("^((?:http|ftp|https):)?//", url.lower()): + return "http://{}".format(url) + return url + + +def new_default_channel(): + """Create new gRPC channel from settings.""" + channel_url = urlparse(format_url(settings.SERVICE_BIND)) + return Channel(host=channel_url.hostname, port=channel_url.port) diff --git a/nitric/api/event.py b/nitric/api/event.py deleted file mode 100644 index 144a6e8..0000000 --- a/nitric/api/event.py +++ /dev/null @@ -1,84 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from typing import List - -from nitric.proto import event as event_model, event -from nitric.proto import event_service -from nitric.proto.event.v1.event_pb2 import NitricEvent -from nitric.api._base_client import BaseClient -from google.protobuf.struct_pb2 import Struct - -from nitric.api.models import Topic - - -class EventClient(BaseClient): - """ - Nitric generic publish/subscribe event client. - - This client insulates application code from stack specific event operations or SDKs. - """ - - def __init__(self): - """Construct a Nitric Event Client.""" - super(self.__class__, self).__init__() - self._stub = event_service.EventStub(self._channel) - - def publish( - self, - topic_name: str, - payload: dict = None, - payload_type: str = "", - event_id: str = None, - ) -> str: - """ - Publish an event/message to a topic, which can be subscribed to by other services. - - :param topic_name: the name of the topic to publish to - :param payload: content of the message to send - :param payload_type: fully qualified name of the event payload type, e.g. io.nitric.example.customer.created - :param event_id: a unique id, used to ensure idempotent processing of events. Defaults to a version 4 UUID. - :return: the request id on successful publish - """ - if payload is None: - payload = {} - payload_struct = Struct() - payload_struct.update(payload) - nitric_event = NitricEvent(id=event_id, payload_type=payload_type, payload=payload_struct) - request = event_model.EventPublishRequest(topic=topic_name, event=nitric_event) - self._exec("Publish", request) - return event_id - - -class TopicClient(BaseClient): - """ - Nitric generic event topic client. - - This client insulates application code from stack specific topic operations or SDKs. - """ - - def __init__(self): - """Construct a Nitric Topic Client.""" - super(self.__class__, self).__init__() - self._stub = event_service.TopicStub(self._channel) - - def get_topics(self) -> List[Topic]: - """Get a list of topics available for publishing or subscription.""" - response: event.TopicListResponse = self._exec("List") - topics = [Topic(name=topic.name) for topic in response.topics] - return topics diff --git a/nitric/api/events.py b/nitric/api/events.py new file mode 100644 index 0000000..c817a5d --- /dev/null +++ b/nitric/api/events.py @@ -0,0 +1,96 @@ +# +# Copyright (c) 2021 Nitric Technologies Pty Ltd. +# +# This file is part of Nitric Python 3 SDK. +# See https://github.com/nitrictech/python-sdk for further info. +# +# Licensed 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. +# +from typing import List, Union +from nitric.api._utils import new_default_channel +from nitric.proto.nitric.event.v1 import EventStub, NitricEvent, TopicStub +from betterproto.lib.google.protobuf import Struct +from dataclasses import dataclass, field + + +@dataclass(frozen=True, order=True) +class Topic(object): + """Represents event topic metadata.""" + + name: str + + +@dataclass(frozen=True, order=True) +class Event(object): + """Represents a NitricEvent.""" + + payload: dict = field(default_factory=dict) + id: str = "" + payload_type: str = "" + + +def _event_to_wire(event: Event) -> NitricEvent: + return NitricEvent( + id=event.id, + payload=Struct().from_dict(event.payload), + payload_type=event.payload_type, + ) + + +class EventClient(object): + """ + Nitric generic publish/subscribe event client. + + This client insulates application code from stack specific event operations or SDKs. + """ + + def __init__(self, topic: str): + """Construct a Nitric Event Client.""" + self.topic = topic + self._stub = EventStub(channel=new_default_channel()) + + async def publish( + self, + event: Union[Event, dict] = None, + ) -> Event: + """ + Publish an event/message to a topic, which can be subscribed to by other services. + + :param event: the event to publish + :return: the published event, with the id added if one was auto-generated + """ + if event is None: + event = Event() + + if isinstance(event, dict): + event = Event(**event) + + response = await self._stub.publish(topic=self.topic, event=_event_to_wire(event)) + return Event(**{**event.__dict__.copy(), **{"id": response.id}}) + + +class TopicClient(object): + """ + Nitric generic event topic client. + + This client insulates application code from stack specific topic operations or SDKs. + """ + + def __init__(self): + """Construct a Nitric Topic Client.""" + self._stub = TopicStub(channel=new_default_channel()) + + async def get_topics(self) -> List[Topic]: + """Get a list of topics available for publishing or subscription.""" + response = await self._stub.list() + return [Topic(name=topic.name) for topic in response.topics] diff --git a/nitric/api/kv.py b/nitric/api/kv.py index 27eb688..cf5b2c8 100644 --- a/nitric/api/kv.py +++ b/nitric/api/kv.py @@ -16,41 +16,36 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from nitric.proto import key_value -from nitric.proto import key_value_service -from nitric.api._base_client import BaseClient -from google.protobuf.struct_pb2 import Struct -from google.protobuf.json_format import MessageToDict -from nitric.proto.kv.v1.kv_pb2 import KeyValueGetResponse +from nitric.api._utils import new_default_channel +from nitric.proto.nitric.kv.v1 import KeyValueStub +from betterproto.lib.google.protobuf import Struct -class KeyValueClient(BaseClient): +class KeyValueClient(object): """ Nitric generic document store/db client. This client insulates application code from stack specific document CRUD operations or SDKs. """ - def __init__(self): - """Construct a new DocumentClient.""" - super(self.__class__, self).__init__() - self._stub = key_value_service.KeyValueStub(self._channel) - - def put(self, collection: str, key: str, value: dict): - """Create a new document with the specified key in the specified collection.""" - value_struct = Struct() - value_struct.update(value) - request = key_value.KeyValuePutRequest(collection=collection, key=key, value=value_struct) - return self._exec("Put", request) - - def get(self, collection: str, key: str) -> dict: - """Retrieve a document from the specified collection by its key.""" - request = key_value.KeyValueGetRequest(collection=collection, key=key) - reply: KeyValueGetResponse = self._exec("Get", request) - document = MessageToDict(reply)["value"] - return document - - def delete(self, collection: str, key: str): + def __init__(self, collection: str): + """ + Construct a new DocumentClient. + + :param collection: name of the key/value collection + """ + self.collection = collection + self._stub = KeyValueStub(channel=new_default_channel()) + + async def put(self, key: str, value: dict): + """Create a new document with the specified key.""" + await self._stub.put(collection=self.collection, key=key, value=Struct().from_dict(value)) + + async def get(self, key: str) -> dict: + """Retrieve a document from the specified key.""" + response = await self._stub.get(collection=self.collection, key=key) + return response.value.to_dict() + + async def delete(self, key: str): """Delete the specified document from the collection.""" - request = key_value.KeyValueDeleteRequest(collection=collection, key=key) - return self._exec("Delete", request) + await self._stub.delete(collection=self.collection, key=key) diff --git a/nitric/api/models.py b/nitric/api/models.py deleted file mode 100644 index d1bf173..0000000 --- a/nitric/api/models.py +++ /dev/null @@ -1,52 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from dataclasses import dataclass, field - - -@dataclass(frozen=True, order=True) -class Topic(object): - """Represents event topic metadata.""" - - name: str - - -@dataclass(frozen=True, order=True) -class Event(object): - """Represents a NitricEvent.""" - - event_id: str - payload_type: str - payload: dict - - -@dataclass(frozen=True, order=True) -class Task(object): - """Represents a NitricTask.""" - - task_id: str - payload_type: str - payload: dict - lease_id: str = field(default=None) - - -@dataclass(frozen=True, order=True) -class FailedTask(Task): - """Represents a failed queue publish for an event.""" - - message: str = field(default="") diff --git a/nitric/api/queue.py b/nitric/api/queue.py deleted file mode 100644 index d69b42b..0000000 --- a/nitric/api/queue.py +++ /dev/null @@ -1,141 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from typing import List - -from google.protobuf.json_format import MessageToDict -from google.protobuf.struct_pb2 import Struct - -from nitric.api._base_client import BaseClient -from nitric.api.models import FailedTask, Task -from nitric.proto import queue -from nitric.proto import queue_service - - -class PushResponse(object): - """Represents the result of a Queue Push.""" - - def __init__(self, failed_tasks: List[FailedTask]): - """Construct a Push Response.""" - self.failed_tasks = failed_tasks - - -class QueueClient(BaseClient): - """ - Nitric generic publish/subscribe tasking client. - - This client insulates application code from stack specific task/topic operations or SDKs. - """ - - def __init__(self): - """Construct a Nitric Queue Client.""" - super(self.__class__, self).__init__() - self._stub = queue_service.QueueStub(self._channel) - - def _task_to_wire(self, task: Task) -> queue.NitricTask: - """ - Convert a Nitric Task to a Nitric Queue Task. - - :param task: to convert - :return: converted task - """ - payload_struct = Struct() - payload_struct.update(task.payload) - - return queue.NitricTask( - id=task.task_id, - payload_type=task.payload_type, - payload=payload_struct, - ) - - def _wire_to_task(self, task: queue.NitricTask) -> Task: - """ - Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK). - - :param task: to convert - :return: converted task - """ - return Task( - task_id=task.id, - payload_type=task.payload_type, - payload=MessageToDict(task.payload), - lease_id=task.lease_id, - ) - - def _wire_to_failed_task(self, failed_task: queue.FailedTask) -> FailedTask: - """ - Convert a queue task that failed to push into a Failed Task object. - - :param failed_task: the failed task - :return: the Failed Task with failure message - """ - task = self._wire_to_task(failed_task.task) - - return FailedTask( - task_id=task.task_id, - payload_type=task.payload_type, - payload=task.payload, - lease_id=task.lease_id, - message=failed_task.message, - ) - - def send_batch(self, queue_name: str, tasks: List[Task] = None) -> PushResponse: - """ - Push a collection of tasks to a queue, which can be retrieved by other services. - - :param queue_name: the name of the queue to publish to - :param tasks: The tasks to push to the queue - :return: PushResponse containing a list containing details of any messages that failed to publish. - """ - if tasks is None: - tasks = [] - wire_tasks = map(self._task_to_wire, tasks) - - request = queue.QueueSendBatchRequest(queue=queue_name, tasks=wire_tasks) - - response: queue.QueueSendBatchResponse = self._exec("SendBatch", request) - - failed_tasks = map(self._wire_to_failed_task, response.failedMessages) - - return PushResponse(failed_tasks=list(failed_tasks)) - - def receive(self, queue_name: str, depth: int = None) -> List[Task]: - """ - Pop 1 or more items from the specified queue up to the depth limit. - - Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on. - Once complete or failed they must be acknowledged using the request specific leaseId. - - If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be - returned to the queue for reprocessing. - - :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific - identifier. - :param depth: The maximum number of queue items to return. Default: 1, Min: 1. - :return: Queue items popped from the specified queue. - """ - # Set the default and minimum depth to 1. - if depth is None or depth < 1: - depth = 1 - - request = queue.QueueReceiveRequest(queue=queue_name, depth=depth) - - response: queue.QueueReceiveResponse = self._exec("Receive", request) - - # Map the response protobuf response items to Python SDK Nitric Queue Items - return [self._wire_to_task(item) for item in response.items] diff --git a/nitric/api/queues.py b/nitric/api/queues.py new file mode 100644 index 0000000..eca5e3f --- /dev/null +++ b/nitric/api/queues.py @@ -0,0 +1,144 @@ +# +# Copyright (c) 2021 Nitric Technologies Pty Ltd. +# +# This file is part of Nitric Python 3 SDK. +# See https://github.com/nitrictech/python-sdk for further info. +# +# Licensed 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. +# +from typing import List, Union + +from betterproto.lib.google.protobuf import Struct + +from nitric.api._utils import new_default_channel +from nitric.proto.nitric.queue.v1 import QueueStub, NitricTask, FailedTask as WireFailedTask +from dataclasses import dataclass, field + + +@dataclass(frozen=True, order=True) +class Task(object): + """Represents a NitricTask.""" + + id: str = field(default=None) + payload_type: str = field(default=None) + payload: dict = field(default_factory=dict) + lease_id: str = field(default=None) + + +@dataclass(frozen=True, order=True) +class FailedTask(Task): + """Represents a failed queue publish for an event.""" + + message: str = field(default="") + + +def _task_to_wire(task: Task) -> NitricTask: + """ + Convert a Nitric Task to a Nitric Queue Task. + + :param task: to convert + :return: converted task + """ + return NitricTask( + id=task.id, + payload_type=task.payload_type, + payload=Struct().from_dict(task.payload), + ) + + +def _wire_to_task(task: NitricTask) -> Task: + """ + Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK). + + :param task: to convert + :return: converted task + """ + return Task( + id=task.id, + payload_type=task.payload_type, + payload=task.payload.to_dict(), + lease_id=task.lease_id, + ) + + +def _wire_to_failed_task(failed_task: WireFailedTask) -> FailedTask: + """ + Convert a queue task that failed to push into a Failed Task object. + + :param failed_task: the failed task + :return: the Failed Task with failure message + """ + task = _wire_to_task(failed_task.task) + + return FailedTask( + id=task.id, + payload_type=task.payload_type, + payload=task.payload, + lease_id=task.lease_id, + message=failed_task.message, + ) + + +class QueueClient(object): + """ + Nitric generic publish/subscribe tasking client. + + This client insulates application code from stack specific task/topic operations or SDKs. + """ + + def __init__(self, queue: str): + """Construct a Nitric Queue Client.""" + self.queue = queue + self._stub = QueueStub(channel=new_default_channel()) + + async def send_batch( + self, tasks: List[Union[Task, dict]] = None, raise_on_failure: bool = True + ) -> List[FailedTask]: + """ + Push a collection of tasks to a queue, which can be retrieved by other services. + + :param tasks: The tasks to push to the queue + :param raise_on_failure: Whether to raise an exception when one or more tasks fails to send + :return: PushResponse containing a list containing details of any messages that failed to publish. + """ + if tasks is None: + tasks = [] + + wire_tasks = [_task_to_wire(Task(**task) if isinstance(task, dict) else task) for task in tasks] + + response = await self._stub.send_batch(queue=self.queue, tasks=wire_tasks) + + return [_wire_to_failed_task(failed_task) for failed_task in response.failed_tasks] + + def receive(self, depth: int = None) -> List[Task]: + """ + Pop 1 or more items from the specified queue up to the depth limit. + + Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on. + Once complete or failed they must be acknowledged using the request specific leaseId. + + If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be + returned to the queue for reprocessing. + + identifier. + :param depth: The maximum number of queue items to return. Default: 1, Min: 1. + :return: Queue items popped from the specified queue. + """ + # Set the default and minimum depth to 1. + if depth is None or depth < 1: + depth = 1 + + response = await self._stub.receive(queue=self.queue, depth=depth) + + # Map the response protobuf response items to Python SDK Nitric Queue Items + return [_wire_to_task(item) for item in response.items] diff --git a/nitric/api/storage.py b/nitric/api/storage.py index 15ac909..f530730 100644 --- a/nitric/api/storage.py +++ b/nitric/api/storage.py @@ -16,44 +16,49 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from nitric.proto import storage -from nitric.proto import storage_service -from nitric.api._base_client import BaseClient +from nitric.api._utils import new_default_channel +from nitric.proto.nitric.storage.v1 import StorageStub -class StorageClient(BaseClient): +class StorageClient(object): """ Nitric generic blob storage client. This client insulates application code from stack specific blob store operations or SDKs. """ - def __init__(self): - """Construct a new StorageClient.""" - super(self.__class__, self).__init__() - self._stub = storage_service.StorageStub(self._channel) + def __init__(self, bucket: str): + """ + Construct a Nitric Event Client. + + :param bucket: name of the bucket to perform operations on. + """ + self.bucket = bucket + self._stub = StorageStub(channel=new_default_channel()) - def write(self, bucket_name: str, key: str, body: bytes): + async def write(self, key: str, body: bytes): """ - Store a file. + Write a file to the bucket under the given key. - :param bucket_name: name of the bucket to store the data in. :param key: key within the bucket, where the file should be stored. :param body: data to be stored. - :return: storage result. """ - request = storage.StorageWriteRequest(bucket_name=bucket_name, key=key, body=body) - response = self._exec("Write", request) - return response + await self._stub.write(bucket_name=self.bucket, key=key, body=body) - def read(self, bucket_name: str, key: str) -> bytes: + async def read(self, key: str) -> bytes: """ Retrieve an existing file. - :param bucket_name: name of the bucket where the file was stored. :param key: key for the file to retrieve. :return: the file as bytes. """ - request = storage.StorageReadRequest(bucket_name=bucket_name, key=key) - response = self._exec("Read", request) + response = await self._stub.read(bucket_name=self.bucket, key=key) return response.body + + async def delete(self, key: str): + """ + Delete an existing file. + + :param key: key of the file to delete. + """ + await self._stub.delete(bucket_name=self.bucket, key=key) diff --git a/nitric/proto/__init__.py b/nitric/proto/__init__.py deleted file mode 100644 index 20df057..0000000 --- a/nitric/proto/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from nitric.proto.event.v1 import event_pb2 as event -from nitric.proto.event.v1 import event_pb2_grpc as event_service -from nitric.proto.storage.v1 import storage_pb2 as storage -from nitric.proto.storage.v1 import storage_pb2_grpc as storage_service -from nitric.proto.kv.v1 import kv_pb2 as key_value -from nitric.proto.kv.v1 import kv_pb2_grpc as key_value_service -from nitric.proto.queue.v1 import queue_pb2 as queue -from nitric.proto.queue.v1 import queue_pb2_grpc as queue_service - -__all__ = [ - "event", - "event_service", - "storage", - "storage_service", - "key_value", - "key_value_service", - "queue", - "queue_service", -] diff --git a/nitric/proto/event/__init__.py b/nitric/proto/event/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/event/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/event/v1/__init__.py b/nitric/proto/event/v1/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/event/v1/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/faas/__init__.py b/nitric/proto/faas/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/faas/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/faas/v1/__init__.py b/nitric/proto/faas/v1/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/faas/v1/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/kv/__init__.py b/nitric/proto/kv/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/kv/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/kv/v1/__init__.py b/nitric/proto/kv/v1/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/kv/v1/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/queue/__init__.py b/nitric/proto/queue/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/queue/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/queue/v1/__init__.py b/nitric/proto/queue/v1/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/queue/v1/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/storage/__init__.py b/nitric/proto/storage/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/storage/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/nitric/proto/storage/v1/__init__.py b/nitric/proto/storage/v1/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/nitric/proto/storage/v1/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/setup.py b/setup.py index 4ba4e62..b6f10eb 100644 --- a/setup.py +++ b/setup.py @@ -44,12 +44,14 @@ def get_current_version_tag(): install_requires=[ "flask==1.1.2", "waitress==1.4.4", - "grpcio==1.33.2", "six==1.15.0", "protobuf==3.13.0", + "betterproto==1.2.5", ], extras_require={ "dev": [ + "betterproto[compiler]==1.2.5", + "grpcio==1.33.2", "grpcio-tools==1.33.2", "tox==3.20.1", "twine==3.2.0", diff --git a/tools/fix_grpc_imports.py b/tools/fix_grpc_imports.py deleted file mode 100644 index 9cfde56..0000000 --- a/tools/fix_grpc_imports.py +++ /dev/null @@ -1,45 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -import glob -import fileinput -import os -import re - -AUTO_GEN_PATH = "../nitric/proto/**/*_pb2*.py" -REPLACE = re.compile(r"^from (?=.*.v1 import)") -WITH = "from nitric.proto." - - -def main(): - """Fix the import statements generated by protoc for python.""" - tools_dir = os.path.dirname(__file__) - gen_dir = os.path.join(tools_dir, AUTO_GEN_PATH) - grcp_paths = glob.glob(gen_dir, recursive=True) - - for path in grcp_paths: - print("fixing imports in {path}".format(path=path)) - with fileinput.FileInput(path, inplace=True) as file: - for line in file: - if not line.startswith(WITH): - line = REPLACE.sub(WITH, line) - print(line, end="") - - -if __name__ == "__main__": - main() From 3c4f0e218d290e098b2820c9860778efabde6ace Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Sat, 26 Jun 2021 13:16:10 +1000 Subject: [PATCH 02/33] chore: ignore autogenerated packages --- .gitignore | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 979cd05..af44a19 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ # Protoc Output Files -*_pb2.py -*_pb2_grpc.py +nitric/proto/ .idea/ From 5efe684857ca757767af3b1a333a640156e375cf Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Mon, 28 Jun 2021 17:19:54 +1000 Subject: [PATCH 03/33] wip: fix Struct to/from dict conversion --- nitric/api/__init__.py | 3 +- nitric/api/_utils.py | 28 ++++++ nitric/api/events.py | 51 +++++------ nitric/api/kv.py | 5 +- nitric/api/queues.py | 11 +-- setup.py | 7 +- tests/api/test_event_client.py | 115 +++++++++++++++++-------- tests/api/test_grpc_error.py | 78 ----------------- tests/api/test_key_value_client.py | 92 -------------------- tests/api/test_models.py | 23 ----- tests/api/test_queue_client.py | 105 ---------------------- tests/api/test_storage_client.py | 65 -------------- tests/api/test_topic_client.py | 45 ---------- tests/faas/__init__.py | 18 ---- tests/faas/test_start.py | 134 ----------------------------- tests/test__utils.py | 20 +++++ tox.ini | 2 +- 17 files changed, 160 insertions(+), 642 deletions(-) delete mode 100644 tests/api/test_grpc_error.py delete mode 100644 tests/api/test_key_value_client.py delete mode 100644 tests/api/test_models.py delete mode 100644 tests/api/test_queue_client.py delete mode 100644 tests/api/test_storage_client.py delete mode 100644 tests/api/test_topic_client.py delete mode 100644 tests/faas/__init__.py delete mode 100644 tests/faas/test_start.py create mode 100644 tests/test__utils.py diff --git a/nitric/api/__init__.py b/nitric/api/__init__.py index ad88325..8200659 100644 --- a/nitric/api/__init__.py +++ b/nitric/api/__init__.py @@ -17,14 +17,13 @@ # limitations under the License. # """Nitric API SDK.""" -from nitric.api.events import EventClient, TopicClient, Event, Topic +from nitric.api.events import EventClient, Event, Topic from nitric.api.kv import KeyValueClient from nitric.api.queues import QueueClient, Task, FailedTask from nitric.api.storage import StorageClient __all__ = [ "EventClient", - "TopicClient", "KeyValueClient", "QueueClient", "StorageClient", diff --git a/nitric/api/_utils.py b/nitric/api/_utils.py index abd0380..40733a4 100644 --- a/nitric/api/_utils.py +++ b/nitric/api/_utils.py @@ -1,4 +1,7 @@ import re +from betterproto.lib.google.protobuf import Struct +from google.protobuf.json_format import MessageToDict +from google.protobuf.struct_pb2 import Struct as WorkingStruct from nitric.config import settings from urllib.parse import urlparse from grpclib.client import Channel @@ -15,3 +18,28 @@ def new_default_channel(): """Create new gRPC channel from settings.""" channel_url = urlparse(format_url(settings.SERVICE_BIND)) return Channel(host=channel_url.hostname, port=channel_url.port) + + +# These functions convert to/from python dict <-> betterproto.lib.google.protobuf.Struct +# the existing Struct().from_dict() method doesn't work for Structs, +# it relies on Message meta information, that isn't available for dynamic structs. +def _dict_from_struct(struct: Struct) -> dict: + """Construct a dict from a Struct.""" + # Convert the bytes representation of the betterproto Struct into a protobuf Struct + # in order to use the MessageToDict function to safely create a dict. + gpb_struct = WorkingStruct() + gpb_struct.ParseFromString(bytes(struct)) + return MessageToDict(gpb_struct) + + +def _struct_from_dict(dictionary: dict) -> Struct: + """Construct a Struct from a dict.""" + # Convert to dict into a Struct class from the protobuf library + # since protobuf Structs are able to be created from a dict + # unlike the Struct class from betterproto. + gpb_struct = WorkingStruct() + gpb_struct.update(dictionary) + # Convert the bytes representation of the protobuf Struct into the betterproto Struct + # so that the returned Struct is compatible with other betterproto generated classes + struct = Struct().parse(gpb_struct.SerializeToString()) + return struct diff --git a/nitric/api/events.py b/nitric/api/events.py index c817a5d..a228b5e 100644 --- a/nitric/api/events.py +++ b/nitric/api/events.py @@ -17,19 +17,11 @@ # limitations under the License. # from typing import List, Union -from nitric.api._utils import new_default_channel +from nitric.api._utils import new_default_channel, _struct_from_dict from nitric.proto.nitric.event.v1 import EventStub, NitricEvent, TopicStub -from betterproto.lib.google.protobuf import Struct from dataclasses import dataclass, field -@dataclass(frozen=True, order=True) -class Topic(object): - """Represents event topic metadata.""" - - name: str - - @dataclass(frozen=True, order=True) class Event(object): """Represents a NitricEvent.""" @@ -42,22 +34,17 @@ class Event(object): def _event_to_wire(event: Event) -> NitricEvent: return NitricEvent( id=event.id, - payload=Struct().from_dict(event.payload), + payload=_struct_from_dict(event.payload), payload_type=event.payload_type, ) -class EventClient(object): - """ - Nitric generic publish/subscribe event client. - - This client insulates application code from stack specific event operations or SDKs. - """ +@dataclass(frozen=True, order=True) +class Topic(object): + """Represents event topic metadata.""" - def __init__(self, topic: str): - """Construct a Nitric Event Client.""" - self.topic = topic - self._stub = EventStub(channel=new_default_channel()) + _stub: EventStub + name: str async def publish( self, @@ -73,24 +60,30 @@ async def publish( event = Event() if isinstance(event, dict): + # TODO: handle events that are just a payload event = Event(**event) - response = await self._stub.publish(topic=self.topic, event=_event_to_wire(event)) + response = await self._stub.publish(topic=self.name, event=_event_to_wire(event)) return Event(**{**event.__dict__.copy(), **{"id": response.id}}) -class TopicClient(object): +class EventClient(object): """ - Nitric generic event topic client. + Nitric generic publish/subscribe event client. - This client insulates application code from stack specific topic operations or SDKs. + This client insulates application code from stack specific event operations or SDKs. """ def __init__(self): - """Construct a Nitric Topic Client.""" - self._stub = TopicStub(channel=new_default_channel()) + """Construct a Nitric Event Client.""" + channel = new_default_channel() + self._stub = EventStub(channel=channel) + self._topic_stub = TopicStub(channel=channel) - async def get_topics(self) -> List[Topic]: + async def topics(self) -> List[Topic]: """Get a list of topics available for publishing or subscription.""" - response = await self._stub.list() - return [Topic(name=topic.name) for topic in response.topics] + response = await self._topic_stub.list() + return [self.topic(topic.name) for topic in response.topics] + + def topic(self, topic: str) -> Topic: + return Topic(_stub=self._stub, name=topic) diff --git a/nitric/api/kv.py b/nitric/api/kv.py index cf5b2c8..0a48e8f 100644 --- a/nitric/api/kv.py +++ b/nitric/api/kv.py @@ -16,9 +16,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from nitric.api._utils import new_default_channel +from nitric.api._utils import new_default_channel, _struct_from_dict from nitric.proto.nitric.kv.v1 import KeyValueStub -from betterproto.lib.google.protobuf import Struct class KeyValueClient(object): @@ -39,7 +38,7 @@ def __init__(self, collection: str): async def put(self, key: str, value: dict): """Create a new document with the specified key.""" - await self._stub.put(collection=self.collection, key=key, value=Struct().from_dict(value)) + await self._stub.put(collection=self.collection, key=key, value=_struct_from_dict(value)) async def get(self, key: str) -> dict: """Retrieve a document from the specified key.""" diff --git a/nitric/api/queues.py b/nitric/api/queues.py index eca5e3f..f0d689e 100644 --- a/nitric/api/queues.py +++ b/nitric/api/queues.py @@ -17,10 +17,7 @@ # limitations under the License. # from typing import List, Union - -from betterproto.lib.google.protobuf import Struct - -from nitric.api._utils import new_default_channel +from nitric.api._utils import new_default_channel, _struct_from_dict from nitric.proto.nitric.queue.v1 import QueueStub, NitricTask, FailedTask as WireFailedTask from dataclasses import dataclass, field @@ -52,7 +49,7 @@ def _task_to_wire(task: Task) -> NitricTask: return NitricTask( id=task.id, payload_type=task.payload_type, - payload=Struct().from_dict(task.payload), + payload=_struct_from_dict(task.payload), ) @@ -120,7 +117,7 @@ async def send_batch( return [_wire_to_failed_task(failed_task) for failed_task in response.failed_tasks] - def receive(self, depth: int = None) -> List[Task]: + async def receive(self, depth: int = None) -> List[Task]: """ Pop 1 or more items from the specified queue up to the depth limit. @@ -141,4 +138,4 @@ def receive(self, depth: int = None) -> List[Task]: response = await self._stub.receive(queue=self.queue, depth=depth) # Map the response protobuf response items to Python SDK Nitric Queue Items - return [_wire_to_task(item) for item in response.items] + return [_wire_to_task(task) for task in response.tasks] diff --git a/setup.py b/setup.py index b6f10eb..61207ac 100644 --- a/setup.py +++ b/setup.py @@ -46,11 +46,12 @@ def get_current_version_tag(): "waitress==1.4.4", "six==1.15.0", "protobuf==3.13.0", - "betterproto==1.2.5", + "betterproto==2.0.0b3", + "asyncio", ], extras_require={ "dev": [ - "betterproto[compiler]==1.2.5", + "betterproto[compiler]==2.0.0b3", "grpcio==1.33.2", "grpcio-tools==1.33.2", "tox==3.20.1", @@ -70,5 +71,5 @@ def get_current_version_tag(): "pdoc3==0.9.2", ] }, - python_requires=">=3.7", + python_requires=">=3.8", ) diff --git a/tests/api/test_event_client.py b/tests/api/test_event_client.py index dc3fb4c..7278671 100644 --- a/tests/api/test_event_client.py +++ b/tests/api/test_event_client.py @@ -16,54 +16,95 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from unittest.mock import patch, Mock -from nitric.api import EventClient -from google.protobuf.struct_pb2 import Struct -from uuid import UUID +from unittest import IsolatedAsyncioTestCase +from unittest.mock import patch, AsyncMock +from betterproto.lib.google.protobuf import Struct -def test_publish(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_publish = Mock() - mock_publish.return_value.topics = [] +from nitric.api import EventClient, Event +from nitric.api._utils import _struct_from_dict - payload = {"content": "of event"} - with patch("nitric.api.EventClient._get_method_function", mock_grpc_method_getter): - client = EventClient() - request_id = client.publish("topic_name", payload, "payload.type", event_id="abc-123") +class Object(object): + pass - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Publish") - payload_struct = Struct() - payload_struct.update(payload) - # Ensure the publish method is called with the expected input - mock_publish.assert_called_once() - assert mock_publish.call_args[0][0].topic == "topic_name" - assert mock_publish.call_args[0][0].event.id == "abc-123" - assert mock_publish.call_args[0][0].event.payload_type == "payload.type" - assert mock_publish.call_args[0][0].event.payload["content"] == "of event" +class EventClientTest(IsolatedAsyncioTestCase): + async def test_publish(self): + mock_publish = AsyncMock() + mock_response = Object() + mock_response.id = "test-id" + mock_publish.return_value = mock_response + payload = {"content": "of event"} -def test_empty_payload(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_publish = Mock() - mock_publish.return_value.topics = [] + with patch("nitric.proto.nitric.event.v1.EventStub.publish", mock_publish): + topic = EventClient().topic("test-topic") + event = await topic.publish(Event(payload=payload)) - with patch("nitric.api.EventClient._get_method_function", mock_grpc_method_getter): - client = EventClient() - client.publish(topic_name="topic_name", payload_type="payload.type") + # Check the returned ID was set on the event + assert event.id == "test-id" - # Ensure the gRPC method is called, with an empty Struct as the payload. - mock_publish.assert_called_once() - assert mock_publish.call_args[0][0].event.payload == Struct() + # Check expected values were passed to Stub + mock_publish.assert_called_once() + assert mock_publish.call_args.kwargs["topic"] == "test-topic" + assert mock_publish.call_args.kwargs["event"].id == "" + assert mock_publish.call_args.kwargs["event"].payload_type == "" + assert len(mock_publish.call_args.kwargs["event"].payload.fields) == 1 + assert mock_publish.call_args.kwargs["event"].payload == _struct_from_dict(payload) + async def test_publish_dict(self): + mock_publish = AsyncMock() + mock_response = Object() + mock_response.id = "123" + mock_publish.return_value = mock_response -def test_grpc_methods(): - client = EventClient() - assert client._get_method_function("Publish")._method == b"/nitric.event.v1.Event/Publish" + payload = {"content": "of event"} + with patch("nitric.proto.nitric.event.v1.EventStub.publish", mock_publish): + topic = EventClient().topic("test-topic") + await topic.publish({"id": "123", "payload": payload}) -def test_create_client(): - client = EventClient() + # Check expected values were passed to Stub + mock_publish.assert_called_once() + assert mock_publish.call_args.kwargs["topic"] == "test-topic" + assert mock_publish.call_args.kwargs["event"].id == "123" + assert mock_publish.call_args.kwargs["event"].payload_type == "" + assert len(mock_publish.call_args.kwargs["event"].payload.fields) == 1 + assert mock_publish.call_args.kwargs["event"].payload == _struct_from_dict(payload) + + async def test_publish_invalid_type(self): + mock_publish = AsyncMock() + mock_response = Object() + mock_response.id = "test-id" + mock_publish.return_value = mock_response + + payload = {"content": "of event"} + + with patch("nitric.proto.nitric.event.v1.EventStub.publish", mock_publish): + topic = EventClient().topic("test-topic") + try: + await topic.publish((1, 2, 3)) + assert False + except AttributeError: + # Exception raised if expected duck type attributes are missing + assert True + + async def test_publish_none(self): + mock_publish = AsyncMock() + mock_response = Object() + mock_response.id = "123" + mock_publish.return_value = mock_response + + payload = {"content": "of event"} + + with patch("nitric.proto.nitric.event.v1.EventStub.publish", mock_publish): + topic = EventClient().topic("test-topic") + await topic.publish() + + # Check expected values were passed to Stub + mock_publish.assert_called_once() + assert mock_publish.call_args.kwargs["topic"] == "test-topic" + assert mock_publish.call_args.kwargs["event"].id == "" + assert mock_publish.call_args.kwargs["event"].payload_type == "" + assert mock_publish.call_args.kwargs["event"].payload == Struct() diff --git a/tests/api/test_grpc_error.py b/tests/api/test_grpc_error.py deleted file mode 100644 index daf8d06..0000000 --- a/tests/api/test_grpc_error.py +++ /dev/null @@ -1,78 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -import unittest -from unittest.mock import patch, Mock -from nitric.api import EventClient -from nitric.api.exception import * -import grpc -from grpc._channel import _InactiveRpcError, _RPCState - - -class GRPCErrorCases(unittest.TestCase): - def test_unavailable(self): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_publish = Mock() - - # Emulate unavailable error - state = _RPCState((), (), (), grpc.StatusCode.UNAVAILABLE, "test only") - mock_publish.side_effect = Mock(side_effect=_InactiveRpcError(state)) - mock_publish._method = b"test.topic/Publish" - - with patch("nitric.api.EventClient._get_method_function", mock_grpc_method_getter): - client = EventClient() - self.assertRaises(UnavailableException, client.publish, topic_name="t", payload_type="p") - - def test_unimplemented(self): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_publish = Mock() - - # Emulate unavailable error - state = _RPCState((), (), (), grpc.StatusCode.UNIMPLEMENTED, "test only") - mock_publish.side_effect = Mock(side_effect=_InactiveRpcError(state)) - mock_publish._method = b"test.topic/Publish" - - with patch("nitric.api.EventClient._get_method_function", mock_grpc_method_getter): - client = EventClient() - self.assertRaises(UnimplementedException, client.publish, topic_name="t", payload_type="p") - - def test_already_exists(self): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_publish = Mock() - - # Emulate unavailable error - state = _RPCState((), (), (), grpc.StatusCode.ALREADY_EXISTS, "test only") - mock_publish.side_effect = Mock(side_effect=_InactiveRpcError(state)) - mock_publish._method = b"test.topic/Publish" - - with patch("nitric.api.EventClient._get_method_function", mock_grpc_method_getter): - client = EventClient() - self.assertRaises(AlreadyExistsException, client.publish, topic_name="t", payload_type="p") - - def test_unexpected_exception(self): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_publish = Mock() - - # Emulate unavailable error - mock_publish.side_effect = Mock(side_effect=Exception("other exception")) - mock_publish._method = b"test.topic/Publish" - - with patch("nitric.api.EventClient._get_method_function", mock_grpc_method_getter): - client = EventClient() - # Expect a standard Exception if a non-grpc error is raised. - self.assertRaises(Exception, client.publish, topic_name="t", payload_type="p") diff --git a/tests/api/test_key_value_client.py b/tests/api/test_key_value_client.py deleted file mode 100644 index 11b27f2..0000000 --- a/tests/api/test_key_value_client.py +++ /dev/null @@ -1,92 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from unittest.mock import patch, Mock - -from google.protobuf.struct_pb2 import Struct - -from nitric.api import KeyValueClient -from nitric.proto.kv.v1.kv_pb2 import KeyValueGetResponse - - -# Put -def test_put_key_value(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_create = Mock() - - test_key_value = {"content": "some text content"} - - with patch("nitric.api.KeyValueClient._get_method_function", mock_grpc_method_getter): - client = KeyValueClient() - client.put("collection_name", "kv_key", test_key_value) - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Put") - - # Ensure the get topics method is called with the expected input - mock_create.assert_called_once() # No input data required to get topics - assert mock_create.call_args[0][0].collection == "collection_name" - assert mock_create.call_args[0][0].key == "kv_key" - assert mock_create.call_args[0][0].value["content"] == "some text content" - - -# Get -def test_get_key_value(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_get = Mock() - value_struct = Struct() - value_struct.update({"kv_key": "doc_value"}) - reply = KeyValueGetResponse(value=value_struct) - mock_get.return_value = reply - - with patch("nitric.api.KeyValueClient._get_method_function", mock_grpc_method_getter): - client = KeyValueClient() - response_value = client.get("collection_name", "kv_key") - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Get") - assert response_value == {"kv_key": "doc_value"} - - -# Delete -def test_delete_key_value(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_create = Mock() - - with patch("nitric.api.KeyValueClient._get_method_function", mock_grpc_method_getter): - client = KeyValueClient() - client.delete("collection_name", "kv_key") - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Delete") - - # Ensure the get topics method is called with the expected input - mock_create.assert_called_once() # No input data required to get topics - assert mock_create.call_args[0][0].collection == "collection_name" - assert mock_create.call_args[0][0].key == "kv_key" - - -def test_grpc_methods(): - client = KeyValueClient() - assert client._get_method_function("Put")._method == b"/nitric.kv.v1.KeyValue/Put" - assert client._get_method_function("Get")._method == b"/nitric.kv.v1.KeyValue/Get" - assert client._get_method_function("Delete")._method == b"/nitric.kv.v1.KeyValue/Delete" - - -def test_create_client(): - client = KeyValueClient() diff --git a/tests/api/test_models.py b/tests/api/test_models.py deleted file mode 100644 index dbe0bdd..0000000 --- a/tests/api/test_models.py +++ /dev/null @@ -1,23 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from nitric.api.models import Topic - - -def test_topic_model(): - topic = Topic("test_topic") diff --git a/tests/api/test_queue_client.py b/tests/api/test_queue_client.py deleted file mode 100644 index c646fcd..0000000 --- a/tests/api/test_queue_client.py +++ /dev/null @@ -1,105 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from unittest.mock import patch, Mock -from nitric.api import QueueClient, Task - - -def test_push(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_push = Mock() - mock_push.return_value.failedMessages = [] - - test_tasks = [Task(task_id="1234", payload_type="test-payload", payload={"test": "test"})] - - with patch("nitric.api.QueueClient._get_method_function", mock_grpc_method_getter): - client = QueueClient() - client.send_batch("test-queue", test_tasks) - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("SendBatch") - - # Ensure the queue push method is called with the expected input - mock_push.assert_called_once() - assert mock_push.call_args[0][0].queue == "test-queue" - assert mock_push.call_args[0][0].tasks[0].id == "1234" - assert mock_push.call_args[0][0].tasks[0].payload_type == "test-payload" - assert mock_push.call_args[0][0].tasks[0].payload["test"] == "test" - - -def test_receive(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_receive = Mock() - mock_receive.return_value.items = [] - - with patch("nitric.api.QueueClient._get_method_function", mock_grpc_method_getter): - client = QueueClient() - client.receive("test-queue", 1) - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Receive") - - # Ensure the queue receive method is called with the expected input - mock_receive.assert_called_once() - assert mock_receive.call_args[0][0].queue == "test-queue" - assert mock_receive.call_args[0][0].depth == 1 - - -def test_receive_no_depth(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_receive = Mock() - mock_receive.return_value.items = [] - - with patch("nitric.api.QueueClient._get_method_function", mock_grpc_method_getter): - client = QueueClient() - client.receive("test-queue") # call receive without the optional depth parameter. - - # Ensure the default value 1 is used. - assert mock_receive.call_args[0][0].depth == 1 - - -def test_receive_none_depth(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_receive = Mock() - mock_receive.return_value.items = [] - - with patch("nitric.api.QueueClient._get_method_function", mock_grpc_method_getter): - client = QueueClient() - client.receive("test-queue", None) # call receive with depth = None. - - # Ensure the default value 1 is used. - assert mock_receive.call_args[0][0].depth == 1 - - -def test_receive_negative_depth(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_receive = Mock() - mock_receive.return_value.items = [] - - with patch("nitric.api.QueueClient._get_method_function", mock_grpc_method_getter): - client = QueueClient() - client.receive("test-queue", -2) # call receive with a negative integer for depth. - - # Ensure the default value 1 is used. - assert mock_receive.call_args[0][0].depth == 1 - - -def test_grpc_methods(): - client = QueueClient() - assert client._get_method_function("SendBatch")._method == b"/nitric.queue.v1.Queue/SendBatch" - assert client._get_method_function("Receive")._method == b"/nitric.queue.v1.Queue/Receive" diff --git a/tests/api/test_storage_client.py b/tests/api/test_storage_client.py deleted file mode 100644 index ba18843..0000000 --- a/tests/api/test_storage_client.py +++ /dev/null @@ -1,65 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from unittest.mock import patch, Mock -from nitric.api import StorageClient - - -# Write to bucket -def test_write(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_create = Mock() - - content = b"test content" - - with patch("nitric.api.StorageClient._get_method_function", mock_grpc_method_getter): - client = StorageClient() - client.write("bucket_name", "key_name", content) - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Write") - - # Ensure the 'Put' method is called with the expected input - mock_create.assert_called_once() # No input data required to get topics - assert mock_create.call_args[0][0].bucket_name == "bucket_name" - assert mock_create.call_args[0][0].key == "key_name" - assert mock_create.call_args[0][0].body == content - - -# Read from bucket -def test_read(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_create = Mock() - - with patch("nitric.api.StorageClient._get_method_function", mock_grpc_method_getter): - client = StorageClient() - client.read("bucket_name", "key_name") - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("Read") - - # Ensure the 'Get' method is called with the expected input - mock_create.assert_called_once() # No input data required to get topics - assert mock_create.call_args[0][0].bucket_name == "bucket_name" - assert mock_create.call_args[0][0].key == "key_name" - - -def test_grpc_methods(): - client = StorageClient() - assert client._get_method_function("Read")._method == b"/nitric.storage.v1.Storage/Read" - assert client._get_method_function("Write")._method == b"/nitric.storage.v1.Storage/Write" diff --git a/tests/api/test_topic_client.py b/tests/api/test_topic_client.py deleted file mode 100644 index 579d3cf..0000000 --- a/tests/api/test_topic_client.py +++ /dev/null @@ -1,45 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from unittest.mock import patch, Mock -from nitric.api import TopicClient -from google.protobuf.struct_pb2 import Struct - - -def test_get_topics(): - mock_grpc_method_getter = Mock() - mock_grpc_method_getter.return_value = mock_get_topics = Mock() - mock_get_topics.return_value.topics = [] - - with patch("nitric.api.TopicClient._get_method_function", mock_grpc_method_getter): - client = TopicClient() - topics = client.get_topics() - - # Ensure the correct gRPC method is retrieved - mock_grpc_method_getter.assert_called_with("List") - # Ensure the get topics method is called - mock_get_topics.assert_called_with(Struct()) # No input data required to get topics - - -def test_grpc_methods(): - client = TopicClient() - assert client._get_method_function("List")._method == b"/nitric.event.v1.Topic/List" - - -def test_create_client(): - client = TopicClient() diff --git a/tests/faas/__init__.py b/tests/faas/__init__.py deleted file mode 100644 index 4eb07ea..0000000 --- a/tests/faas/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# diff --git a/tests/faas/test_start.py b/tests/faas/test_start.py deleted file mode 100644 index 1ca423e..0000000 --- a/tests/faas/test_start.py +++ /dev/null @@ -1,134 +0,0 @@ -# -# Copyright (c) 2021 Nitric Technologies Pty Ltd. -# -# This file is part of Nitric Python 3 SDK. -# See https://github.com/nitrictech/python-sdk for further info. -# -# Licensed 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. -# -from unittest.mock import patch, Mock -import unittest -from nitric.faas import Response, ResponseContext, HttpResponseContext -from nitric.faas import start -from nitric.faas.faas import Handler -from nitric.proto.faas.v1.faas_pb2 import TriggerResponse, TriggerRequest -from google.protobuf import json_format - - -class StartCases(unittest.TestCase): - def test_serve_called(self): - mock_serve = Mock() - mock_serve.return_value = None - - with patch("nitric.faas.faas.serve", mock_serve): - start(func=lambda a: "test mock response") - - args, kwargs = mock_serve.call_args - mock_serve.assert_called_once() - assert kwargs["host"] == "127.0.0.1" - assert kwargs["port"] == 8080 - - -class HandlerCases(unittest.TestCase): - def test_full_response(self): - mock_func = Mock() - mock_response = Response( - data="it works".encode(), - context=ResponseContext(context=HttpResponseContext(headers={"a": "a header"}, status=200)), - ) - mock_func.return_value = mock_response - - return_body = json_format.MessageToJson(mock_response.to_grpc_trigger_response_context()) - - construct_request_mock = Mock() - construct_request_mock.return_value = TriggerRequest() - - with patch("nitric.faas.faas.construct_request", construct_request_mock): - handler = Handler(mock_func) - response = handler() - - # Ensure the response is returned in the tuple format for Flask - assert response == (return_body, 200, {"Content-Type": "application/json"}) - - def test_unhandled_exception(self): - # always return and error to test how it's handled internally - def error_func(): - raise Exception("mock error") - - construct_request_mock = Mock() - construct_request_mock.return_value = TriggerRequest() - - with patch("nitric.faas.faas.construct_request", construct_request_mock): - handler = Handler(error_func) - response = handler() - - # Ensure the 500 internal server error status is returned. - # TODO: No body should be included outside of debug mode. Use this assert in future once that's implemented - # assert response == ('', 500) - # We'll return a 200 OK for errors, the actual response is encoded in the body - assert response[1] == 200 # For now, just check that the error status is set - - def test_debug_unhandled_exception(self): - # TODO: set the debug environment variable (or equivalent) once available - # always return and error to test how it's handled internally - def error_func(): - raise Exception("mock error") - - construct_request_mock = Mock() - construct_request_mock.return_value = TriggerRequest() - - with patch("nitric.faas.faas.construct_request", construct_request_mock): - handler = Handler(error_func) - response = handler() - - trigger_response = json_format.Parse(response[0], TriggerResponse()) - - # Ensure the debug details are provided along with the error status - assert trigger_response.data.decode().startswith( - "Error

An Error Occurred:

" - ) - assert response[1] == 200 # Status code - - def test_str_response(self): - mock_func = Mock() - mock_func.return_value = "test" - - construct_request_mock = Mock() - construct_request_mock.return_value = TriggerRequest() - - with patch("nitric.faas.faas.construct_request", construct_request_mock): - handler = Handler(mock_func) - response = handler() - - trigger_response = json_format.Parse(response[0], TriggerResponse()) - - # Ensure the response string was wrapped with http response values - assert trigger_response.data.decode() == "test" - assert response[1] == 200 - - def test_no_response(self): - def no_response(request): - # do nothing - mock = Mock() - - construct_request_mock = Mock() - construct_request_mock.return_value = TriggerRequest() - - with patch("nitric.faas.faas.construct_request", construct_request_mock): - handler = Handler(no_response) - response = handler() - - trigger_response = json_format.Parse(response[0], TriggerResponse()) - # Ensure an empty response with a success status - assert trigger_response.data.decode() == "" - assert response[1] == 200 diff --git a/tests/test__utils.py b/tests/test__utils.py new file mode 100644 index 0000000..3b39605 --- /dev/null +++ b/tests/test__utils.py @@ -0,0 +1,20 @@ +import copy + +from nitric.api._utils import _struct_from_dict, _dict_from_struct + + +def test__dict_from_struct(): + dict_val = { + "a": True, + "b": False, + "c": 1, + "d": 4.123, + "e": "this is a string", + "f": None, + "g": {"ga": 1, "gb": "testing inner dict"}, + "h": [1, 2, 3, "four"], + } + dict_copy = copy.deepcopy(dict_val) + + # Serialization and Deserialization shouldn't modify the object in most cases. + assert _dict_from_struct(_struct_from_dict(dict_val)) == dict_copy diff --git a/tox.ini b/tox.ini index 579b1aa..5e4be78 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = linter,py3.7,py3.8 +envlist = linter,py3.8 [testenv] deps = From 343290c175692a14e21752c4afd9b5d234ae217b Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Mon, 28 Jun 2021 18:23:34 +1000 Subject: [PATCH 04/33] test(QueueClient): update tests for new api and async --- nitric/api/events.py | 8 +-- nitric/api/queues.py | 73 +++++++++++++++++------ tests/api/test_event_client.py | 10 ++-- tests/api/test_queue_client.py | 103 +++++++++++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 27 deletions(-) create mode 100644 tests/api/test_queue_client.py diff --git a/nitric/api/events.py b/nitric/api/events.py index a228b5e..d540a72 100644 --- a/nitric/api/events.py +++ b/nitric/api/events.py @@ -27,8 +27,8 @@ class Event(object): """Represents a NitricEvent.""" payload: dict = field(default_factory=dict) - id: str = "" - payload_type: str = "" + id: str = field(default=None) + payload_type: str = field(default=None) def _event_to_wire(event: Event) -> NitricEvent: @@ -85,5 +85,5 @@ async def topics(self) -> List[Topic]: response = await self._topic_stub.list() return [self.topic(topic.name) for topic in response.topics] - def topic(self, topic: str) -> Topic: - return Topic(_stub=self._stub, name=topic) + def topic(self, name: str) -> Topic: + return Topic(_stub=self._stub, name=name) diff --git a/nitric/api/queues.py b/nitric/api/queues.py index f0d689e..7be4f0b 100644 --- a/nitric/api/queues.py +++ b/nitric/api/queues.py @@ -30,12 +30,25 @@ class Task(object): payload_type: str = field(default=None) payload: dict = field(default_factory=dict) lease_id: str = field(default=None) + _queue_stub: QueueStub = field(default=None) + _queue: str = field(default=None) + + async def complete(self): + if self._queue_stub is None or self._queue is None or self._queue == "": + raise Exception("Task was not created via Queue.") + if self.lease_id is None: + raise Exception( + "No lease_id available for task. Tasks must be received using Queue.receive to have a " + "valid lease_id." + ) + await self._queue_stub.complete(queue=self._queue, lease_id=self.lease_id) @dataclass(frozen=True, order=True) class FailedTask(Task): """Represents a failed queue publish for an event.""" + lease_id: str = None # failed tasks should never have a lease id. message: str = field(default="") @@ -86,19 +99,29 @@ def _wire_to_failed_task(failed_task: WireFailedTask) -> FailedTask: ) -class QueueClient(object): - """ - Nitric generic publish/subscribe tasking client. +@dataclass(frozen=True, order=True) +class Queue(object): - This client insulates application code from stack specific task/topic operations or SDKs. - """ + _queue_stub: QueueStub + name: str - def __init__(self, queue: str): - """Construct a Nitric Queue Client.""" - self.queue = queue - self._stub = QueueStub(channel=new_default_channel()) + async def send( + self, tasks: Union[Task, dict, List[Union[Task, dict]]] = None + ) -> Union[Task, List[Union[Task, FailedTask]]]: + if isinstance(tasks, list): + return await self._send_batch(tasks) + + task = tasks + if task is None: + task = Task() + + if isinstance(task, dict): + # TODO: handle tasks that are just a payload + task = Task(**task) + + await self._queue_stub.send(queue=self.name, task=_task_to_wire(task)) - async def send_batch( + async def _send_batch( self, tasks: List[Union[Task, dict]] = None, raise_on_failure: bool = True ) -> List[FailedTask]: """ @@ -113,11 +136,11 @@ async def send_batch( wire_tasks = [_task_to_wire(Task(**task) if isinstance(task, dict) else task) for task in tasks] - response = await self._stub.send_batch(queue=self.queue, tasks=wire_tasks) + response = await self._queue_stub.send_batch(queue=self.name, tasks=wire_tasks) return [_wire_to_failed_task(failed_task) for failed_task in response.failed_tasks] - async def receive(self, depth: int = None) -> List[Task]: + async def receive(self, limit: int = None) -> List[Task]: """ Pop 1 or more items from the specified queue up to the depth limit. @@ -127,15 +150,29 @@ async def receive(self, depth: int = None) -> List[Task]: If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be returned to the queue for reprocessing. - identifier. - :param depth: The maximum number of queue items to return. Default: 1, Min: 1. + :param limit: The maximum number of queue items to return. Default: 1, Min: 1. :return: Queue items popped from the specified queue. """ # Set the default and minimum depth to 1. - if depth is None or depth < 1: - depth = 1 + if limit is None or limit < 1: + limit = 1 - response = await self._stub.receive(queue=self.queue, depth=depth) + response = await self._queue_stub.receive(queue=self.name, depth=limit) - # Map the response protobuf response items to Python SDK Nitric Queue Items + # Map the response protobuf response items to Python SDK Nitric Tasks return [_wire_to_task(task) for task in response.tasks] + + +class QueueClient(object): + """ + Nitric generic publish/subscribe tasking client. + + This client insulates application code from stack specific task/topic operations or SDKs. + """ + + def __init__(self): + """Construct a Nitric Queue Client.""" + self._queue_stub = QueueStub(channel=new_default_channel()) + + def queue(self, name: str): + return Queue(_queue_stub=self._queue_stub, name=name) diff --git a/tests/api/test_event_client.py b/tests/api/test_event_client.py index 7278671..a61118b 100644 --- a/tests/api/test_event_client.py +++ b/tests/api/test_event_client.py @@ -48,8 +48,8 @@ async def test_publish(self): # Check expected values were passed to Stub mock_publish.assert_called_once() assert mock_publish.call_args.kwargs["topic"] == "test-topic" - assert mock_publish.call_args.kwargs["event"].id == "" - assert mock_publish.call_args.kwargs["event"].payload_type == "" + assert mock_publish.call_args.kwargs["event"].id is None + assert mock_publish.call_args.kwargs["event"].payload_type is None assert len(mock_publish.call_args.kwargs["event"].payload.fields) == 1 assert mock_publish.call_args.kwargs["event"].payload == _struct_from_dict(payload) @@ -69,7 +69,7 @@ async def test_publish_dict(self): mock_publish.assert_called_once() assert mock_publish.call_args.kwargs["topic"] == "test-topic" assert mock_publish.call_args.kwargs["event"].id == "123" - assert mock_publish.call_args.kwargs["event"].payload_type == "" + assert mock_publish.call_args.kwargs["event"].payload_type is None assert len(mock_publish.call_args.kwargs["event"].payload.fields) == 1 assert mock_publish.call_args.kwargs["event"].payload == _struct_from_dict(payload) @@ -105,6 +105,6 @@ async def test_publish_none(self): # Check expected values were passed to Stub mock_publish.assert_called_once() assert mock_publish.call_args.kwargs["topic"] == "test-topic" - assert mock_publish.call_args.kwargs["event"].id == "" - assert mock_publish.call_args.kwargs["event"].payload_type == "" + assert mock_publish.call_args.kwargs["event"].id is None + assert mock_publish.call_args.kwargs["event"].payload_type is None assert mock_publish.call_args.kwargs["event"].payload == Struct() diff --git a/tests/api/test_queue_client.py b/tests/api/test_queue_client.py new file mode 100644 index 0000000..309c7d3 --- /dev/null +++ b/tests/api/test_queue_client.py @@ -0,0 +1,103 @@ +# +# Copyright (c) 2021 Nitric Technologies Pty Ltd. +# +# This file is part of Nitric Python 3 SDK. +# See https://github.com/nitrictech/python-sdk for further info. +# +# Licensed 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. +# +from unittest import IsolatedAsyncioTestCase +from unittest.mock import patch, AsyncMock + +from betterproto.lib.google.protobuf import Struct + +from nitric.api import QueueClient, Task +from nitric.api._utils import _struct_from_dict + + +class Object(object): + pass + + +class QueueClientTest(IsolatedAsyncioTestCase): + async def test_send(self): + mock_send = AsyncMock() + mock_response = Object() + mock_send.return_value = mock_response + + payload = {"content": "of task"} + + with patch("nitric.proto.nitric.queue.v1.QueueStub.send", mock_send): + queue = QueueClient().queue("test-queue") + await queue.send(Task(payload=payload)) + + # Check expected values were passed to Stub + mock_send.assert_called_once() + assert mock_send.call_args.kwargs["queue"] == "test-queue" + assert mock_send.call_args.kwargs["task"].id is None + assert mock_send.call_args.kwargs["task"].payload_type is None + assert len(mock_send.call_args.kwargs["task"].payload.fields) == 1 + assert mock_send.call_args.kwargs["task"].payload == _struct_from_dict(payload) + + async def test_send_dict(self): + mock_send = AsyncMock() + mock_response = Object() + mock_send.return_value = mock_response + + payload = {"content": "of task"} + + with patch("nitric.proto.nitric.queue.v1.QueueStub.send", mock_send): + queue = QueueClient().queue("test-queue") + await queue.send({"id": "123", "payload": payload}) + + # Check expected values were passed to Stub + mock_send.assert_called_once() + assert mock_send.call_args.kwargs["queue"] == "test-queue" + assert mock_send.call_args.kwargs["task"].id == "123" + assert mock_send.call_args.kwargs["task"].payload_type is None + assert len(mock_send.call_args.kwargs["task"].payload.fields) == 1 + assert mock_send.call_args.kwargs["task"].payload == _struct_from_dict(payload) + + async def test_publish_invalid_type(self): + mock_send = AsyncMock() + mock_response = Object() + mock_send.return_value = mock_response + + payload = {"content": "of task"} + + with patch("nitric.proto.nitric.queue.v1.QueueStub.send", mock_send): + queue = QueueClient().queue("test-queue") + try: + await queue.send((1, 2, 3)) + assert False + except AttributeError: + # Exception raised if expected duck type attributes are missing + assert True + + async def test_send_none(self): + mock_send = AsyncMock() + mock_response = Object() + mock_send.return_value = mock_response + + payload = {"content": "of task"} + + with patch("nitric.proto.nitric.queue.v1.QueueStub.send", mock_send): + queue = QueueClient().queue("test-queue") + await queue.send() + + # Check expected values were passed to Stub + mock_send.assert_called_once() + assert mock_send.call_args.kwargs["queue"] == "test-queue" + assert mock_send.call_args.kwargs["task"].id is None + assert mock_send.call_args.kwargs["task"].payload_type is None + assert mock_send.call_args.kwargs["task"].payload == Struct() From 15db383cbb123ac65f4e18e043d5eba4ab3e7249 Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Mon, 28 Jun 2021 20:46:45 +1000 Subject: [PATCH 05/33] wip: update storage api and tests --- nitric/api/storage.py | 58 ++++++++++++---------- tests/api/test_storage_client.py | 83 ++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 26 deletions(-) create mode 100644 tests/api/test_storage_client.py diff --git a/nitric/api/storage.py b/nitric/api/storage.py index f530730..1cbc4f5 100644 --- a/nitric/api/storage.py +++ b/nitric/api/storage.py @@ -16,6 +16,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from dataclasses import dataclass + from nitric.api._utils import new_default_channel from nitric.proto.nitric.storage.v1 import StorageStub @@ -27,38 +29,42 @@ class StorageClient(object): This client insulates application code from stack specific blob store operations or SDKs. """ - def __init__(self, bucket: str): - """ - Construct a Nitric Event Client. + def __init__(self): + """Construct a Nitric Storage Client.""" + self._storage_stub = StorageStub(channel=new_default_channel()) - :param bucket: name of the bucket to perform operations on. - """ - self.bucket = bucket - self._stub = StorageStub(channel=new_default_channel()) + def bucket(self, name: str): + return Bucket(_storage_stub=self._storage_stub, name=name) - async def write(self, key: str, body: bytes): - """ - Write a file to the bucket under the given key. - :param key: key within the bucket, where the file should be stored. - :param body: data to be stored. - """ - await self._stub.write(bucket_name=self.bucket, key=key, body=body) +@dataclass(frozen=True, order=True) +class Bucket(object): + _storage_stub: StorageStub + name: str - async def read(self, key: str) -> bytes: - """ - Retrieve an existing file. + def file(self, key: str): + return File(_storage_stub=self._storage_stub, _bucket=self.name, key=key) - :param key: key for the file to retrieve. - :return: the file as bytes. - """ - response = await self._stub.read(bucket_name=self.bucket, key=key) - return response.body - async def delete(self, key: str): +@dataclass(frozen=True, order=True) +class File(object): + _storage_stub: StorageStub + _bucket: str + key: str + + async def write(self, body: bytes): """ - Delete an existing file. + Write the bytes as the content of this file. - :param key: key of the file to delete. + Will create the file if it doesn't already exist. """ - await self._stub.delete(bucket_name=self.bucket, key=key) + await self._storage_stub.write(bucket_name=self._bucket, key=self.key, body=body) + + async def read(self) -> bytes: + """Read this files contents from the bucket.""" + response = await self._storage_stub.read(bucket_name=self._bucket, key=self.key) + return response.body + + async def delete(self): + """Delete this file from the bucket.""" + await self._storage_stub.delete(bucket_name=self._bucket, key=self.key) diff --git a/tests/api/test_storage_client.py b/tests/api/test_storage_client.py new file mode 100644 index 0000000..6586c2c --- /dev/null +++ b/tests/api/test_storage_client.py @@ -0,0 +1,83 @@ +# +# Copyright (c) 2021 Nitric Technologies Pty Ltd. +# +# This file is part of Nitric Python 3 SDK. +# See https://github.com/nitrictech/python-sdk for further info. +# +# Licensed 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. +# +from unittest import IsolatedAsyncioTestCase +from unittest.mock import patch, AsyncMock + +from betterproto.lib.google.protobuf import Struct + +from nitric.api import StorageClient +from nitric.api._utils import _struct_from_dict + + +class Object(object): + pass + + +class StorageClientTest(IsolatedAsyncioTestCase): + async def test_write(self): + mock_write = AsyncMock() + mock_response = Object() + mock_write.return_value = mock_response + + contents = b"some text as bytes" + + with patch("nitric.proto.nitric.storage.v1.StorageStub.write", mock_write): + bucket = StorageClient().bucket("test-bucket") + file = bucket.file("test-file") + await file.write(contents) + + # Check expected values were passed to Stub + mock_write.assert_called_once() + assert mock_write.call_args.kwargs["bucket_name"] == "test-bucket" + assert mock_write.call_args.kwargs["key"] == "test-file" + assert mock_write.call_args.kwargs["body"] == contents + + async def test_read(self): + contents = b"some text as bytes" + + mock_read = AsyncMock() + mock_response = Object() + mock_response.body = contents + mock_read.return_value = mock_response + + with patch("nitric.proto.nitric.storage.v1.StorageStub.read", mock_read): + bucket = StorageClient().bucket("test-bucket") + file = bucket.file("test-file") + response = await file.read() + + assert response == contents + + # Check expected values were passed to Stub + mock_read.assert_called_once() + assert mock_read.call_args.kwargs["bucket_name"] == "test-bucket" + assert mock_read.call_args.kwargs["key"] == "test-file" + + async def test_delete(self): + mock_read = AsyncMock() + mock_read.return_value = Object() + + with patch("nitric.proto.nitric.storage.v1.StorageStub.delete", mock_read): + bucket = StorageClient().bucket("test-bucket") + file = bucket.file("test-file") + await file.delete() + + # Check expected values were passed to Stub + mock_read.assert_called_once() + assert mock_read.call_args.kwargs["bucket_name"] == "test-bucket" + assert mock_read.call_args.kwargs["key"] == "test-file" From 616cfea5f117b38aa684ac91ffa48f87e797dd38 Mon Sep 17 00:00:00 2001 From: Tim Holm Date: Sun, 13 Jun 2021 22:32:13 +1000 Subject: [PATCH 06/33] wip: WIP python gRPC FaaS implementation. --- nitric/faas/__init__.py | 4 +- nitric/faas/faas.py | 202 +++++++++++++++---------------- nitric/faas/response.py | 57 ++------- nitric/faas/trigger.py | 58 +++------ nitric/proto/faas/__init__.py | 0 nitric/proto/faas/v1/__init__.py | 0 tests/faas/test_request.py | 111 +++++++++++++++++ 7 files changed, 235 insertions(+), 197 deletions(-) create mode 100644 nitric/proto/faas/__init__.py create mode 100644 nitric/proto/faas/v1/__init__.py create mode 100644 tests/faas/test_request.py diff --git a/nitric/faas/__init__.py b/nitric/faas/__init__.py index d818ceb..26d0199 100644 --- a/nitric/faas/__init__.py +++ b/nitric/faas/__init__.py @@ -17,8 +17,8 @@ # limitations under the License. # """Nitric Function as a Service (FaaS) Package.""" -from nitric.faas.trigger import Trigger, TriggerContext -from nitric.faas.response import Response, ResponseContext, HttpResponseContext, TopicResponseContext +from nitric.faas.trigger import Request, Context, SourceType +from nitric.faas.response import Response from nitric.faas.faas import start __all__ = [ diff --git a/nitric/faas/faas.py b/nitric/faas/faas.py index 80a4ea1..a7efce6 100644 --- a/nitric/faas/faas.py +++ b/nitric/faas/faas.py @@ -16,116 +16,106 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Callable, Union +from typing import Awaitable, Coroutine, Callable, Union -from flask import Flask, request -from waitress import serve - -from nitric.proto.faas.v1.faas_pb2 import TriggerRequest, TriggerResponse from nitric.config import settings -from nitric.faas import Trigger, Response -from google.protobuf import json_format - - -def construct_request() -> TriggerRequest: - """Construct a Nitric Request object from the Flask HTTP Request.""" - # full_path used to better match behavior in other SDKs - # return TriggerRequest(dict(request.headers), request.get_data(), path=request.full_path) - message = json_format.Parse(request.get_data(), TriggerRequest(), ignore_unknown_fields=False) - return message - - -def http_response(response: TriggerResponse): - """ - Return a full HTTP response tuple based on the Nitric Response contents. - - The response includes a body, status and headers as appropriate. - """ - headers = {"Content-Type": "application/json"} - - return json_format.MessageToJson(response), 200, headers - - -def exception_to_html(): - """Return a traceback as HTML.""" - import traceback - import sys - import html - - limit = None - exception_type, value, tb = sys.exc_info() - trace_list = traceback.format_tb(tb, limit) + traceback.format_exception_only(exception_type, value) - body = "Traceback:\n" + "%-20s %s" % ("".join(trace_list[:-1]), trace_list[-1]) - return ( - "Error

An Error Occurred:

\n
"
-        + html.escape(body)
-        + "
\n" - ) - - -class Handler(object): - """Nitric Function handler.""" - - def __init__(self, func: Callable[[Trigger], Union[Response, str]]): - """Construct a new handler using the provided function to handle new requests.""" - self.func = func - - def __call__(self, path="", *args): - """Construct Nitric Request from HTTP Request.""" - trigger_request = construct_request() - - grpc_trigger_response: TriggerResponse - - # convert it to a trigger - trigger = Trigger.from_trigger_request(trigger_request) - - try: - # Execute the handler function - response: Union[Response, str] = self.func(trigger) - - final_response: Response - if isinstance(response, str): - final_response = trigger.default_response() - final_response.data = response.encode() - elif isinstance(response, Response): - final_response = response - else: - # assume None - final_response = trigger.default_response() - final_response.data = "".encode() - - grpc_trigger_response = final_response.to_grpc_trigger_response_context() - - except Exception: - trigger_response = trigger.default_response() - if trigger_response.context.is_http(): - trigger_response.context.as_http().status = 500 - trigger_response.context.as_http().headers = {"Content-Type": "text/html"} - trigger_response.data = exception_to_html().encode() - elif trigger_response.context.is_topic(): - trigger_response.data = "Error processing message" - trigger_response.context.as_topic().success = False - - grpc_trigger_response = trigger_response.to_grpc_trigger_response_context() - - return http_response(grpc_trigger_response) - - -def start(func: Callable[[Trigger], Union[Response, str]]): +from nitric.faas import Request, Response +from grpc import aio + +from nitric.faas.trigger import Trigger +from nitric.proto.faas.v1 import faas_pb2, faas_pb2_grpc + +import asyncio + + +def get_stream(stub: faas_pb2_grpc.FaasStub) -> aio.StreamStreamCall[faas_pb2.ClientMessage, faas_pb2.ServerMessage]: + return stub.TriggerStream() + + +async def loop( + func: Union[Callable[[Request], Union[Response, str]], Coroutine[Awaitable[Union[str, Response]], Request]] +): + """FaaS loop""" + async with aio.insecure_channel(settings.SERVICE_BIND) as channel: + stub = faas_pb2_grpc.FaasStub(channel) + stream = get_stream(stub) + + # Let the server know we're ready to work + await stream.write(faas_pb2.ClientMessage(init_request=faas_pb2.InitRequest())) + + # Infinite loop + while 1: + # Receive a message, will block until a message is available + # This can be one of ServerMessage of EOFType + # If its an EOFType we may terminate the stream + # Otherwise we keep running + msg = await stream.read() + + # EOF we can exit now + if msg is None: + # Break the loop + break + + if msg.init_response is not None: + # Handle the init response + print("Function connected to Membrane") + # We don't need to reply + # Time to go to the next available message + continue + elif msg.trigger_request is not None: + client_msg = faas_pb2.ClientMessage( + id=msg.id, + ) + + trigger = Trigger.from_trigger_request(trigger_request=msg.trigger_request) + # Invoke the handler here + try: + # FIXME: Await the function as an async function + # This will allow the user to define non-blocking I/O within the scope + # of their function allowing the runtime to queue up more requests + if asyncio.iscoroutinefunction(func): + response = await func(trigger) + else: + response = func(trigger) + + if isinstance(response, Response): + client_msg.trigger_response = response.to_grpc_trigger_response_context() + elif isinstance(response, str): + # Construct a default response from the data + default_response = trigger.default_response() + default_response.data = response.encode() + client_msg.trigger_response = default_response + + # translate the response + except Exception: + # Handle the exception here + # write an exception back to the server + default_response = trigger.default_response() + default_response.data = "Internal Error".encode() + if default_response.context.is_http(): + http_context = default_response.context.as_http() + http_context.status = 500 + http_context.headers = {"Content-Type": "text/plain"} + elif default_response.context.is_topic(): + topic_context = default_response.context.as_topic() + topic_context.success = False + + client_msg.trigger_response = default_response.to_grpc_trigger_response_context() + + # Write it back to the server + await stream.write(client_msg) + # Continue the loop + + print("Function Exiting") + + +# TODO: We need to change this to an Awaitable or a Coroutine +def start(func: Union[Callable[[Request], Union[Response, str]], Coroutine[Awaitable[Union[str, Response]], Request]]): """ Register the provided function as the request handler and starts handling new requests. :param func: to use to handle new requests """ - app = Flask(__name__) - app.add_url_rule("/", "index", Handler(func), methods=["GET", "PUT", "POST", "PATCH", "DELETE"]) - app.add_url_rule( - "/", - "path", - Handler(func), - methods=["GET", "PUT", "POST", "PATCH", "DELETE"], - ) - - host, port = f"{settings.CHILD_ADDRESS}".split(":") - # Start the function HTTP server - serve(app, host=host, port=int(port)) + + # Begin the event loop + asyncio.run(loop(func)) diff --git a/nitric/faas/response.py b/nitric/faas/response.py index 472aaab..408a462 100644 --- a/nitric/faas/response.py +++ b/nitric/faas/response.py @@ -17,78 +17,44 @@ # limitations under the License. # from typing import Union, Dict -from nitric.proto.faas.v1 import faas_pb2 -from nitric.proto.faas.v1.faas_pb2 import TriggerResponse +from nitric.proto.faas.v1.faas_pb2 import TriggerResponse, HttpResponseContext, TopicResponseContext class TopicResponseContext(object): - """Response context for triggers raised by a topic event.""" - def __init__(self, success: bool = True): - """Create a Topic response context.""" self.success = success - def to_grpc_topic_response_context(self) -> faas_pb2.TopicResponseContext: - """Translate a topic response context for wire transport.""" - return faas_pb2.TopicResponseContext(success=self.success) + def to_grpc_topic_response_context(self) -> TopicResponseContext: + return TopicResponseContext(success=self.success) class HttpResponseContext(object): - """Response context for triggers raised by a HTTP request.""" - - def __init__(self, headers: Dict[str, str] = None, status: int = 200): - """Create a HTTP response context.""" - if headers is None: - self.headers = {} - else: - self.headers = headers + def __init__(self, headers: Dict[str, str] = {}, status: int = 200): + self.headers = headers self.status = status - def to_grpc_http_response_context(self) -> faas_pb2.HttpResponseContext: - """Translate a HTTP response context for on wire transport.""" - return faas_pb2.HttpResponseContext(headers=self.headers, status=self.status) + def to_grpc_http_response_context(self) -> HttpResponseContext: + return HttpResponseContext(headers=self.headers, status=self.status) class ResponseContext(object): - """Wrapper for typed response context for triggers.""" - def __init__(self, context: Union[TopicResponseContext, HttpResponseContext]): - """Create a new response context wrapper.""" self.context = context def is_http(self): - """ - Determine if response is for a HTTP request. - - :return true if context is for a HTTP request. - """ return isinstance(self.context, HttpResponseContext) def is_topic(self): - """ - Determine if response is for an event raised by a topic. - - :return true if context is for a topic event. - """ return isinstance(self.context, TopicResponseContext) def as_http(self) -> Union[HttpResponseContext, None]: - """ - Unwraps response context as Http response context. - - :return HttpResponseContext if is_http is true otherwise return None - """ if not self.is_http(): return None return self.context def as_topic(self) -> Union[TopicResponseContext, None]: - """ - Unwraps response context as Topic response context. - - :return TopicResponseContext if is_topic is true otherwise return None - """ + """Determine is ResponseContext is for a topic""" if not self.is_topic(): return None @@ -109,14 +75,15 @@ def __init__( self.data = data def to_grpc_trigger_response_context(self) -> TriggerResponse: - """Translate a response object ready for on the wire transport.""" + """Translate a response object ready for on the wire transport""" + response = TriggerResponse(data=self.data) if self.context.is_http(): ctx = self.context.as_http() - response.http.CopyFrom(ctx.to_grpc_http_response_context()) + response.http = ctx.to_grpc_http_response_context() elif self.context.is_topic(): ctx = self.context.as_topic() - response.topic.CopyFrom(ctx.to_grpc_topic_response_context()) + response.topic = ctx.to_grpc_topic_response_context() return response diff --git a/nitric/faas/trigger.py b/nitric/faas/trigger.py index 4a0b04e..99c31e0 100644 --- a/nitric/faas/trigger.py +++ b/nitric/faas/trigger.py @@ -24,27 +24,25 @@ class HttpTriggerContext(object): - """Represents Trigger metadata from a HTTP subscription.""" + """Represents Trigger metadata from a HTTP subscription""" def __init__( self, method: str, - path: str, headers: typing.Dict[str, str], + path_params: typing.Dict[str, str], query_params: typing.Dict[str, str], ): - """Create a Http trigger context.""" self.method = method - self.path = path self.headers = headers + self.path_params = path_params self.query_params = query_params class TopicTriggerContext(object): - """Represents Trigger metadata from a topic subscription.""" + """Represents Trigger metadata from a topic subscription""" def __init__(self, topic: str): - """Create a Topic trigger context.""" self.topic = topic @@ -56,38 +54,18 @@ def __init__(self, context: typing.Union[TopicTriggerContext, HttpTriggerContext self.context = context def is_http(self) -> bool: - """ - Determine if trigger was raised by a http request. - - :return true if trigger was raised by a HTTP request - """ return isinstance(self.context, HttpTriggerContext) def as_http(self) -> typing.Union[HttpTriggerContext, None]: - """ - Unwrap HttpTriggerContext. - - :return HttpTriggerContext if is_http is true otherwise None - """ if not self.is_http(): return None return self.context def is_topic(self) -> bool: - """ - Determine if trigger was raised by a topic event. - - :return true if trigger is for a topic event - """ return isinstance(self.context, TriggerContext) def as_topic(self) -> typing.Union[TopicTriggerContext, None]: - """ - Unwrap TopicTriggerContext. - - :return TopicTriggerContext if is_topic is true otherwise None - """ if not self.is_topic(): return None @@ -95,18 +73,13 @@ def as_topic(self) -> typing.Union[TopicTriggerContext, None]: @staticmethod def from_trigger_request(trigger_request: TriggerRequest): - """ - Create a TriggerContext from a gRPC TriggerRequest. - - :return Created TriggerContext - """ if trigger_request.http is not None: return TriggerContext( context=HttpTriggerContext( - headers=dict(trigger_request.http.headers), - path=trigger_request.http.path, + headers=trigger_request.http.headers, method=trigger_request.http.method, - query_params=dict(trigger_request.http.query_params), + query_params=trigger_request.http.query_params, + path_params=trigger_request.http.path_params, ) ) elif trigger_request.topic is not None: @@ -117,6 +90,11 @@ def from_trigger_request(trigger_request: TriggerRequest): return None +def _clean_header(header_name: str): + """Convert a Nitric HTTP request header name into the equivalent Context property name.""" + return header_name.lower().replace("x-nitric-", "").replace("-", "_") + + class Trigger(object): """ Represents a standard Nitric function request. @@ -147,12 +125,9 @@ def get_object(self) -> dict: def default_response(self) -> Response: """ - Create a relevant default response. - + Convenience method to construct a relevant default response The returned response can be interrogated with its context to determine the appropriate - response context e.g. response.context.is_http() or response.context.is_topic(). - - :returns Default response for this Trigger + response context e.g. response.context.is_http() or response.context.is_topic() """ response_ctx = None @@ -165,11 +140,6 @@ def default_response(self) -> Response: @staticmethod def from_trigger_request(trigger_request: TriggerRequest): - """ - Create a Trigger from a gRPC TriggerRequest. - - :returns Created Trigger - """ context = TriggerContext.from_trigger_request(trigger_request) return Trigger(context=context, data=trigger_request.data) diff --git a/nitric/proto/faas/__init__.py b/nitric/proto/faas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nitric/proto/faas/v1/__init__.py b/nitric/proto/faas/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/faas/test_request.py b/tests/faas/test_request.py new file mode 100644 index 0000000..7b5a444 --- /dev/null +++ b/tests/faas/test_request.py @@ -0,0 +1,111 @@ +# +# Copyright (c) 2021 Nitric Technologies Pty Ltd. +# +# This file is part of Nitric Python 3 SDK. +# See https://github.com/nitrictech/python-sdk for further info. +# +# Licensed 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. +# +from json.decoder import JSONDecodeError + +from nitric.faas.trigger import _clean_header, Request +from unittest.mock import patch, Mock +import unittest + + +class RequestCases(unittest.TestCase): + def test_clean_header(self): + test_headers = [ + # Input, Expected Output + ("x-nitric-test-prop", "test_prop"), + ("X-NITRIC-ALL-CAPS-PROP", "all_caps_prop"), + ("x-not-nitric-prop", "x_not_nitric_prop"), + ] + + for header in test_headers: + cleaned = _clean_header(header[0]) + assert cleaned == header[1] + + def test_headers_are_cleaned_in_request(self): + test_headers = { + "x-nitric-request-id": "abc123", + "x-nitric-source": "some.source", + "x-nitric-source-type": "REQUEST", + "x-nitric-payload-type": "com.example.payload.type", + } + + mock_clean_headers = Mock() + mock_clean_headers.side_effect = [ + "request_id", + "source", + "source_type", + "payload_type", + ] + with patch("nitric.faas.request._clean_header", mock_clean_headers): + request = Request(test_headers, b"test content") + mock_clean_headers.assert_called_with("x-nitric-payload-type") + + def test_mime_canon_headers_are_cleaned_in_request(self): + test_headers = { + "X-Nitric-Request-Id": "abc123", + "X-Nitric-Source": "some.source", + "X-Nitric-Source-Type": "REQUEST", + "X-Nitric-Payload-Type": "com.example.payload.type", + } + + mock_clean_headers = Mock() + mock_clean_headers.side_effect = [ + "request_id", + "source", + "source_type", + "payload_type", + ] + with patch("nitric.faas.request._clean_header", mock_clean_headers): + request = Request(test_headers, b"test content") + mock_clean_headers.assert_called_with("X-Nitric-Payload-Type") + + def test_unsupported_headers_ignored(self): + test_headers = { + "x-nitric-request-id": "abc123", + "x-nitric-source": "some.source", + "x-nitric-source-type": "REQUEST", + "x-nitric-payload-type": "com.example.payload.type", + "x-nitric-unknown-header": "should be ignored", + } + + request = Request(test_headers, b"test content") + # Make sure the unknown header didn't end up in the context and no errors are thrown. + assert len([key for key in request.context.__dict__.keys() if "unknown" in key]) == 0 + + def test_get_object(self): + test_headers = { + "x-nitric-request-id": "abc123", + "x-nitric-source": "some.source", + "x-nitric-source-type": "REQUEST", + "x-nitric-payload-type": "com.example.payload.type", + "x-nitric-unknown-header": "should be ignored", + } + request = Request(headers=test_headers, payload=b'{"name": "John"}') + assert request.get_object()["name"] == "John" + + def test_get_object_with_invalid_payload_json(self): + test_headers = { + "x-nitric-request-id": "abc123", + "x-nitric-source": "some.source", + "x-nitric-source-type": "REQUEST", + "x-nitric-payload-type": "com.example.payload.type", + "x-nitric-unknown-header": "should be ignored", + } + # Missing beginning " before "name" property. + request = Request(headers=test_headers, payload=b'{name": "John"}') + self.assertRaises(JSONDecodeError, request.get_object) From 5e5baf95847337a2c781a017e0c294879042652e Mon Sep 17 00:00:00 2001 From: Tim Holm Date: Tue, 15 Jun 2021 09:50:06 +1000 Subject: [PATCH 07/33] wip: Working Python gRPC FaaS PoC. --- nitric/faas/__init__.py | 2 +- nitric/faas/faas.py | 22 +++++++++++----------- nitric/faas/response.py | 15 ++++++++------- 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/nitric/faas/__init__.py b/nitric/faas/__init__.py index 26d0199..02f9ff3 100644 --- a/nitric/faas/__init__.py +++ b/nitric/faas/__init__.py @@ -17,7 +17,7 @@ # limitations under the License. # """Nitric Function as a Service (FaaS) Package.""" -from nitric.faas.trigger import Request, Context, SourceType +from nitric.faas.trigger import TriggerRequest, TriggerContext from nitric.faas.response import Response from nitric.faas.faas import start diff --git a/nitric/faas/faas.py b/nitric/faas/faas.py index a7efce6..fc881a8 100644 --- a/nitric/faas/faas.py +++ b/nitric/faas/faas.py @@ -16,10 +16,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Awaitable, Coroutine, Callable, Union +from typing import Callable, Union from nitric.config import settings -from nitric.faas import Request, Response +from nitric.faas import TriggerRequest, Response from grpc import aio from nitric.faas.trigger import Trigger @@ -32,9 +32,7 @@ def get_stream(stub: faas_pb2_grpc.FaasStub) -> aio.StreamStreamCall[faas_pb2.Cl return stub.TriggerStream() -async def loop( - func: Union[Callable[[Request], Union[Response, str]], Coroutine[Awaitable[Union[str, Response]], Request]] -): +async def loop(func: Union[Callable[[TriggerRequest], Union[Response, str]]]): """FaaS loop""" async with aio.insecure_channel(settings.SERVICE_BIND) as channel: stub = faas_pb2_grpc.FaasStub(channel) @@ -56,13 +54,13 @@ async def loop( # Break the loop break - if msg.init_response is not None: + if msg.HasField("init_response"): # Handle the init response print("Function connected to Membrane") # We don't need to reply # Time to go to the next available message continue - elif msg.trigger_request is not None: + elif msg.HasField("trigger_request"): client_msg = faas_pb2.ClientMessage( id=msg.id, ) @@ -74,17 +72,19 @@ async def loop( # This will allow the user to define non-blocking I/O within the scope # of their function allowing the runtime to queue up more requests if asyncio.iscoroutinefunction(func): + print("call non-blocking") response = await func(trigger) else: response = func(trigger) + print("call blocking") if isinstance(response, Response): - client_msg.trigger_response = response.to_grpc_trigger_response_context() + client_msg.trigger_response.CopyFrom(response.to_grpc_trigger_response_context()) elif isinstance(response, str): # Construct a default response from the data default_response = trigger.default_response() default_response.data = response.encode() - client_msg.trigger_response = default_response + client_msg.trigger_response.CopyFrom(default_response.to_grpc_trigger_response_context()) # translate the response except Exception: @@ -100,7 +100,7 @@ async def loop( topic_context = default_response.context.as_topic() topic_context.success = False - client_msg.trigger_response = default_response.to_grpc_trigger_response_context() + client_msg.trigger_response.CopyFrom(default_response.to_grpc_trigger_response_context()) # Write it back to the server await stream.write(client_msg) @@ -110,7 +110,7 @@ async def loop( # TODO: We need to change this to an Awaitable or a Coroutine -def start(func: Union[Callable[[Request], Union[Response, str]], Coroutine[Awaitable[Union[str, Response]], Request]]): +def start(func: Union[Callable[[TriggerRequest], Union[Response, str]]]): """ Register the provided function as the request handler and starts handling new requests. diff --git a/nitric/faas/response.py b/nitric/faas/response.py index 408a462..61482cf 100644 --- a/nitric/faas/response.py +++ b/nitric/faas/response.py @@ -17,15 +17,16 @@ # limitations under the License. # from typing import Union, Dict -from nitric.proto.faas.v1.faas_pb2 import TriggerResponse, HttpResponseContext, TopicResponseContext +from nitric.proto.faas.v1 import faas_pb2 +from nitric.proto.faas.v1.faas_pb2 import TriggerResponse class TopicResponseContext(object): def __init__(self, success: bool = True): self.success = success - def to_grpc_topic_response_context(self) -> TopicResponseContext: - return TopicResponseContext(success=self.success) + def to_grpc_topic_response_context(self) -> faas_pb2.TopicResponseContext: + return faas_pb2.TopicResponseContext(success=self.success) class HttpResponseContext(object): @@ -33,8 +34,8 @@ def __init__(self, headers: Dict[str, str] = {}, status: int = 200): self.headers = headers self.status = status - def to_grpc_http_response_context(self) -> HttpResponseContext: - return HttpResponseContext(headers=self.headers, status=self.status) + def to_grpc_http_response_context(self) -> faas_pb2.HttpResponseContext: + return faas_pb2.HttpResponseContext(headers=self.headers, status=self.status) class ResponseContext(object): @@ -81,9 +82,9 @@ def to_grpc_trigger_response_context(self) -> TriggerResponse: if self.context.is_http(): ctx = self.context.as_http() - response.http = ctx.to_grpc_http_response_context() + response.http.CopyFrom(ctx.to_grpc_http_response_context()) elif self.context.is_topic(): ctx = self.context.as_topic() - response.topic = ctx.to_grpc_topic_response_context() + response.topic.CopyFrom(ctx.to_grpc_topic_response_context()) return response From 2d4e23de78b121ebaf494fd5059a422aed6c8fe7 Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Wed, 30 Jun 2021 15:18:11 +1000 Subject: [PATCH 08/33] chore: ignore asyncio license It's marked as UNKNOWN, but it's really Apache 2, so that's fine. --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 5e4be78..c6195b8 100644 --- a/tox.ini +++ b/tox.ini @@ -20,7 +20,7 @@ commands = flake8 nitric black nitric tests tools pydocstyle nitric - pip-licenses --allow-only="MIT License;BSD License;Zope Public License;Python Software Foundation License;Apache License 2.0;Apache Software License;MIT License, Mozilla Public License 2.0 (MPL 2.0);MIT;BSD License, Apache Software License;3-Clause BSD License;Historical Permission Notice and Disclaimer (HPND);Mozilla Public License 2.0 (MPL 2.0);Apache Software License, BSD License;BSD;Python Software Foundation License, MIT License;Public Domain;Public Domain, Python Software Foundation License, BSD License, GNU General Public License (GPL);GNU Library or Lesser General Public License (LGPL);LGPL;Apache Software License, MIT License" --ignore-packages nitric + pip-licenses --allow-only="MIT License;BSD License;Zope Public License;Python Software Foundation License;Apache License 2.0;Apache Software License;MIT License, Mozilla Public License 2.0 (MPL 2.0);MIT;BSD License, Apache Software License;3-Clause BSD License;Historical Permission Notice and Disclaimer (HPND);Mozilla Public License 2.0 (MPL 2.0);Apache Software License, BSD License;BSD;Python Software Foundation License, MIT License;Public Domain;Public Domain, Python Software Foundation License, BSD License, GNU General Public License (GPL);GNU Library or Lesser General Public License (LGPL);LGPL;Apache Software License, MIT License" --ignore-packages nitric asyncio [flake8] From 522ec952b67feaf27a9f2b9e39471103b56c37a7 Mon Sep 17 00:00:00 2001 From: Jye Cusch Date: Wed, 30 Jun 2021 15:28:54 +1000 Subject: [PATCH 09/33] feat: port faas.start to bi-di streaming with membrane Support bi-directional streaming of triggers and responses to the Membrane and remove reliance on HTTP servers and frameworks. --- docs/nitric/api/events.html | 370 +++++++ docs/nitric/api/index.html | 660 ++++-------- docs/nitric/api/kv.html | 131 +-- docs/nitric/api/models.html | 271 ----- docs/nitric/api/queue.html | 437 -------- docs/nitric/api/queues.html | 615 +++++++++++ docs/nitric/api/storage.html | 297 ++++-- docs/nitric/faas/faas.html | 266 ++--- docs/nitric/faas/index.html | 377 +++---- docs/nitric/faas/request.html | 344 ------ docs/nitric/faas/response.html | 306 +++--- docs/nitric/faas/trigger.html | 295 +++--- docs/nitric/index.html | 5 + docs/nitric/proto/auth/v1/auth_pb2.html | 309 ------ docs/nitric/proto/auth/v1/auth_pb2_grpc.html | 335 ------ docs/nitric/proto/auth/v1/index.html | 93 -- .../nitric/proto/event/v1/event_pb2_grpc.html | 573 ---------- docs/nitric/proto/event/v1/index.html | 93 -- docs/nitric/proto/faas/v1/faas_pb2_grpc.html | 335 ------ docs/nitric/proto/faas/v1/index.html | 93 -- docs/nitric/proto/index.html | 45 +- docs/nitric/proto/kv/v1/index.html | 93 -- docs/nitric/proto/kv/v1/kv_pb2_grpc.html | 563 ---------- .../proto/{ => nitric}/event/index.html | 10 +- docs/nitric/proto/nitric/event/v1/index.html | 661 ++++++++++++ .../proto/{kv => nitric/faas}/index.html | 10 +- docs/nitric/proto/nitric/faas/v1/index.html | 777 ++++++++++++++ docs/nitric/proto/nitric/index.html | 108 ++ .../proto/{faas => nitric/kv}/index.html | 10 +- docs/nitric/proto/nitric/kv/v1/index.html | 700 ++++++++++++ .../proto/{auth => nitric/queue}/index.html | 10 +- docs/nitric/proto/nitric/queue/v1/index.html | 992 ++++++++++++++++++ docs/nitric/proto/nitric/storage/index.html | 88 ++ .../nitric/proto/nitric/storage/v1/index.html | 698 ++++++++++++ docs/nitric/proto/queue/index.html | 88 -- docs/nitric/proto/queue/v1/index.html | 93 -- .../nitric/proto/queue/v1/queue_pb2_grpc.html | 677 ------------ docs/nitric/proto/storage/index.html | 88 -- .../proto/storage/v1/storage_pb2_grpc.html | 563 ---------- .../storage/v1/index.html => utils.html} | 102 +- nitric/api/events.py | 5 +- nitric/api/kv.py | 2 +- nitric/api/queues.py | 13 +- nitric/api/storage.py | 8 +- nitric/faas/__init__.py | 4 +- nitric/faas/faas.py | 148 ++- nitric/faas/response.py | 71 +- nitric/faas/trigger.py | 72 +- nitric/proto/faas/__init__.py | 0 nitric/proto/faas/v1/__init__.py | 0 nitric/{api/_utils.py => utils.py} | 20 +- setup.py | 7 +- tests/api/test_event_client.py | 2 +- tests/api/test_queue_client.py | 2 +- tests/api/test_storage_client.py | 3 - tests/faas/test_request.py | 111 -- tests/test__utils.py | 20 +- 57 files changed, 6417 insertions(+), 6652 deletions(-) create mode 100644 docs/nitric/api/events.html delete mode 100644 docs/nitric/api/models.html delete mode 100644 docs/nitric/api/queue.html create mode 100644 docs/nitric/api/queues.html delete mode 100644 docs/nitric/faas/request.html delete mode 100644 docs/nitric/proto/auth/v1/auth_pb2.html delete mode 100644 docs/nitric/proto/auth/v1/auth_pb2_grpc.html delete mode 100644 docs/nitric/proto/auth/v1/index.html delete mode 100644 docs/nitric/proto/event/v1/event_pb2_grpc.html delete mode 100644 docs/nitric/proto/event/v1/index.html delete mode 100644 docs/nitric/proto/faas/v1/faas_pb2_grpc.html delete mode 100644 docs/nitric/proto/faas/v1/index.html delete mode 100644 docs/nitric/proto/kv/v1/index.html delete mode 100644 docs/nitric/proto/kv/v1/kv_pb2_grpc.html rename docs/nitric/proto/{ => nitric}/event/index.html (93%) create mode 100644 docs/nitric/proto/nitric/event/v1/index.html rename docs/nitric/proto/{kv => nitric/faas}/index.html (93%) create mode 100644 docs/nitric/proto/nitric/faas/v1/index.html create mode 100644 docs/nitric/proto/nitric/index.html rename docs/nitric/proto/{faas => nitric/kv}/index.html (93%) create mode 100644 docs/nitric/proto/nitric/kv/v1/index.html rename docs/nitric/proto/{auth => nitric/queue}/index.html (93%) create mode 100644 docs/nitric/proto/nitric/queue/v1/index.html create mode 100644 docs/nitric/proto/nitric/storage/index.html create mode 100644 docs/nitric/proto/nitric/storage/v1/index.html delete mode 100644 docs/nitric/proto/queue/index.html delete mode 100644 docs/nitric/proto/queue/v1/index.html delete mode 100644 docs/nitric/proto/queue/v1/queue_pb2_grpc.html delete mode 100644 docs/nitric/proto/storage/index.html delete mode 100644 docs/nitric/proto/storage/v1/storage_pb2_grpc.html rename docs/nitric/{proto/storage/v1/index.html => utils.html} (64%) delete mode 100644 nitric/proto/faas/__init__.py delete mode 100644 nitric/proto/faas/v1/__init__.py rename nitric/{api/_utils.py => utils.py} (71%) delete mode 100644 tests/faas/test_request.py diff --git a/docs/nitric/api/events.html b/docs/nitric/api/events.html new file mode 100644 index 0000000..b1af7bd --- /dev/null +++ b/docs/nitric/api/events.html @@ -0,0 +1,370 @@ + + + + + + +nitric.api.events API documentation + + + + + + + + + + + +
+
+
+

Module nitric.api.events

+
+
+
+ +Expand source code + +
#
+# Copyright (c) 2021 Nitric Technologies Pty Ltd.
+#
+# This file is part of Nitric Python 3 SDK.
+# See https://github.com/nitrictech/python-sdk for further info.
+#
+# Licensed 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.
+#
+from typing import List, Union
+from nitric.utils import new_default_channel, _struct_from_dict
+from nitric.proto.nitric.event.v1 import EventStub, NitricEvent, TopicStub
+from dataclasses import dataclass, field
+
+
+@dataclass(frozen=True, order=True)
+class Event(object):
+    """Represents a NitricEvent."""
+
+    payload: dict = field(default_factory=dict)
+    id: str = field(default=None)
+    payload_type: str = field(default=None)
+
+
+def _event_to_wire(event: Event) -> NitricEvent:
+    return NitricEvent(
+        id=event.id,
+        payload=_struct_from_dict(event.payload),
+        payload_type=event.payload_type,
+    )
+
+
+@dataclass(frozen=True, order=True)
+class Topic(object):
+    """A reference to a topic on an event service, used to perform operations on that topic."""
+
+    _stub: EventStub
+    name: str
+
+    async def publish(
+        self,
+        event: Union[Event, dict] = None,
+    ) -> Event:
+        """
+        Publish an event/message to a topic, which can be subscribed to by other services.
+
+        :param event: the event to publish
+        :return: the published event, with the id added if one was auto-generated
+        """
+        if event is None:
+            event = Event()
+
+        if isinstance(event, dict):
+            # TODO: handle events that are just a payload
+            event = Event(**event)
+
+        response = await self._stub.publish(topic=self.name, event=_event_to_wire(event))
+        return Event(**{**event.__dict__.copy(), **{"id": response.id}})
+
+
+class EventClient(object):
+    """
+    Nitric generic publish/subscribe event client.
+
+    This client insulates application code from stack specific event operations or SDKs.
+    """
+
+    def __init__(self):
+        """Construct a Nitric Event Client."""
+        channel = new_default_channel()
+        self._stub = EventStub(channel=channel)
+        self._topic_stub = TopicStub(channel=channel)
+
+    async def topics(self) -> List[Topic]:
+        """Get a list of topics available for publishing or subscription."""
+        response = await self._topic_stub.list()
+        return [self.topic(topic.name) for topic in response.topics]
+
+    def topic(self, name: str) -> Topic:
+        """Return a reference a topic from the connected event service."""
+        return Topic(_stub=self._stub, name=name)
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Event +(payload: dict = <factory>, id: str = None, payload_type: str = None) +
+
+

Represents a NitricEvent.

+
+ +Expand source code + +
class Event(object):
+    """Represents a NitricEvent."""
+
+    payload: dict = field(default_factory=dict)
+    id: str = field(default=None)
+    payload_type: str = field(default=None)
+
+

Class variables

+
+
var id : str
+
+
+
+
var payload : dict
+
+
+
+
var payload_type : str
+
+
+
+
+
+
+class EventClient +
+
+

Nitric generic publish/subscribe event client.

+

This client insulates application code from stack specific event operations or SDKs.

+

Construct a Nitric Event Client.

+
+ +Expand source code + +<<<<<<< refs/remotes/origin/main:docs/nitric/api/models.html +
class FailedTask(Task):
+    """Represents a failed queue publish for an event."""
+=======
+
class EventClient(object):
+    """
+    Nitric generic publish/subscribe event client.
+
+    This client insulates application code from stack specific event operations or SDKs.
+    """
+
+    def __init__(self):
+        """Construct a Nitric Event Client."""
+        channel = new_default_channel()
+        self._stub = EventStub(channel=channel)
+        self._topic_stub = TopicStub(channel=channel)
+>>>>>>> feat: port faas.start to bi-di streaming with membrane:docs/nitric/api/events.html
+
+    async def topics(self) -> List[Topic]:
+        """Get a list of topics available for publishing or subscription."""
+        response = await self._topic_stub.list()
+        return [self.topic(topic.name) for topic in response.topics]
+
+    def topic(self, name: str) -> Topic:
+        """Return a reference a topic from the connected event service."""
+        return Topic(_stub=self._stub, name=name)
+
+

Methods

+
+
+def topic(self, name: str) ‑> Topic +
+
+

Return a reference a topic from the connected event service.

+
+ +Expand source code + +
def topic(self, name: str) -> Topic:
+    """Return a reference a topic from the connected event service."""
+    return Topic(_stub=self._stub, name=name)
+
+
+
+async def topics(self) ‑> List[Topic] +
+
+

Get a list of topics available for publishing or subscription.

+
+ +Expand source code + +
async def topics(self) -> List[Topic]:
+    """Get a list of topics available for publishing or subscription."""
+    response = await self._topic_stub.list()
+    return [self.topic(topic.name) for topic in response.topics]
+
+
+
+
+
+class Topic +(_stub: EventStub, name: str) +
+
+

A reference to a topic on an event service, used to perform operations on that topic.

+
+ +Expand source code + +<<<<<<< refs/remotes/origin/main:docs/nitric/api/models.html +
class Task(object):
+    """Represents a NitricTask."""
+=======
+
class Topic(object):
+    """A reference to a topic on an event service, used to perform operations on that topic."""
+
+    _stub: EventStub
+    name: str
+
+    async def publish(
+        self,
+        event: Union[Event, dict] = None,
+    ) -> Event:
+        """
+        Publish an event/message to a topic, which can be subscribed to by other services.
+
+        :param event: the event to publish
+        :return: the published event, with the id added if one was auto-generated
+        """
+        if event is None:
+            event = Event()
+
+        if isinstance(event, dict):
+            # TODO: handle events that are just a payload
+            event = Event(**event)
+>>>>>>> feat: port faas.start to bi-di streaming with membrane:docs/nitric/api/events.html
+
+        response = await self._stub.publish(topic=self.name, event=_event_to_wire(event))
+        return Event(**{**event.__dict__.copy(), **{"id": response.id}})
+
+

Class variables

+
+
var name : str
+
+
+
+
+

Methods

+
+
+async def publish(self, event: Union[Event, dict] = None) ‑> Event +
+
+

Publish an event/message to a topic, which can be subscribed to by other services.

+

:param event: the event to publish +:return: the published event, with the id added if one was auto-generated

+
+ +Expand source code + +<<<<<<< refs/remotes/origin/main:docs/nitric/api/models.html +
class Topic(object):
+    """Represents event topic metadata."""
+=======
+
async def publish(
+    self,
+    event: Union[Event, dict] = None,
+) -> Event:
+    """
+    Publish an event/message to a topic, which can be subscribed to by other services.
+
+    :param event: the event to publish
+    :return: the published event, with the id added if one was auto-generated
+    """
+    if event is None:
+        event = Event()
+
+    if isinstance(event, dict):
+        # TODO: handle events that are just a payload
+        event = Event(**event)
+>>>>>>> feat: port faas.start to bi-di streaming with membrane:docs/nitric/api/events.html
+
+    response = await self._stub.publish(topic=self.name, event=_event_to_wire(event))
+    return Event(**{**event.__dict__.copy(), **{"id": response.id}})
+
+
+
+
+
+
+
+ +
+ + + \ No newline at end of file diff --git a/docs/nitric/api/index.html b/docs/nitric/api/index.html index 2590509..4000717 100644 --- a/docs/nitric/api/index.html +++ b/docs/nitric/api/index.html @@ -46,15 +46,13 @@

Module nitric.api

# limitations under the License. # """Nitric API SDK.""" -from nitric.api.event import EventClient, TopicClient +from nitric.api.events import EventClient, Event, Topic from nitric.api.kv import KeyValueClient -from nitric.api.queue import QueueClient +from nitric.api.queues import QueueClient, Task, FailedTask from nitric.api.storage import StorageClient -from nitric.api.models import Event, Task, FailedTask, Topic __all__ = [ "EventClient", - "TopicClient", "KeyValueClient", "QueueClient", "StorageClient", @@ -68,7 +66,7 @@

Module nitric.api

Sub-modules

-
nitric.api.event
+
nitric.api.events
@@ -80,11 +78,7 @@

Sub-modules

-
nitric.api.models
-
-
-
-
nitric.api.queue
+
nitric.api.queues
@@ -103,7 +97,7 @@

Classes

class Event -(event_id: str, payload_type: str, payload: dict) +(payload: dict = <factory>, id: str = None, payload_type: str = None)

Represents a NitricEvent.

@@ -114,13 +108,13 @@

Classes

class Event(object):
     """Represents a NitricEvent."""
 
-    event_id: str
-    payload_type: str
-    payload: dict
+ payload: dict = field(default_factory=dict) + id: str = field(default=None) + payload_type: str = field(default=None)

Class variables

-
var event_id : str
+
var id : str
@@ -145,7 +139,7 @@

Class variables

Expand source code -
class EventClient(BaseClient):
+
class EventClient(object):
     """
     Nitric generic publish/subscribe event client.
 
@@ -154,86 +148,55 @@ 

Class variables

def __init__(self): """Construct a Nitric Event Client.""" - super(self.__class__, self).__init__() - self._stub = event_service.EventStub(self._channel) + channel = new_default_channel() + self._stub = EventStub(channel=channel) + self._topic_stub = TopicStub(channel=channel) - def publish( - self, - topic_name: str, - payload: dict = None, - payload_type: str = "", - event_id: str = None, - ) -> str: - """ - Publish an event/message to a topic, which can be subscribed to by other services. + async def topics(self) -> List[Topic]: + """Get a list of topics available for publishing or subscription.""" + response = await self._topic_stub.list() + return [self.topic(topic.name) for topic in response.topics] - :param topic_name: the name of the topic to publish to - :param payload: content of the message to send - :param payload_type: fully qualified name of the event payload type, e.g. io.nitric.example.customer.created - :param event_id: a unique id, used to ensure idempotent processing of events. Defaults to a version 4 UUID. - :return: the request id on successful publish - """ - if payload is None: - payload = {} - payload_struct = Struct() - payload_struct.update(payload) - nitric_event = NitricEvent(id=event_id, payload_type=payload_type, payload=payload_struct) - request = event_model.EventPublishRequest(topic=topic_name, event=nitric_event) - self._exec("Publish", request) - return event_id
+ def topic(self, name: str) -> Topic: + """Return a reference a topic from the connected event service.""" + return Topic(_stub=self._stub, name=name)
-

Ancestors

-
    -
  • nitric.api._base_client.BaseClient
  • -
  • abc.ABC
  • -

Methods

-
-def publish(self, topic_name: str, payload: dict = None, payload_type: str = '', event_id: str = None) ‑> str +
+def topic(self, name: str) ‑> Topic
-

Publish an event/message to a topic, which can be subscribed to by other services.

-

:param topic_name: the name of the topic to publish to -:param payload: content of the message to send -:param payload_type: fully qualified name of the event payload type, e.g. io.nitric.example.customer.created -:param event_id: a unique id, used to ensure idempotent processing of events. Defaults to a version 4 UUID. -:return: the request id on successful publish

+

Return a reference a topic from the connected event service.

Expand source code -
def publish(
-    self,
-    topic_name: str,
-    payload: dict = None,
-    payload_type: str = "",
-    event_id: str = None,
-) -> str:
-    """
-    Publish an event/message to a topic, which can be subscribed to by other services.
-
-    :param topic_name: the name of the topic to publish to
-    :param payload: content of the message to send
-    :param payload_type: fully qualified name of the event payload type, e.g. io.nitric.example.customer.created
-    :param event_id: a unique id, used to ensure idempotent processing of events. Defaults to a version 4 UUID.
-    :return: the request id on successful publish
-    """
-    if payload is None:
-        payload = {}
-    payload_struct = Struct()
-    payload_struct.update(payload)
-    nitric_event = NitricEvent(id=event_id, payload_type=payload_type, payload=payload_struct)
-    request = event_model.EventPublishRequest(topic=topic_name, event=nitric_event)
-    self._exec("Publish", request)
-    return event_id
+
def topic(self, name: str) -> Topic:
+    """Return a reference a topic from the connected event service."""
+    return Topic(_stub=self._stub, name=name)
+
+
+
+async def topics(self) ‑> List[Topic] +
+
+

Get a list of topics available for publishing or subscription.

+
+ +Expand source code + +
async def topics(self) -> List[Topic]:
+    """Get a list of topics available for publishing or subscription."""
+    response = await self._topic_stub.list()
+    return [self.topic(topic.name) for topic in response.topics]
class FailedTask -(task_id: str, payload_type: str, payload: dict, lease_id: str = None, message: str = '') +(id: str = None, payload_type: str = None, payload: dict = <factory>, lease_id: str = None, message: str = '')

Represents a failed queue publish for an event.

@@ -244,71 +207,79 @@

Methods

class FailedTask(Task):
     """Represents a failed queue publish for an event."""
 
+    lease_id: str = None  # failed tasks should never have a lease id.
     message: str = field(default="")

Ancestors

Class variables

+
var lease_id : str
+
+
+
var message : str
+

Inherited members

+
class KeyValueClient +(collection: str)

Nitric generic document store/db client.

This client insulates application code from stack specific document CRUD operations or SDKs.

-

Construct a new DocumentClient.

+

Construct a new DocumentClient.

+

:param collection: name of the key/value collection

Expand source code -
class KeyValueClient(BaseClient):
+
class KeyValueClient(object):
     """
     Nitric generic document store/db client.
 
     This client insulates application code from stack specific document CRUD operations or SDKs.
     """
 
-    def __init__(self):
-        """Construct a new DocumentClient."""
-        super(self.__class__, self).__init__()
-        self._stub = key_value_service.KeyValueStub(self._channel)
+    def __init__(self, collection: str):
+        """
+        Construct a new DocumentClient.
+
+        :param collection: name of the key/value collection
+        """
+        self.collection = collection
+        self._stub = KeyValueStub(channel=new_default_channel())
 
-    def put(self, collection: str, key: str, value: dict):
-        """Create a new document with the specified key in the specified collection."""
-        value_struct = Struct()
-        value_struct.update(value)
-        request = key_value.KeyValuePutRequest(collection=collection, key=key, value=value_struct)
-        return self._exec("Put", request)
+    async def put(self, key: str, value: dict):
+        """Create a new document with the specified key."""
+        await self._stub.put(collection=self.collection, key=key, value=_struct_from_dict(value))
 
-    def get(self, collection: str, key: str) -> dict:
-        """Retrieve a document from the specified collection by its key."""
-        request = key_value.KeyValueGetRequest(collection=collection, key=key)
-        reply: KeyValueGetResponse = self._exec("Get", request)
-        document = MessageToDict(reply)["value"]
-        return document
+    async def get(self, key: str) -> dict:
+        """Retrieve a document from the specified key."""
+        response = await self._stub.get(collection=self.collection, key=key)
+        return response.value.to_dict()
 
-    def delete(self, collection: str, key: str):
+    async def delete(self, key: str):
         """Delete the specified document from the collection."""
-        request = key_value.KeyValueDeleteRequest(collection=collection, key=key)
-        return self._exec("Delete", request)
+ await self._stub.delete(collection=self.collection, key=key)
-

Ancestors

-
    -
  • nitric.api._base_client.BaseClient
  • -
  • abc.ABC
  • -

Methods

-def delete(self, collection: str, key: str) +async def delete(self, key: str)

Delete the specified document from the collection.

@@ -316,44 +287,38 @@

Methods

Expand source code -
def delete(self, collection: str, key: str):
+
async def delete(self, key: str):
     """Delete the specified document from the collection."""
-    request = key_value.KeyValueDeleteRequest(collection=collection, key=key)
-    return self._exec("Delete", request)
+ await self._stub.delete(collection=self.collection, key=key)
-def get(self, collection: str, key: str) ‑> dict +async def get(self, key: str) ‑> dict
-

Retrieve a document from the specified collection by its key.

+

Retrieve a document from the specified key.

Expand source code -
def get(self, collection: str, key: str) -> dict:
-    """Retrieve a document from the specified collection by its key."""
-    request = key_value.KeyValueGetRequest(collection=collection, key=key)
-    reply: KeyValueGetResponse = self._exec("Get", request)
-    document = MessageToDict(reply)["value"]
-    return document
+
async def get(self, key: str) -> dict:
+    """Retrieve a document from the specified key."""
+    response = await self._stub.get(collection=self.collection, key=key)
+    return response.value.to_dict()
-def put(self, collection: str, key: str, value: dict) +async def put(self, key: str, value: dict)
-

Create a new document with the specified key in the specified collection.

+

Create a new document with the specified key.

Expand source code -
def put(self, collection: str, key: str, value: dict):
-    """Create a new document with the specified key in the specified collection."""
-    value_struct = Struct()
-    value_struct.update(value)
-    request = key_value.KeyValuePutRequest(collection=collection, key=key, value=value_struct)
-    return self._exec("Put", request)
+
async def put(self, key: str, value: dict):
+    """Create a new document with the specified key."""
+    await self._stub.put(collection=self.collection, key=key, value=_struct_from_dict(value))
@@ -369,7 +334,7 @@

Methods

Expand source code -
class QueueClient(BaseClient):
+
class QueueClient(object):
     """
     Nitric generic publish/subscribe tasking client.
 
@@ -378,184 +343,26 @@ 

Methods

def __init__(self): """Construct a Nitric Queue Client.""" - super(self.__class__, self).__init__() - self._stub = queue_service.QueueStub(self._channel) - - def _task_to_wire(self, task: Task) -> queue.NitricTask: - """ - Convert a Nitric Task to a Nitric Queue Task. + self._queue_stub = QueueStub(channel=new_default_channel()) - :param task: to convert - :return: converted task - """ - payload_struct = Struct() - payload_struct.update(task.payload) - - return queue.NitricTask( - id=task.task_id, - payload_type=task.payload_type, - payload=payload_struct, - ) - - def _wire_to_task(self, task: queue.NitricTask) -> Task: - """ - Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK). - - :param task: to convert - :return: converted task - """ - return Task( - task_id=task.id, - payload_type=task.payload_type, - payload=MessageToDict(task.payload), - lease_id=task.lease_id, - ) - - def _wire_to_failed_task(self, failed_task: queue.FailedTask) -> FailedTask: - """ - Convert a queue task that failed to push into a Failed Task object. - - :param failed_task: the failed task - :return: the Failed Task with failure message - """ - task = self._wire_to_task(failed_task.task) - - return FailedTask( - task_id=task.task_id, - payload_type=task.payload_type, - payload=task.payload, - lease_id=task.lease_id, - message=failed_task.message, - ) - - def send_batch(self, queue_name: str, tasks: List[Task] = None) -> PushResponse: - """ - Push a collection of tasks to a queue, which can be retrieved by other services. - - :param queue_name: the name of the queue to publish to - :param tasks: The tasks to push to the queue - :return: PushResponse containing a list containing details of any messages that failed to publish. - """ - if tasks is None: - tasks = [] - wire_tasks = map(self._task_to_wire, tasks) - - request = queue.QueueSendBatchRequest(queue=queue_name, tasks=wire_tasks) - - response: queue.QueueSendBatchResponse = self._exec("SendBatch", request) - - failed_tasks = map(self._wire_to_failed_task, response.failedMessages) - - return PushResponse(failed_tasks=list(failed_tasks)) - - def receive(self, queue_name: str, depth: int = None) -> List[Task]: - """ - Pop 1 or more items from the specified queue up to the depth limit. - - Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on. - Once complete or failed they must be acknowledged using the request specific leaseId. - - If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be - returned to the queue for reprocessing. - - :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific - identifier. - :param depth: The maximum number of queue items to return. Default: 1, Min: 1. - :return: Queue items popped from the specified queue. - """ - # Set the default and minimum depth to 1. - if depth is None or depth < 1: - depth = 1 - - request = queue.QueueReceiveRequest(queue=queue_name, depth=depth) - - response: queue.QueueReceiveResponse = self._exec("Receive", request) - - # Map the response protobuf response items to Python SDK Nitric Queue Items - return [self._wire_to_task(item) for item in response.items]
+ def queue(self, name: str): + """Return a reference to a queue from the connected queue service.""" + return Queue(_queue_stub=self._queue_stub, name=name)
-

Ancestors

-
    -
  • nitric.api._base_client.BaseClient
  • -
  • abc.ABC
  • -

Methods

-
-def receive(self, queue_name: str, depth: int = None) ‑> List[Task] +
+def queue(self, name: str)
-

Pop 1 or more items from the specified queue up to the depth limit.

-

Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on. -Once complete or failed they must be acknowledged using the request specific leaseId.

-

If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be -returned to the queue for reprocessing.

-

:param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific -identifier. -:param depth: The maximum number of queue items to return. Default: 1, Min: 1. -:return: Queue items popped from the specified queue.

+

Return a reference to a queue from the connected queue service.

Expand source code -
def receive(self, queue_name: str, depth: int = None) -> List[Task]:
-    """
-    Pop 1 or more items from the specified queue up to the depth limit.
-
-    Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
-    Once complete or failed they must be acknowledged using the request specific leaseId.
-
-    If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
-    returned to the queue for reprocessing.
-
-    :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific
-    identifier.
-    :param depth: The maximum number of queue items to return. Default: 1, Min: 1.
-    :return: Queue items popped from the specified queue.
-    """
-    # Set the default and minimum depth to 1.
-    if depth is None or depth < 1:
-        depth = 1
-
-    request = queue.QueueReceiveRequest(queue=queue_name, depth=depth)
-
-    response: queue.QueueReceiveResponse = self._exec("Receive", request)
-
-    # Map the response protobuf response items to Python SDK Nitric Queue Items
-    return [self._wire_to_task(item) for item in response.items]
-
-
-
-def send_batch(self, queue_name: str, tasks: List[Task] = None) ‑> PushResponse -
-
-

Push a collection of tasks to a queue, which can be retrieved by other services.

-

:param queue_name: the name of the queue to publish to -:param tasks: The tasks to push to the queue -:return: PushResponse containing a list containing details of any messages that failed to publish.

-
- -Expand source code - -
def send_batch(self, queue_name: str, tasks: List[Task] = None) -> PushResponse:
-    """
-    Push a collection of tasks to a queue, which can be retrieved by other services.
-
-    :param queue_name: the name of the queue to publish to
-    :param tasks: The tasks to push to the queue
-    :return: PushResponse containing a list containing details of any messages that failed to publish.
-    """
-    if tasks is None:
-        tasks = []
-    wire_tasks = map(self._task_to_wire, tasks)
-
-    request = queue.QueueSendBatchRequest(queue=queue_name, tasks=wire_tasks)
-
-    response: queue.QueueSendBatchResponse = self._exec("SendBatch", request)
-
-    failed_tasks = map(self._wire_to_failed_task, response.failedMessages)
-
-    return PushResponse(failed_tasks=list(failed_tasks))
+
def queue(self, name: str):
+    """Return a reference to a queue from the connected queue service."""
+    return Queue(_queue_stub=self._queue_stub, name=name)
@@ -566,12 +373,12 @@

Methods

Nitric generic blob storage client.

This client insulates application code from stack specific blob store operations or SDKs.

-

Construct a new StorageClient.

+

Construct a Nitric Storage Client.

Expand source code -
class StorageClient(BaseClient):
+
class StorageClient(object):
     """
     Nitric generic blob storage client.
 
@@ -579,99 +386,34 @@ 

Methods

""" def __init__(self): - """Construct a new StorageClient.""" - super(self.__class__, self).__init__() - self._stub = storage_service.StorageStub(self._channel) + """Construct a Nitric Storage Client.""" + self._storage_stub = StorageStub(channel=new_default_channel()) - def write(self, bucket_name: str, key: str, body: bytes): - """ - Store a file. - - :param bucket_name: name of the bucket to store the data in. - :param key: key within the bucket, where the file should be stored. - :param body: data to be stored. - :return: storage result. - """ - request = storage.StorageWriteRequest(bucket_name=bucket_name, key=key, body=body) - response = self._exec("Write", request) - return response - - def read(self, bucket_name: str, key: str) -> bytes: - """ - Retrieve an existing file. - - :param bucket_name: name of the bucket where the file was stored. - :param key: key for the file to retrieve. - :return: the file as bytes. - """ - request = storage.StorageReadRequest(bucket_name=bucket_name, key=key) - response = self._exec("Read", request) - return response.body
+ def bucket(self, name: str): + """Return a reference to a bucket from the connected storage service.""" + return Bucket(_storage_stub=self._storage_stub, name=name)
-

Ancestors

-
    -
  • nitric.api._base_client.BaseClient
  • -
  • abc.ABC
  • -

Methods

-
-def read(self, bucket_name: str, key: str) ‑> bytes +
+def bucket(self, name: str)
-

Retrieve an existing file.

-

:param bucket_name: name of the bucket where the file was stored. -:param key: key for the file to retrieve. -:return: the file as bytes.

+

Return a reference to a bucket from the connected storage service.

Expand source code -
def read(self, bucket_name: str, key: str) -> bytes:
-    """
-    Retrieve an existing file.
-
-    :param bucket_name: name of the bucket where the file was stored.
-    :param key: key for the file to retrieve.
-    :return: the file as bytes.
-    """
-    request = storage.StorageReadRequest(bucket_name=bucket_name, key=key)
-    response = self._exec("Read", request)
-    return response.body
-
-
-
-def write(self, bucket_name: str, key: str, body: bytes) -
-
-

Store a file.

-

:param bucket_name: name of the bucket to store the data in. -:param key: key within the bucket, where the file should be stored. -:param body: data to be stored. -:return: storage result.

-
- -Expand source code - -
def write(self, bucket_name: str, key: str, body: bytes):
-    """
-    Store a file.
-
-    :param bucket_name: name of the bucket to store the data in.
-    :param key: key within the bucket, where the file should be stored.
-    :param body: data to be stored.
-    :return: storage result.
-    """
-    request = storage.StorageWriteRequest(bucket_name=bucket_name, key=key, body=body)
-    response = self._exec("Write", request)
-    return response
+
def bucket(self, name: str):
+    """Return a reference to a bucket from the connected storage service."""
+    return Bucket(_storage_stub=self._storage_stub, name=name)
class Task -(task_id: str, payload_type: str, payload: dict, lease_id: str = None) +(id: str = None, payload_type: str = None, payload: dict = <factory>, lease_id: str = None)

Represents a NitricTask.

@@ -682,17 +424,34 @@

Methods

class Task(object):
     """Represents a NitricTask."""
 
-    task_id: str
-    payload_type: str
-    payload: dict
-    lease_id: str = field(default=None)
+ id: str = field(default=None) + payload_type: str = field(default=None) + payload: dict = field(default_factory=dict) + lease_id: str = field(default=None) + _queue_stub: QueueStub = field(default=None) + _queue: str = field(default=None) + + async def complete(self): + """Mark this task as complete and remove it from the queue.""" + if self._queue_stub is None or self._queue is None or self._queue == "": + raise Exception("Task was not created via Queue.") + if self.lease_id is None: + raise Exception( + "No lease_id available for task. Tasks must be received using Queue.receive to have a " + "valid lease_id." + ) + await self._queue_stub.complete(queue=self._queue, lease_id=self.lease_id)

Subclasses

Class variables

+
var id : str
+
+
+
var lease_id : str
@@ -705,26 +464,71 @@

Class variables

-
var task_id : str
+
+

Methods

+
+
+async def complete(self) +
-
+

Mark this task as complete and remove it from the queue.

+
+ +Expand source code + +
async def complete(self):
+    """Mark this task as complete and remove it from the queue."""
+    if self._queue_stub is None or self._queue is None or self._queue == "":
+        raise Exception("Task was not created via Queue.")
+    if self.lease_id is None:
+        raise Exception(
+            "No lease_id available for task. Tasks must be received using Queue.receive to have a "
+            "valid lease_id."
+        )
+    await self._queue_stub.complete(queue=self._queue, lease_id=self.lease_id)
+
class Topic -(name: str) +(_stub: EventStub, name: str)
-

Represents event topic metadata.

+

A reference to a topic on an event service, used to perform operations on that topic.

Expand source code
class Topic(object):
+<<<<<<< refs/remotes/origin/main
     """Represents event topic metadata."""
+=======
+    """A reference to a topic on an event service, used to perform operations on that topic."""
+
+    _stub: EventStub
+    name: str
+
+    async def publish(
+        self,
+        event: Union[Event, dict] = None,
+    ) -> Event:
+        """
+        Publish an event/message to a topic, which can be subscribed to by other services.
+
+        :param event: the event to publish
+        :return: the published event, with the id added if one was auto-generated
+        """
+        if event is None:
+            event = Event()
+
+        if isinstance(event, dict):
+            # TODO: handle events that are just a payload
+            event = Event(**event)
+>>>>>>> feat: port faas.start to bi-di streaming with membrane
 
-    name: str
+ response = await self._stub.publish(topic=self.name, event=_event_to_wire(event)) + return Event(**{**event.__dict__.copy(), **{"id": response.id}})

Class variables

@@ -733,57 +537,38 @@

Class variables

- -
-class TopicClient +

Methods

+
+
+async def publish(self, event: Union[Event, dict] = None) ‑> Event
-

Nitric generic event topic client.

-

This client insulates application code from stack specific topic operations or SDKs.

-

Construct a Nitric Topic Client.

+

Publish an event/message to a topic, which can be subscribed to by other services.

+

:param event: the event to publish +:return: the published event, with the id added if one was auto-generated

Expand source code -
class TopicClient(BaseClient):
+
async def publish(
+    self,
+    event: Union[Event, dict] = None,
+) -> Event:
     """
-    Nitric generic event topic client.
+    Publish an event/message to a topic, which can be subscribed to by other services.
 
-    This client insulates application code from stack specific topic operations or SDKs.
+    :param event: the event to publish
+    :return: the published event, with the id added if one was auto-generated
     """
+    if event is None:
+        event = Event()
 
-    def __init__(self):
-        """Construct a Nitric Topic Client."""
-        super(self.__class__, self).__init__()
-        self._stub = event_service.TopicStub(self._channel)
+    if isinstance(event, dict):
+        # TODO: handle events that are just a payload
+        event = Event(**event)
 
-    def get_topics(self) -> List[Topic]:
-        """Get a list of topics available for publishing or subscription."""
-        response: event.TopicListResponse = self._exec("List")
-        topics = [Topic(name=topic.name) for topic in response.topics]
-        return topics
-
-

Ancestors

-
    -
  • nitric.api._base_client.BaseClient
  • -
  • abc.ABC
  • -
-

Methods

-
-
-def get_topics(self) ‑> List[Topic] -
-
-

Get a list of topics available for publishing or subscription.

-
- -Expand source code - -
def get_topics(self) -> List[Topic]:
-    """Get a list of topics available for publishing or subscription."""
-    response: event.TopicListResponse = self._exec("List")
-    topics = [Topic(name=topic.name) for topic in response.topics]
-    return topics
+ response = await self._stub.publish(topic=self.name, event=_event_to_wire(event)) + return Event(**{**event.__dict__.copy(), **{"id": response.id}})
@@ -804,11 +589,10 @@

Index

  • Sub-modules

  • @@ -817,7 +601,7 @@

    Index

  • Event

    @@ -825,12 +609,14 @@

    Event<
  • EventClient

  • FailedTask

  • @@ -845,36 +631,30 @@

    QueueClient

  • StorageClient

  • Task

  • Topic

    -
  • -
  • -

    TopicClient

    -
  • diff --git a/docs/nitric/api/kv.html b/docs/nitric/api/kv.html index c614e70..57e530b 100644 --- a/docs/nitric/api/kv.html +++ b/docs/nitric/api/kv.html @@ -44,44 +44,38 @@

    Module nitric.api.kv

    # See the License for the specific language governing permissions and # limitations under the License. # -from nitric.proto import key_value -from nitric.proto import key_value_service -from nitric.api._base_client import BaseClient -from google.protobuf.struct_pb2 import Struct -from google.protobuf.json_format import MessageToDict -from nitric.proto.kv.v1.kv_pb2 import KeyValueGetResponse +from nitric.utils import new_default_channel, _struct_from_dict +from nitric.proto.nitric.kv.v1 import KeyValueStub -class KeyValueClient(BaseClient): +class KeyValueClient(object): """ Nitric generic document store/db client. This client insulates application code from stack specific document CRUD operations or SDKs. """ - def __init__(self): - """Construct a new DocumentClient.""" - super(self.__class__, self).__init__() - self._stub = key_value_service.KeyValueStub(self._channel) + def __init__(self, collection: str): + """ + Construct a new DocumentClient. - def put(self, collection: str, key: str, value: dict): - """Create a new document with the specified key in the specified collection.""" - value_struct = Struct() - value_struct.update(value) - request = key_value.KeyValuePutRequest(collection=collection, key=key, value=value_struct) - return self._exec("Put", request) + :param collection: name of the key/value collection + """ + self.collection = collection + self._stub = KeyValueStub(channel=new_default_channel()) - def get(self, collection: str, key: str) -> dict: - """Retrieve a document from the specified collection by its key.""" - request = key_value.KeyValueGetRequest(collection=collection, key=key) - reply: KeyValueGetResponse = self._exec("Get", request) - document = MessageToDict(reply)["value"] - return document + async def put(self, key: str, value: dict): + """Create a new document with the specified key.""" + await self._stub.put(collection=self.collection, key=key, value=_struct_from_dict(value)) - def delete(self, collection: str, key: str): + async def get(self, key: str) -> dict: + """Retrieve a document from the specified key.""" + response = await self._stub.get(collection=self.collection, key=key) + return response.value.to_dict() + + async def delete(self, key: str): """Delete the specified document from the collection.""" - request = key_value.KeyValueDeleteRequest(collection=collection, key=key) - return self._exec("Delete", request)
    + await self._stub.delete(collection=self.collection, key=key)
    @@ -95,55 +89,50 @@

    Classes

    class KeyValueClient +(collection: str)

    Nitric generic document store/db client.

    This client insulates application code from stack specific document CRUD operations or SDKs.

    -

    Construct a new DocumentClient.

    +

    Construct a new DocumentClient.

    +

    :param collection: name of the key/value collection

    Expand source code -
    class KeyValueClient(BaseClient):
    +
    class KeyValueClient(object):
         """
         Nitric generic document store/db client.
     
         This client insulates application code from stack specific document CRUD operations or SDKs.
         """
     
    -    def __init__(self):
    -        """Construct a new DocumentClient."""
    -        super(self.__class__, self).__init__()
    -        self._stub = key_value_service.KeyValueStub(self._channel)
    +    def __init__(self, collection: str):
    +        """
    +        Construct a new DocumentClient.
    +
    +        :param collection: name of the key/value collection
    +        """
    +        self.collection = collection
    +        self._stub = KeyValueStub(channel=new_default_channel())
     
    -    def put(self, collection: str, key: str, value: dict):
    -        """Create a new document with the specified key in the specified collection."""
    -        value_struct = Struct()
    -        value_struct.update(value)
    -        request = key_value.KeyValuePutRequest(collection=collection, key=key, value=value_struct)
    -        return self._exec("Put", request)
    +    async def put(self, key: str, value: dict):
    +        """Create a new document with the specified key."""
    +        await self._stub.put(collection=self.collection, key=key, value=_struct_from_dict(value))
     
    -    def get(self, collection: str, key: str) -> dict:
    -        """Retrieve a document from the specified collection by its key."""
    -        request = key_value.KeyValueGetRequest(collection=collection, key=key)
    -        reply: KeyValueGetResponse = self._exec("Get", request)
    -        document = MessageToDict(reply)["value"]
    -        return document
    +    async def get(self, key: str) -> dict:
    +        """Retrieve a document from the specified key."""
    +        response = await self._stub.get(collection=self.collection, key=key)
    +        return response.value.to_dict()
     
    -    def delete(self, collection: str, key: str):
    +    async def delete(self, key: str):
             """Delete the specified document from the collection."""
    -        request = key_value.KeyValueDeleteRequest(collection=collection, key=key)
    -        return self._exec("Delete", request)
    + await self._stub.delete(collection=self.collection, key=key)
    -

    Ancestors

    -
      -
    • nitric.api._base_client.BaseClient
    • -
    • abc.ABC
    • -

    Methods

    -def delete(self, collection: str, key: str) +async def delete(self, key: str)

    Delete the specified document from the collection.

    @@ -151,38 +140,43 @@

    Methods

    Expand source code -
    def delete(self, collection: str, key: str):
    +
    async def delete(self, key: str):
         """Delete the specified document from the collection."""
    -    request = key_value.KeyValueDeleteRequest(collection=collection, key=key)
    -    return self._exec("Delete", request)
    + await self._stub.delete(collection=self.collection, key=key)
    -def get(self, collection: str, key: str) ‑> dict +async def get(self, key: str) ‑> dict
    -

    Retrieve a document from the specified collection by its key.

    +

    Retrieve a document from the specified key.

    Expand source code -
    def get(self, collection: str, key: str) -> dict:
    -    """Retrieve a document from the specified collection by its key."""
    -    request = key_value.KeyValueGetRequest(collection=collection, key=key)
    -    reply: KeyValueGetResponse = self._exec("Get", request)
    -    document = MessageToDict(reply)["value"]
    -    return document
    +
    async def get(self, key: str) -> dict:
    +    """Retrieve a document from the specified key."""
    +    response = await self._stub.get(collection=self.collection, key=key)
    +    return response.value.to_dict()
    +<<<<<<< refs/remotes/origin/main def put(self, collection: str, key: str, value: dict)

    Create a new document with the specified key in the specified collection.

    +======= +async def put(self, key: str, value: dict) +
    +
    +

    Create a new document with the specified key.

    +>>>>>>> feat: port faas.start to bi-di streaming with membrane
    Expand source code +<<<<<<< refs/remotes/origin/main
    def put(self, collection: str, key: str, value: dict):
         """Create a new document with the specified key in the specified collection."""
         value_struct = Struct()
    @@ -216,6 +210,12 @@ 

    Instance variables

    var value

    Field nitric.kv.v1.KeyValueGetResponse.value

    +======= +
    async def put(self, key: str, value: dict):
    +    """Create a new document with the specified key."""
    +    await self._stub.put(collection=self.collection, key=key, value=_struct_from_dict(value))
    +
    +>>>>>>> feat: port faas.start to bi-di streaming with membrane
    @@ -243,6 +243,7 @@

    put +<<<<<<< refs/remotes/origin/main
  • KeyValueGetResponse

      @@ -250,6 +251,8 @@

      value

  • +======= +>>>>>>> feat: port faas.start to bi-di streaming with membrane diff --git a/docs/nitric/api/models.html b/docs/nitric/api/models.html deleted file mode 100644 index dbb3e6f..0000000 --- a/docs/nitric/api/models.html +++ /dev/null @@ -1,271 +0,0 @@ - - - - - - -nitric.api.models API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.api.models

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -from dataclasses import dataclass, field
    -
    -
    -@dataclass(frozen=True, order=True)
    -class Topic(object):
    -    """Represents event topic metadata."""
    -
    -    name: str
    -
    -
    -@dataclass(frozen=True, order=True)
    -class Event(object):
    -    """Represents a NitricEvent."""
    -
    -    event_id: str
    -    payload_type: str
    -    payload: dict
    -
    -
    -@dataclass(frozen=True, order=True)
    -class Task(object):
    -    """Represents a NitricTask."""
    -
    -    task_id: str
    -    payload_type: str
    -    payload: dict
    -    lease_id: str = field(default=None)
    -
    -
    -@dataclass(frozen=True, order=True)
    -class FailedTask(Task):
    -    """Represents a failed queue publish for an event."""
    -
    -    message: str = field(default="")
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Event -(event_id: str, payload_type: str, payload: dict) -
    -
    -

    Represents a NitricEvent.

    -
    - -Expand source code - -
    class Event(object):
    -    """Represents a NitricEvent."""
    -
    -    event_id: str
    -    payload_type: str
    -    payload: dict
    -
    -

    Class variables

    -
    -
    var event_id : str
    -
    -
    -
    -
    var payload : dict
    -
    -
    -
    -
    var payload_type : str
    -
    -
    -
    -
    -
    -
    -class FailedTask -(task_id: str, payload_type: str, payload: dict, lease_id: str = None, message: str = '') -
    -
    -

    Represents a failed queue publish for an event.

    -
    - -Expand source code - -
    class FailedTask(Task):
    -    """Represents a failed queue publish for an event."""
    -
    -    message: str = field(default="")
    -
    -

    Ancestors

    - -

    Class variables

    -
    -
    var message : str
    -
    -
    -
    -
    -
    -
    -class Task -(task_id: str, payload_type: str, payload: dict, lease_id: str = None) -
    -
    -

    Represents a NitricTask.

    -
    - -Expand source code - -
    class Task(object):
    -    """Represents a NitricTask."""
    -
    -    task_id: str
    -    payload_type: str
    -    payload: dict
    -    lease_id: str = field(default=None)
    -
    -

    Subclasses

    - -

    Class variables

    -
    -
    var lease_id : str
    -
    -
    -
    -
    var payload : dict
    -
    -
    -
    -
    var payload_type : str
    -
    -
    -
    -
    var task_id : str
    -
    -
    -
    -
    -
    -
    -class Topic -(name: str) -
    -
    -

    Represents event topic metadata.

    -
    - -Expand source code - -
    class Topic(object):
    -    """Represents event topic metadata."""
    -
    -    name: str
    -
    -

    Class variables

    -
    -
    var name : str
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/api/queue.html b/docs/nitric/api/queue.html deleted file mode 100644 index 7993e8f..0000000 --- a/docs/nitric/api/queue.html +++ /dev/null @@ -1,437 +0,0 @@ - - - - - - -nitric.api.queue API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.api.queue

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -from typing import List
    -
    -from google.protobuf.json_format import MessageToDict
    -from google.protobuf.struct_pb2 import Struct
    -
    -from nitric.api._base_client import BaseClient
    -from nitric.api.models import FailedTask, Task
    -from nitric.proto import queue
    -from nitric.proto import queue_service
    -
    -
    -class PushResponse(object):
    -    """Represents the result of a Queue Push."""
    -
    -    def __init__(self, failed_tasks: List[FailedTask]):
    -        """Construct a Push Response."""
    -        self.failed_tasks = failed_tasks
    -
    -
    -class QueueClient(BaseClient):
    -    """
    -    Nitric generic publish/subscribe tasking client.
    -
    -    This client insulates application code from stack specific task/topic operations or SDKs.
    -    """
    -
    -    def __init__(self):
    -        """Construct a Nitric Queue Client."""
    -        super(self.__class__, self).__init__()
    -        self._stub = queue_service.QueueStub(self._channel)
    -
    -    def _task_to_wire(self, task: Task) -> queue.NitricTask:
    -        """
    -        Convert a Nitric Task to a Nitric Queue Task.
    -
    -        :param task: to convert
    -        :return: converted task
    -        """
    -        payload_struct = Struct()
    -        payload_struct.update(task.payload)
    -
    -        return queue.NitricTask(
    -            id=task.task_id,
    -            payload_type=task.payload_type,
    -            payload=payload_struct,
    -        )
    -
    -    def _wire_to_task(self, task: queue.NitricTask) -> Task:
    -        """
    -        Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK).
    -
    -        :param task: to convert
    -        :return: converted task
    -        """
    -        return Task(
    -            task_id=task.id,
    -            payload_type=task.payload_type,
    -            payload=MessageToDict(task.payload),
    -            lease_id=task.lease_id,
    -        )
    -
    -    def _wire_to_failed_task(self, failed_task: queue.FailedTask) -> FailedTask:
    -        """
    -        Convert a queue task that failed to push into a Failed Task object.
    -
    -        :param failed_task: the failed task
    -        :return: the Failed Task with failure message
    -        """
    -        task = self._wire_to_task(failed_task.task)
    -
    -        return FailedTask(
    -            task_id=task.task_id,
    -            payload_type=task.payload_type,
    -            payload=task.payload,
    -            lease_id=task.lease_id,
    -            message=failed_task.message,
    -        )
    -
    -    def send_batch(self, queue_name: str, tasks: List[Task] = None) -> PushResponse:
    -        """
    -        Push a collection of tasks to a queue, which can be retrieved by other services.
    -
    -        :param queue_name: the name of the queue to publish to
    -        :param tasks: The tasks to push to the queue
    -        :return: PushResponse containing a list containing details of any messages that failed to publish.
    -        """
    -        if tasks is None:
    -            tasks = []
    -        wire_tasks = map(self._task_to_wire, tasks)
    -
    -        request = queue.QueueSendBatchRequest(queue=queue_name, tasks=wire_tasks)
    -
    -        response: queue.QueueSendBatchResponse = self._exec("SendBatch", request)
    -
    -        failed_tasks = map(self._wire_to_failed_task, response.failedMessages)
    -
    -        return PushResponse(failed_tasks=list(failed_tasks))
    -
    -    def receive(self, queue_name: str, depth: int = None) -> List[Task]:
    -        """
    -        Pop 1 or more items from the specified queue up to the depth limit.
    -
    -        Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
    -        Once complete or failed they must be acknowledged using the request specific leaseId.
    -
    -        If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
    -        returned to the queue for reprocessing.
    -
    -        :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific
    -        identifier.
    -        :param depth: The maximum number of queue items to return. Default: 1, Min: 1.
    -        :return: Queue items popped from the specified queue.
    -        """
    -        # Set the default and minimum depth to 1.
    -        if depth is None or depth < 1:
    -            depth = 1
    -
    -        request = queue.QueueReceiveRequest(queue=queue_name, depth=depth)
    -
    -        response: queue.QueueReceiveResponse = self._exec("Receive", request)
    -
    -        # Map the response protobuf response items to Python SDK Nitric Queue Items
    -        return [self._wire_to_task(item) for item in response.items]
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class PushResponse -(failed_tasks: List[FailedTask]) -
    -
    -

    Represents the result of a Queue Push.

    -

    Construct a Push Response.

    -
    - -Expand source code - -
    class PushResponse(object):
    -    """Represents the result of a Queue Push."""
    -
    -    def __init__(self, failed_tasks: List[FailedTask]):
    -        """Construct a Push Response."""
    -        self.failed_tasks = failed_tasks
    -
    -
    -
    -class QueueClient -
    -
    -

    Nitric generic publish/subscribe tasking client.

    -

    This client insulates application code from stack specific task/topic operations or SDKs.

    -

    Construct a Nitric Queue Client.

    -
    - -Expand source code - -
    class QueueClient(BaseClient):
    -    """
    -    Nitric generic publish/subscribe tasking client.
    -
    -    This client insulates application code from stack specific task/topic operations or SDKs.
    -    """
    -
    -    def __init__(self):
    -        """Construct a Nitric Queue Client."""
    -        super(self.__class__, self).__init__()
    -        self._stub = queue_service.QueueStub(self._channel)
    -
    -    def _task_to_wire(self, task: Task) -> queue.NitricTask:
    -        """
    -        Convert a Nitric Task to a Nitric Queue Task.
    -
    -        :param task: to convert
    -        :return: converted task
    -        """
    -        payload_struct = Struct()
    -        payload_struct.update(task.payload)
    -
    -        return queue.NitricTask(
    -            id=task.task_id,
    -            payload_type=task.payload_type,
    -            payload=payload_struct,
    -        )
    -
    -    def _wire_to_task(self, task: queue.NitricTask) -> Task:
    -        """
    -        Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK).
    -
    -        :param task: to convert
    -        :return: converted task
    -        """
    -        return Task(
    -            task_id=task.id,
    -            payload_type=task.payload_type,
    -            payload=MessageToDict(task.payload),
    -            lease_id=task.lease_id,
    -        )
    -
    -    def _wire_to_failed_task(self, failed_task: queue.FailedTask) -> FailedTask:
    -        """
    -        Convert a queue task that failed to push into a Failed Task object.
    -
    -        :param failed_task: the failed task
    -        :return: the Failed Task with failure message
    -        """
    -        task = self._wire_to_task(failed_task.task)
    -
    -        return FailedTask(
    -            task_id=task.task_id,
    -            payload_type=task.payload_type,
    -            payload=task.payload,
    -            lease_id=task.lease_id,
    -            message=failed_task.message,
    -        )
    -
    -    def send_batch(self, queue_name: str, tasks: List[Task] = None) -> PushResponse:
    -        """
    -        Push a collection of tasks to a queue, which can be retrieved by other services.
    -
    -        :param queue_name: the name of the queue to publish to
    -        :param tasks: The tasks to push to the queue
    -        :return: PushResponse containing a list containing details of any messages that failed to publish.
    -        """
    -        if tasks is None:
    -            tasks = []
    -        wire_tasks = map(self._task_to_wire, tasks)
    -
    -        request = queue.QueueSendBatchRequest(queue=queue_name, tasks=wire_tasks)
    -
    -        response: queue.QueueSendBatchResponse = self._exec("SendBatch", request)
    -
    -        failed_tasks = map(self._wire_to_failed_task, response.failedMessages)
    -
    -        return PushResponse(failed_tasks=list(failed_tasks))
    -
    -    def receive(self, queue_name: str, depth: int = None) -> List[Task]:
    -        """
    -        Pop 1 or more items from the specified queue up to the depth limit.
    -
    -        Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
    -        Once complete or failed they must be acknowledged using the request specific leaseId.
    -
    -        If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
    -        returned to the queue for reprocessing.
    -
    -        :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific
    -        identifier.
    -        :param depth: The maximum number of queue items to return. Default: 1, Min: 1.
    -        :return: Queue items popped from the specified queue.
    -        """
    -        # Set the default and minimum depth to 1.
    -        if depth is None or depth < 1:
    -            depth = 1
    -
    -        request = queue.QueueReceiveRequest(queue=queue_name, depth=depth)
    -
    -        response: queue.QueueReceiveResponse = self._exec("Receive", request)
    -
    -        # Map the response protobuf response items to Python SDK Nitric Queue Items
    -        return [self._wire_to_task(item) for item in response.items]
    -
    -

    Ancestors

    -
      -
    • nitric.api._base_client.BaseClient
    • -
    • abc.ABC
    • -
    -

    Methods

    -
    -
    -def receive(self, queue_name: str, depth: int = None) ‑> List[Task] -
    -
    -

    Pop 1 or more items from the specified queue up to the depth limit.

    -

    Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on. -Once complete or failed they must be acknowledged using the request specific leaseId.

    -

    If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be -returned to the queue for reprocessing.

    -

    :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific -identifier. -:param depth: The maximum number of queue items to return. Default: 1, Min: 1. -:return: Queue items popped from the specified queue.

    -
    - -Expand source code - -
    def receive(self, queue_name: str, depth: int = None) -> List[Task]:
    -    """
    -    Pop 1 or more items from the specified queue up to the depth limit.
    -
    -    Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
    -    Once complete or failed they must be acknowledged using the request specific leaseId.
    -
    -    If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
    -    returned to the queue for reprocessing.
    -
    -    :param queue_name: Nitric name for the queue. This will be automatically resolved to the provider specific
    -    identifier.
    -    :param depth: The maximum number of queue items to return. Default: 1, Min: 1.
    -    :return: Queue items popped from the specified queue.
    -    """
    -    # Set the default and minimum depth to 1.
    -    if depth is None or depth < 1:
    -        depth = 1
    -
    -    request = queue.QueueReceiveRequest(queue=queue_name, depth=depth)
    -
    -    response: queue.QueueReceiveResponse = self._exec("Receive", request)
    -
    -    # Map the response protobuf response items to Python SDK Nitric Queue Items
    -    return [self._wire_to_task(item) for item in response.items]
    -
    -
    -
    -def send_batch(self, queue_name: str, tasks: List[Task] = None) ‑> PushResponse -
    -
    -

    Push a collection of tasks to a queue, which can be retrieved by other services.

    -

    :param queue_name: the name of the queue to publish to -:param tasks: The tasks to push to the queue -:return: PushResponse containing a list containing details of any messages that failed to publish.

    -
    - -Expand source code - -
    def send_batch(self, queue_name: str, tasks: List[Task] = None) -> PushResponse:
    -    """
    -    Push a collection of tasks to a queue, which can be retrieved by other services.
    -
    -    :param queue_name: the name of the queue to publish to
    -    :param tasks: The tasks to push to the queue
    -    :return: PushResponse containing a list containing details of any messages that failed to publish.
    -    """
    -    if tasks is None:
    -        tasks = []
    -    wire_tasks = map(self._task_to_wire, tasks)
    -
    -    request = queue.QueueSendBatchRequest(queue=queue_name, tasks=wire_tasks)
    -
    -    response: queue.QueueSendBatchResponse = self._exec("SendBatch", request)
    -
    -    failed_tasks = map(self._wire_to_failed_task, response.failedMessages)
    -
    -    return PushResponse(failed_tasks=list(failed_tasks))
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/api/queues.html b/docs/nitric/api/queues.html new file mode 100644 index 0000000..0eb1f2a --- /dev/null +++ b/docs/nitric/api/queues.html @@ -0,0 +1,615 @@ + + + + + + +nitric.api.queues API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.api.queues

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +from typing import List, Union
    +from nitric.utils import new_default_channel, _struct_from_dict
    +from nitric.proto.nitric.queue.v1 import QueueStub, NitricTask, FailedTask as WireFailedTask
    +from dataclasses import dataclass, field
    +
    +
    +@dataclass(frozen=True, order=True)
    +class Task(object):
    +    """Represents a NitricTask."""
    +
    +    id: str = field(default=None)
    +    payload_type: str = field(default=None)
    +    payload: dict = field(default_factory=dict)
    +    lease_id: str = field(default=None)
    +    _queue_stub: QueueStub = field(default=None)
    +    _queue: str = field(default=None)
    +
    +    async def complete(self):
    +        """Mark this task as complete and remove it from the queue."""
    +        if self._queue_stub is None or self._queue is None or self._queue == "":
    +            raise Exception("Task was not created via Queue.")
    +        if self.lease_id is None:
    +            raise Exception(
    +                "No lease_id available for task. Tasks must be received using Queue.receive to have a "
    +                "valid lease_id."
    +            )
    +        await self._queue_stub.complete(queue=self._queue, lease_id=self.lease_id)
    +
    +
    +@dataclass(frozen=True, order=True)
    +class FailedTask(Task):
    +    """Represents a failed queue publish for an event."""
    +
    +    lease_id: str = None  # failed tasks should never have a lease id.
    +    message: str = field(default="")
    +
    +
    +def _task_to_wire(task: Task) -> NitricTask:
    +    """
    +    Convert a Nitric Task to a Nitric Queue Task.
    +
    +    :param task: to convert
    +    :return: converted task
    +    """
    +    return NitricTask(
    +        id=task.id,
    +        payload_type=task.payload_type,
    +        payload=_struct_from_dict(task.payload),
    +    )
    +
    +
    +def _wire_to_task(task: NitricTask) -> Task:
    +    """
    +    Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK).
    +
    +    :param task: to convert
    +    :return: converted task
    +    """
    +    return Task(
    +        id=task.id,
    +        payload_type=task.payload_type,
    +        payload=task.payload.to_dict(),
    +        lease_id=task.lease_id,
    +    )
    +
    +
    +def _wire_to_failed_task(failed_task: WireFailedTask) -> FailedTask:
    +    """
    +    Convert a queue task that failed to push into a Failed Task object.
    +
    +    :param failed_task: the failed task
    +    :return: the Failed Task with failure message
    +    """
    +    task = _wire_to_task(failed_task.task)
    +
    +    return FailedTask(
    +        id=task.id,
    +        payload_type=task.payload_type,
    +        payload=task.payload,
    +        lease_id=task.lease_id,
    +        message=failed_task.message,
    +    )
    +
    +
    +@dataclass(frozen=True, order=True)
    +class Queue(object):
    +    """A reference to a queue from a queue service, used to perform operations on that queue."""
    +
    +    _queue_stub: QueueStub
    +    name: str
    +
    +    async def send(
    +        self, tasks: Union[Task, dict, List[Union[Task, dict]]] = None
    +    ) -> Union[Task, List[Union[Task, FailedTask]]]:
    +        """
    +        Send one or more tasks to this queue.
    +
    +        If a list of tasks is provided this function will return a list containing any tasks that failed to be sent to
    +        the queue.
    +
    +        :param tasks: A task or list of tasks to send to the queue.
    +        """
    +        if isinstance(tasks, list):
    +            return await self._send_batch(tasks)
    +
    +        task = tasks
    +        if task is None:
    +            task = Task()
    +
    +        if isinstance(task, dict):
    +            # TODO: handle tasks that are just a payload
    +            task = Task(**task)
    +
    +        await self._queue_stub.send(queue=self.name, task=_task_to_wire(task))
    +
    +    async def _send_batch(
    +        self, tasks: List[Union[Task, dict]] = None, raise_on_failure: bool = True
    +    ) -> List[FailedTask]:
    +        """
    +        Push a collection of tasks to a queue, which can be retrieved by other services.
    +
    +        :param tasks: The tasks to push to the queue
    +        :param raise_on_failure: Whether to raise an exception when one or more tasks fails to send
    +        :return: PushResponse containing a list containing details of any messages that failed to publish.
    +        """
    +        if tasks is None:
    +            tasks = []
    +
    +        wire_tasks = [_task_to_wire(Task(**task) if isinstance(task, dict) else task) for task in tasks]
    +
    +        response = await self._queue_stub.send_batch(queue=self.name, tasks=wire_tasks)
    +
    +        return [_wire_to_failed_task(failed_task) for failed_task in response.failed_tasks]
    +
    +    async def receive(self, limit: int = None) -> List[Task]:
    +        """
    +        Pop 1 or more items from the specified queue up to the depth limit.
    +
    +        Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
    +        Once complete or failed they must be acknowledged using the request specific leaseId.
    +
    +        If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
    +        returned to the queue for reprocessing.
    +
    +        :param limit: The maximum number of queue items to return. Default: 1, Min: 1.
    +        :return: Queue items popped from the specified queue.
    +        """
    +        # Set the default and minimum depth to 1.
    +        if limit is None or limit < 1:
    +            limit = 1
    +
    +        response = await self._queue_stub.receive(queue=self.name, depth=limit)
    +
    +        # Map the response protobuf response items to Python SDK Nitric Tasks
    +        return [_wire_to_task(task) for task in response.tasks]
    +
    +
    +class QueueClient(object):
    +    """
    +    Nitric generic publish/subscribe tasking client.
    +
    +    This client insulates application code from stack specific task/topic operations or SDKs.
    +    """
    +
    +    def __init__(self):
    +        """Construct a Nitric Queue Client."""
    +        self._queue_stub = QueueStub(channel=new_default_channel())
    +
    +    def queue(self, name: str):
    +        """Return a reference to a queue from the connected queue service."""
    +        return Queue(_queue_stub=self._queue_stub, name=name)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class FailedTask +(id: str = None, payload_type: str = None, payload: dict = <factory>, lease_id: str = None, message: str = '') +
    +
    +

    Represents a failed queue publish for an event.

    +
    + +Expand source code + +
    class FailedTask(Task):
    +    """Represents a failed queue publish for an event."""
    +
    +    lease_id: str = None  # failed tasks should never have a lease id.
    +    message: str = field(default="")
    +
    +

    Ancestors

    + +

    Class variables

    +
    +
    var lease_id : str
    +
    +
    +
    +
    var message : str
    +
    +
    +
    +
    +

    Inherited members

    + +
    +
    +class Queue +(_queue_stub: QueueStub, name: str) +
    +
    +

    A reference to a queue from a queue service, used to perform operations on that queue.

    +
    + +Expand source code + +
    class Queue(object):
    +    """A reference to a queue from a queue service, used to perform operations on that queue."""
    +
    +    _queue_stub: QueueStub
    +    name: str
    +
    +    async def send(
    +        self, tasks: Union[Task, dict, List[Union[Task, dict]]] = None
    +    ) -> Union[Task, List[Union[Task, FailedTask]]]:
    +        """
    +        Send one or more tasks to this queue.
    +
    +        If a list of tasks is provided this function will return a list containing any tasks that failed to be sent to
    +        the queue.
    +
    +        :param tasks: A task or list of tasks to send to the queue.
    +        """
    +        if isinstance(tasks, list):
    +            return await self._send_batch(tasks)
    +
    +        task = tasks
    +        if task is None:
    +            task = Task()
    +
    +        if isinstance(task, dict):
    +            # TODO: handle tasks that are just a payload
    +            task = Task(**task)
    +
    +        await self._queue_stub.send(queue=self.name, task=_task_to_wire(task))
    +
    +    async def _send_batch(
    +        self, tasks: List[Union[Task, dict]] = None, raise_on_failure: bool = True
    +    ) -> List[FailedTask]:
    +        """
    +        Push a collection of tasks to a queue, which can be retrieved by other services.
    +
    +        :param tasks: The tasks to push to the queue
    +        :param raise_on_failure: Whether to raise an exception when one or more tasks fails to send
    +        :return: PushResponse containing a list containing details of any messages that failed to publish.
    +        """
    +        if tasks is None:
    +            tasks = []
    +
    +        wire_tasks = [_task_to_wire(Task(**task) if isinstance(task, dict) else task) for task in tasks]
    +
    +        response = await self._queue_stub.send_batch(queue=self.name, tasks=wire_tasks)
    +
    +        return [_wire_to_failed_task(failed_task) for failed_task in response.failed_tasks]
    +
    +    async def receive(self, limit: int = None) -> List[Task]:
    +        """
    +        Pop 1 or more items from the specified queue up to the depth limit.
    +
    +        Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
    +        Once complete or failed they must be acknowledged using the request specific leaseId.
    +
    +        If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
    +        returned to the queue for reprocessing.
    +
    +        :param limit: The maximum number of queue items to return. Default: 1, Min: 1.
    +        :return: Queue items popped from the specified queue.
    +        """
    +        # Set the default and minimum depth to 1.
    +        if limit is None or limit < 1:
    +            limit = 1
    +
    +        response = await self._queue_stub.receive(queue=self.name, depth=limit)
    +
    +        # Map the response protobuf response items to Python SDK Nitric Tasks
    +        return [_wire_to_task(task) for task in response.tasks]
    +
    +

    Class variables

    +
    +
    var name : str
    +
    +
    +
    +
    +

    Methods

    +
    +
    +async def receive(self, limit: int = None) ‑> List[Task] +
    +
    +

    Pop 1 or more items from the specified queue up to the depth limit.

    +

    Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on. +Once complete or failed they must be acknowledged using the request specific leaseId.

    +

    If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be +returned to the queue for reprocessing.

    +

    :param limit: The maximum number of queue items to return. Default: 1, Min: 1. +:return: Queue items popped from the specified queue.

    +
    + +Expand source code + +
    async def receive(self, limit: int = None) -> List[Task]:
    +    """
    +    Pop 1 or more items from the specified queue up to the depth limit.
    +
    +    Queue items are Nitric Tasks that are leased for a limited period of time, where they may be worked on.
    +    Once complete or failed they must be acknowledged using the request specific leaseId.
    +
    +    If the lease on a queue item expires before it is acknowledged or the lease is extended the task will be
    +    returned to the queue for reprocessing.
    +
    +    :param limit: The maximum number of queue items to return. Default: 1, Min: 1.
    +    :return: Queue items popped from the specified queue.
    +    """
    +    # Set the default and minimum depth to 1.
    +    if limit is None or limit < 1:
    +        limit = 1
    +
    +    response = await self._queue_stub.receive(queue=self.name, depth=limit)
    +
    +    # Map the response protobuf response items to Python SDK Nitric Tasks
    +    return [_wire_to_task(task) for task in response.tasks]
    +
    +
    +
    +async def send(self, tasks: Union[Task, dict, List[Union[Task, dict]]] = None) ‑> Union[Task, List[Union[Task, FailedTask]]] +
    +
    +

    Send one or more tasks to this queue.

    +

    If a list of tasks is provided this function will return a list containing any tasks that failed to be sent to +the queue.

    +

    :param tasks: A task or list of tasks to send to the queue.

    +
    + +Expand source code + +
    async def send(
    +    self, tasks: Union[Task, dict, List[Union[Task, dict]]] = None
    +) -> Union[Task, List[Union[Task, FailedTask]]]:
    +    """
    +    Send one or more tasks to this queue.
    +
    +    If a list of tasks is provided this function will return a list containing any tasks that failed to be sent to
    +    the queue.
    +
    +    :param tasks: A task or list of tasks to send to the queue.
    +    """
    +    if isinstance(tasks, list):
    +        return await self._send_batch(tasks)
    +
    +    task = tasks
    +    if task is None:
    +        task = Task()
    +
    +    if isinstance(task, dict):
    +        # TODO: handle tasks that are just a payload
    +        task = Task(**task)
    +
    +    await self._queue_stub.send(queue=self.name, task=_task_to_wire(task))
    +
    +
    +
    +
    +
    +class QueueClient +
    +
    +

    Nitric generic publish/subscribe tasking client.

    +

    This client insulates application code from stack specific task/topic operations or SDKs.

    +

    Construct a Nitric Queue Client.

    +
    + +Expand source code + +
    class QueueClient(object):
    +    """
    +    Nitric generic publish/subscribe tasking client.
    +
    +    This client insulates application code from stack specific task/topic operations or SDKs.
    +    """
    +
    +    def __init__(self):
    +        """Construct a Nitric Queue Client."""
    +        self._queue_stub = QueueStub(channel=new_default_channel())
    +
    +    def queue(self, name: str):
    +        """Return a reference to a queue from the connected queue service."""
    +        return Queue(_queue_stub=self._queue_stub, name=name)
    +
    +

    Methods

    +
    +
    +def queue(self, name: str) +
    +
    +

    Return a reference to a queue from the connected queue service.

    +
    + +Expand source code + +
    def queue(self, name: str):
    +    """Return a reference to a queue from the connected queue service."""
    +    return Queue(_queue_stub=self._queue_stub, name=name)
    +
    +
    +
    +
    +
    +class Task +(id: str = None, payload_type: str = None, payload: dict = <factory>, lease_id: str = None) +
    +
    +

    Represents a NitricTask.

    +
    + +Expand source code + +
    class Task(object):
    +    """Represents a NitricTask."""
    +
    +    id: str = field(default=None)
    +    payload_type: str = field(default=None)
    +    payload: dict = field(default_factory=dict)
    +    lease_id: str = field(default=None)
    +    _queue_stub: QueueStub = field(default=None)
    +    _queue: str = field(default=None)
    +
    +    async def complete(self):
    +        """Mark this task as complete and remove it from the queue."""
    +        if self._queue_stub is None or self._queue is None or self._queue == "":
    +            raise Exception("Task was not created via Queue.")
    +        if self.lease_id is None:
    +            raise Exception(
    +                "No lease_id available for task. Tasks must be received using Queue.receive to have a "
    +                "valid lease_id."
    +            )
    +        await self._queue_stub.complete(queue=self._queue, lease_id=self.lease_id)
    +
    +

    Subclasses

    + +

    Class variables

    +
    +
    var id : str
    +
    +
    +
    +
    var lease_id : str
    +
    +
    +
    +
    var payload : dict
    +
    +
    +
    +
    var payload_type : str
    +
    +
    +
    +
    +

    Methods

    +
    +
    +async def complete(self) +
    +
    +

    Mark this task as complete and remove it from the queue.

    +
    + +Expand source code + +
    async def complete(self):
    +    """Mark this task as complete and remove it from the queue."""
    +    if self._queue_stub is None or self._queue is None or self._queue == "":
    +        raise Exception("Task was not created via Queue.")
    +    if self.lease_id is None:
    +        raise Exception(
    +            "No lease_id available for task. Tasks must be received using Queue.receive to have a "
    +            "valid lease_id."
    +        )
    +    await self._queue_stub.complete(queue=self._queue, lease_id=self.lease_id)
    +
    +
    +
    +
    +
    +
    +
    + +
    + + + \ No newline at end of file diff --git a/docs/nitric/api/storage.html b/docs/nitric/api/storage.html index c8c59a1..4b78a51 100644 --- a/docs/nitric/api/storage.html +++ b/docs/nitric/api/storage.html @@ -44,12 +44,13 @@

    Module nitric.api.storage

    # See the License for the specific language governing permissions and # limitations under the License. # -from nitric.proto import storage -from nitric.proto import storage_service -from nitric.api._base_client import BaseClient +from dataclasses import dataclass +from nitric.utils import new_default_channel +from nitric.proto.nitric.storage.v1 import StorageStub -class StorageClient(BaseClient): + +class StorageClient(object): """ Nitric generic blob storage client. @@ -57,34 +58,50 @@

    Module nitric.api.storage

    """ def __init__(self): - """Construct a new StorageClient.""" - super(self.__class__, self).__init__() - self._stub = storage_service.StorageStub(self._channel) + """Construct a Nitric Storage Client.""" + self._storage_stub = StorageStub(channel=new_default_channel()) - def write(self, bucket_name: str, key: str, body: bytes): - """ - Store a file. + def bucket(self, name: str): + """Return a reference to a bucket from the connected storage service.""" + return Bucket(_storage_stub=self._storage_stub, name=name) + + +@dataclass(frozen=True, order=True) +class Bucket(object): + """A reference to a bucket in a storage service, used to the perform operations on that bucket.""" + + _storage_stub: StorageStub + name: str + + def file(self, key: str): + """Return a reference to a file in this bucket.""" + return File(_storage_stub=self._storage_stub, _bucket=self.name, key=key) - :param bucket_name: name of the bucket to store the data in. - :param key: key within the bucket, where the file should be stored. - :param body: data to be stored. - :return: storage result. - """ - request = storage.StorageWriteRequest(bucket_name=bucket_name, key=key, body=body) - response = self._exec("Write", request) - return response - def read(self, bucket_name: str, key: str) -> bytes: +@dataclass(frozen=True, order=True) +class File(object): + """A reference to a file in a bucket, used to perform operations on that file.""" + + _storage_stub: StorageStub + _bucket: str + key: str + + async def write(self, body: bytes): """ - Retrieve an existing file. + Write the bytes as the content of this file. - :param bucket_name: name of the bucket where the file was stored. - :param key: key for the file to retrieve. - :return: the file as bytes. + Will create the file if it doesn't already exist. """ - request = storage.StorageReadRequest(bucket_name=bucket_name, key=key) - response = self._exec("Read", request) - return response.body
    + await self._storage_stub.write(bucket_name=self._bucket, key=self.key, body=body) + + async def read(self) -> bytes: + """Read this files contents from the bucket.""" + response = await self._storage_stub.read(bucket_name=self._bucket, key=self.key) + return response.body + + async def delete(self): + """Delete this file from the bucket.""" + await self._storage_stub.delete(bucket_name=self._bucket, key=self.key)
    @@ -96,111 +113,184 @@

    Module nitric.api.storage

    Classes

    -
    -class StorageClient +
    +class Bucket +(_storage_stub: StorageStub, name: str)
    -

    Nitric generic blob storage client.

    -

    This client insulates application code from stack specific blob store operations or SDKs.

    -

    Construct a new StorageClient.

    +

    A reference to a bucket in a storage service, used to the perform operations on that bucket.

    Expand source code -
    class StorageClient(BaseClient):
    -    """
    -    Nitric generic blob storage client.
    +
    class Bucket(object):
    +    """A reference to a bucket in a storage service, used to the perform operations on that bucket."""
     
    -    This client insulates application code from stack specific blob store operations or SDKs.
    -    """
    +    _storage_stub: StorageStub
    +    name: str
     
    -    def __init__(self):
    -        """Construct a new StorageClient."""
    -        super(self.__class__, self).__init__()
    -        self._stub = storage_service.StorageStub(self._channel)
    +    def file(self, key: str):
    +        """Return a reference to a file in this bucket."""
    +        return File(_storage_stub=self._storage_stub, _bucket=self.name, key=key)
    +
    +

    Class variables

    +
    +
    var name : str
    +
    +
    +
    +
    +

    Methods

    +
    +
    +def file(self, key: str) +
    +
    +

    Return a reference to a file in this bucket.

    +
    + +Expand source code + +
    def file(self, key: str):
    +    """Return a reference to a file in this bucket."""
    +    return File(_storage_stub=self._storage_stub, _bucket=self.name, key=key)
    +
    +
    +
    +
    +
    +class File +(_storage_stub: StorageStub, _bucket: str, key: str) +
    +
    +

    A reference to a file in a bucket, used to perform operations on that file.

    +
    + +Expand source code + +
    class File(object):
    +    """A reference to a file in a bucket, used to perform operations on that file."""
     
    -    def write(self, bucket_name: str, key: str, body: bytes):
    -        """
    -        Store a file.
    +    _storage_stub: StorageStub
    +    _bucket: str
    +    key: str
     
    -        :param bucket_name: name of the bucket to store the data in.
    -        :param key: key within the bucket, where the file should be stored.
    -        :param body: data to be stored.
    -        :return: storage result.
    +    async def write(self, body: bytes):
             """
    -        request = storage.StorageWriteRequest(bucket_name=bucket_name, key=key, body=body)
    -        response = self._exec("Write", request)
    -        return response
    +        Write the bytes as the content of this file.
     
    -    def read(self, bucket_name: str, key: str) -> bytes:
    +        Will create the file if it doesn't already exist.
             """
    -        Retrieve an existing file.
    +        await self._storage_stub.write(bucket_name=self._bucket, key=self.key, body=body)
     
    -        :param bucket_name: name of the bucket where the file was stored.
    -        :param key: key for the file to retrieve.
    -        :return: the file as bytes.
    -        """
    -        request = storage.StorageReadRequest(bucket_name=bucket_name, key=key)
    -        response = self._exec("Read", request)
    -        return response.body
    + async def read(self) -> bytes: + """Read this files contents from the bucket.""" + response = await self._storage_stub.read(bucket_name=self._bucket, key=self.key) + return response.body + + async def delete(self): + """Delete this file from the bucket.""" + await self._storage_stub.delete(bucket_name=self._bucket, key=self.key)
    -

    Ancestors

    -
      -
    • nitric.api._base_client.BaseClient
    • -
    • abc.ABC
    • -
    +

    Class variables

    +
    +
    var key : str
    +
    +
    +
    +

    Methods

    -
    -def read(self, bucket_name: str, key: str) ‑> bytes +
    +async def delete(self) +
    +
    +

    Delete this file from the bucket.

    +
    + +Expand source code + +
    async def delete(self):
    +    """Delete this file from the bucket."""
    +    await self._storage_stub.delete(bucket_name=self._bucket, key=self.key)
    +
    +
    +
    +async def read(self) ‑> bytes +
    +
    +

    Read this files contents from the bucket.

    +
    + +Expand source code + +
    async def read(self) -> bytes:
    +    """Read this files contents from the bucket."""
    +    response = await self._storage_stub.read(bucket_name=self._bucket, key=self.key)
    +    return response.body
    +
    +
    +
    +async def write(self, body: bytes)
    -

    Retrieve an existing file.

    -

    :param bucket_name: name of the bucket where the file was stored. -:param key: key for the file to retrieve. -:return: the file as bytes.

    +

    Write the bytes as the content of this file.

    +

    Will create the file if it doesn't already exist.

    Expand source code -
    def read(self, bucket_name: str, key: str) -> bytes:
    +
    async def write(self, body: bytes):
         """
    -    Retrieve an existing file.
    +    Write the bytes as the content of this file.
     
    -    :param bucket_name: name of the bucket where the file was stored.
    -    :param key: key for the file to retrieve.
    -    :return: the file as bytes.
    +    Will create the file if it doesn't already exist.
         """
    -    request = storage.StorageReadRequest(bucket_name=bucket_name, key=key)
    -    response = self._exec("Read", request)
    -    return response.body
    + await self._storage_stub.write(bucket_name=self._bucket, key=self.key, body=body)
    -
    -def write(self, bucket_name: str, key: str, body: bytes) +
    +
    +
    +class StorageClient
    -

    Store a file.

    -

    :param bucket_name: name of the bucket to store the data in. -:param key: key within the bucket, where the file should be stored. -:param body: data to be stored. -:return: storage result.

    +

    Nitric generic blob storage client.

    +

    This client insulates application code from stack specific blob store operations or SDKs.

    +

    Construct a Nitric Storage Client.

    Expand source code -
    def write(self, bucket_name: str, key: str, body: bytes):
    +
    class StorageClient(object):
         """
    -    Store a file.
    +    Nitric generic blob storage client.
     
    -    :param bucket_name: name of the bucket to store the data in.
    -    :param key: key within the bucket, where the file should be stored.
    -    :param body: data to be stored.
    -    :return: storage result.
    +    This client insulates application code from stack specific blob store operations or SDKs.
         """
    -    request = storage.StorageWriteRequest(bucket_name=bucket_name, key=key, body=body)
    -    response = self._exec("Write", request)
    -    return response
    + + def __init__(self): + """Construct a Nitric Storage Client.""" + self._storage_stub = StorageStub(channel=new_default_channel()) + + def bucket(self, name: str): + """Return a reference to a bucket from the connected storage service.""" + return Bucket(_storage_stub=self._storage_stub, name=name)
    +
    +

    Methods

    +
    +
    +def bucket(self, name: str) +
    +
    +

    Return a reference to a bucket from the connected storage service.

    +
    + +Expand source code + +
    def bucket(self, name: str):
    +    """Return a reference to a bucket from the connected storage service."""
    +    return Bucket(_storage_stub=self._storage_stub, name=name)
    @@ -222,10 +312,25 @@

    Index

  • Classes

    diff --git a/docs/nitric/faas/faas.html b/docs/nitric/faas/faas.html index 936a025..09e23be 100644 --- a/docs/nitric/faas/faas.html +++ b/docs/nitric/faas/faas.html @@ -44,119 +44,85 @@

    Module nitric.faas.faas

    # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Callable, Union +import traceback +from typing import Callable, Union, Coroutine, Any -from flask import Flask, request -from waitress import serve +import betterproto +from betterproto.grpc.util.async_channel import AsyncChannel -from nitric.proto.faas.v1.faas_pb2 import TriggerRequest, TriggerResponse -from nitric.config import settings +from nitric.utils import new_default_channel from nitric.faas import Trigger, Response -from google.protobuf import json_format +from nitric.proto.nitric.faas.v1 import FaasStub, InitRequest, ClientMessage +import asyncio -def construct_request() -> TriggerRequest: - """Construct a Nitric Request object from the Flask HTTP Request.""" - # full_path used to better match behavior in other SDKs - # return TriggerRequest(dict(request.headers), request.get_data(), path=request.full_path) - message = json_format.Parse(request.get_data(), TriggerRequest(), ignore_unknown_fields=False) - return message - - -def http_response(response: TriggerResponse): +async def _register_faas_worker( + func: Callable[[Trigger], Union[Coroutine[Any, Any, Union[Response, None, dict]], Union[Response, None, dict]]] +): """ - Return a full HTTP response tuple based on the Nitric Response contents. + Register a new FaaS worker with the Membrane, using the provided function as the handler. - The response includes a body, status and headers as appropriate. + :param func: handler function for incoming triggers. Can be sync or async, async is preferred. """ - headers = {"Content-Type": "application/json"} - - return json_format.MessageToJson(response), 200, headers - - -def exception_to_html(): - """Return a traceback as HTML.""" - import traceback - import sys - import html - - limit = None - exception_type, value, tb = sys.exc_info() - trace_list = traceback.format_tb(tb, limit) + traceback.format_exception_only(exception_type, value) - body = "Traceback:\n" + "%-20s %s" % ("".join(trace_list[:-1]), trace_list[-1]) - return ( - "<html><head><title>Error</title></head><body><h2>An Error Occurred:</h2>\n<pre>" - + html.escape(body) - + "</pre></body></html>\n" - ) - - -class Handler(object): - """Nitric Function handler.""" - - def __init__(self, func: Callable[[Trigger], Union[Response, str]]): - """Construct a new handler using the provided function to handle new requests.""" - self.func = func - - def __call__(self, path="", *args): - """Construct Nitric Request from HTTP Request.""" - trigger_request = construct_request() - - grpc_trigger_response: TriggerResponse - - # convert it to a trigger - trigger = Trigger.from_trigger_request(trigger_request) - - try: - # Execute the handler function - response: Union[Response, str] = self.func(trigger) - - final_response: Response - if isinstance(response, str): - final_response = trigger.default_response() - final_response.data = response.encode() - elif isinstance(response, Response): - final_response = response + channel = new_default_channel() + client = FaasStub(channel) + request_channel = AsyncChannel(close=True) + # We can start be sending all the requests we already have + try: + await request_channel.send(ClientMessage(init_request=InitRequest())) + async for srv_msg in client.trigger_stream(request_channel): + # The response iterator will remain active until the connection is closed + msg_type, val = betterproto.which_one_of(srv_msg, "content") + + if msg_type == "init_response": + print("function connected to Membrane") + # We don't need to reply + # proceed to the next available message + continue + if msg_type == "trigger_request": + trigger = Trigger.from_trigger_request(srv_msg.trigger_request) + try: + response = await func(trigger) if asyncio.iscoroutinefunction(func) else func(trigger) + except Exception: + print("Error calling handler function") + traceback.print_exc() + response = trigger.default_response() + if response.context.is_http(): + response.context.as_http().status = 500 + else: + response.context.as_topic().success = False + + # Handle lite responses with just data, assume a success in these cases + if not isinstance(response, Response): + full_response = trigger.default_response() + full_response.data = bytes(str(response), "utf-8") + response = full_response + + # Send function response back to server + await request_channel.send( + ClientMessage(id=srv_msg.id, trigger_response=response.to_grpc_trigger_response_context()) + ) else: - # assume None - final_response = trigger.default_response() - final_response.data = "".encode() - - grpc_trigger_response = final_response.to_grpc_trigger_response_context() - - except Exception: - trigger_response = trigger.default_response() - if trigger_response.context.is_http(): - trigger_response.context.as_http().status = 500 - trigger_response.context.as_http().headers = {"Content-Type": "text/html"} - trigger_response.data = exception_to_html().encode() - elif trigger_response.context.is_topic(): - trigger_response.data = "Error processing message" - trigger_response.context.as_topic().success = False - - grpc_trigger_response = trigger_response.to_grpc_trigger_response_context() - - return http_response(grpc_trigger_response) - - -def start(func: Callable[[Trigger], Union[Response, str]]): + print("unhandled message type {0}, skipping".format(msg_type)) + continue + if request_channel.done(): + break + except Exception: + traceback.print_exc() + finally: + print("stream from Membrane closed, closing client stream") + # The channel must be closed to complete the gRPC connection + request_channel.close() + channel.close() + + +def start(handler: Callable[[Trigger], Coroutine[Any, Any, Union[Response, None, dict]]]): """ - Register the provided function as the request handler and starts handling new requests. + Register the provided function as the trigger handler and starts handling new trigger requests. - :param func: to use to handle new requests + :param handler: handler function for incoming triggers. Can be sync or async, async is preferred. """ - app = Flask(__name__) - app.add_url_rule("/", "index", Handler(func), methods=["GET", "PUT", "POST", "PATCH", "DELETE"]) - app.add_url_rule( - "/<path:path>", - "path", - Handler(func), - methods=["GET", "PUT", "POST", "PATCH", "DELETE"], - ) - - host, port = f"{settings.CHILD_ADDRESS}".split(":") - # Start the function HTTP server - serve(app, host=host, port=int(port))
    + asyncio.run(_register_faas_worker(handler))
  • @@ -166,103 +132,29 @@

    Module nitric.faas.faas

    Functions

    -
    -def construct_request() ‑> faas.v1.faas_pb2.TriggerRequest -
    -
    -

    Construct a Nitric Request object from the Flask HTTP Request.

    -
    - -Expand source code - -
    def construct_request() -> TriggerRequest:
    -    """Construct a Nitric Request object from the Flask HTTP Request."""
    -    # full_path used to better match behavior in other SDKs
    -    # return TriggerRequest(dict(request.headers), request.get_data(), path=request.full_path)
    -    message = json_format.Parse(request.get_data(), TriggerRequest(), ignore_unknown_fields=False)
    -    return message
    -
    -
    -
    -def exception_to_html() -
    -
    -

    Return a traceback as HTML.

    -
    - -Expand source code - -
    def exception_to_html():
    -    """Return a traceback as HTML."""
    -    import traceback
    -    import sys
    -    import html
    -
    -    limit = None
    -    exception_type, value, tb = sys.exc_info()
    -    trace_list = traceback.format_tb(tb, limit) + traceback.format_exception_only(exception_type, value)
    -    body = "Traceback:\n" + "%-20s %s" % ("".join(trace_list[:-1]), trace_list[-1])
    -    return (
    -        "<html><head><title>Error</title></head><body><h2>An Error Occurred:</h2>\n<pre>"
    -        + html.escape(body)
    -        + "</pre></body></html>\n"
    -    )
    -
    -
    -
    -def http_response(response: faas.v1.faas_pb2.TriggerResponse) -
    -
    -

    Return a full HTTP response tuple based on the Nitric Response contents.

    -

    The response includes a body, status and headers as appropriate.

    -
    - -Expand source code - -
    def http_response(response: TriggerResponse):
    -    """
    -    Return a full HTTP response tuple based on the Nitric Response contents.
    -
    -    The response includes a body, status and headers as appropriate.
    -    """
    -    headers = {"Content-Type": "application/json"}
    -
    -    return json_format.MessageToJson(response), 200, headers
    -
    -
    -def start(func: Callable[[Trigger], Union[Response, str]]) +def start(handler: Callable[[Trigger], Coroutine[Any, Any, Union[Response, NoneType, dict]]])
    -

    Register the provided function as the request handler and starts handling new requests.

    -

    :param func: to use to handle new requests

    +

    Register the provided function as the trigger handler and starts handling new trigger requests.

    +

    :param handler: handler function for incoming triggers. Can be sync or async, async is preferred.

    Expand source code -
    def start(func: Callable[[Trigger], Union[Response, str]]):
    +
    def start(handler: Callable[[Trigger], Coroutine[Any, Any, Union[Response, None, dict]]]):
         """
    -    Register the provided function as the request handler and starts handling new requests.
    +    Register the provided function as the trigger handler and starts handling new trigger requests.
     
    -    :param func: to use to handle new requests
    +    :param handler: handler function for incoming triggers. Can be sync or async, async is preferred.
         """
    -    app = Flask(__name__)
    -    app.add_url_rule("/", "index", Handler(func), methods=["GET", "PUT", "POST", "PATCH", "DELETE"])
    -    app.add_url_rule(
    -        "/<path:path>",
    -        "path",
    -        Handler(func),
    -        methods=["GET", "PUT", "POST", "PATCH", "DELETE"],
    -    )
    -
    -    host, port = f"{settings.CHILD_ADDRESS}".split(":")
    -    # Start the function HTTP server
    -    serve(app, host=host, port=int(port))
    + asyncio.run(_register_faas_worker(handler))
    +<<<<<<< refs/remotes/origin/main

    Classes

    @@ -397,6 +289,8 @@

    Instance variables

    +======= +>>>>>>> feat: port faas.start to bi-di streaming with membrane
    @@ -684,6 +703,12 @@

    Index

    diff --git a/docs/nitric/index.html b/docs/nitric/index.html index 4b52622..4db1f09 100644 --- a/docs/nitric/index.html +++ b/docs/nitric/index.html @@ -67,6 +67,10 @@

    Sub-modules

    +
    nitric.utils
    +
    +
    +
    @@ -88,6 +92,7 @@

    Index

  • nitric.config
  • nitric.faas
  • nitric.proto
  • +
  • nitric.utils
  • diff --git a/docs/nitric/proto/auth/v1/auth_pb2.html b/docs/nitric/proto/auth/v1/auth_pb2.html deleted file mode 100644 index 3ed5f5b..0000000 --- a/docs/nitric/proto/auth/v1/auth_pb2.html +++ /dev/null @@ -1,309 +0,0 @@ - - - - - - -nitric.proto.auth.v1.auth_pb2 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.auth.v1.auth_pb2

    -
    -
    -

    Generated protocol buffer code.

    -
    - -Expand source code - -
    # -*- coding: utf-8 -*-
    -#
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the protocol buffer compiler.  DO NOT EDIT!
    -# source: auth/v1/auth.proto
    -"""Generated protocol buffer code."""
    -from google.protobuf import descriptor as _descriptor
    -from google.protobuf import message as _message
    -from google.protobuf import reflection as _reflection
    -from google.protobuf import symbol_database as _symbol_database
    -# @@protoc_insertion_point(imports)
    -
    -_sym_db = _symbol_database.Default()
    -
    -
    -
    -
    -DESCRIPTOR = _descriptor.FileDescriptor(
    -  name='auth/v1/auth.proto',
    -  package='nitric.auth.v1',
    -  syntax='proto3',
    -  serialized_options=b'\n\027io.nitric.proto.auth.v1B\004AuthP\001Z\014nitric/v1;v1\252\002\024Nitric.Proto.Auth.v1\312\002\024Nitric\\Proto\\Auth\\V1',
    -  create_key=_descriptor._internal_create_key,
    -  serialized_pb=b'\n\x12\x61uth/v1/auth.proto\x12\x0enitric.auth.v1\"P\n\x11UserCreateRequest\x12\x0e\n\x06tenant\x18\x01 \x01(\t\x12\n\n\x02id\x18\x02 \x01(\t\x12\r\n\x05\x65mail\x18\x03 \x01(\t\x12\x10\n\x08password\x18\x04 \x01(\t\"\x14\n\x12UserCreateResponse2W\n\x04User\x12O\n\x06\x43reate\x12!.nitric.auth.v1.UserCreateRequest\x1a\".nitric.auth.v1.UserCreateResponseB]\n\x17io.nitric.proto.auth.v1B\x04\x41uthP\x01Z\x0cnitric/v1;v1\xaa\x02\x14Nitric.Proto.Auth.v1\xca\x02\x14Nitric\\Proto\\Auth\\V1b\x06proto3'
    -)
    -
    -
    -
    -
    -_USERCREATEREQUEST = _descriptor.Descriptor(
    -  name='UserCreateRequest',
    -  full_name='nitric.auth.v1.UserCreateRequest',
    -  filename=None,
    -  file=DESCRIPTOR,
    -  containing_type=None,
    -  create_key=_descriptor._internal_create_key,
    -  fields=[
    -    _descriptor.FieldDescriptor(
    -      name='tenant', full_name='nitric.auth.v1.UserCreateRequest.tenant', index=0,
    -      number=1, type=9, cpp_type=9, label=1,
    -      has_default_value=False, default_value=b"".decode('utf-8'),
    -      message_type=None, enum_type=None, containing_type=None,
    -      is_extension=False, extension_scope=None,
    -      serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key),
    -    _descriptor.FieldDescriptor(
    -      name='id', full_name='nitric.auth.v1.UserCreateRequest.id', index=1,
    -      number=2, type=9, cpp_type=9, label=1,
    -      has_default_value=False, default_value=b"".decode('utf-8'),
    -      message_type=None, enum_type=None, containing_type=None,
    -      is_extension=False, extension_scope=None,
    -      serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key),
    -    _descriptor.FieldDescriptor(
    -      name='email', full_name='nitric.auth.v1.UserCreateRequest.email', index=2,
    -      number=3, type=9, cpp_type=9, label=1,
    -      has_default_value=False, default_value=b"".decode('utf-8'),
    -      message_type=None, enum_type=None, containing_type=None,
    -      is_extension=False, extension_scope=None,
    -      serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key),
    -    _descriptor.FieldDescriptor(
    -      name='password', full_name='nitric.auth.v1.UserCreateRequest.password', index=3,
    -      number=4, type=9, cpp_type=9, label=1,
    -      has_default_value=False, default_value=b"".decode('utf-8'),
    -      message_type=None, enum_type=None, containing_type=None,
    -      is_extension=False, extension_scope=None,
    -      serialized_options=None, file=DESCRIPTOR,  create_key=_descriptor._internal_create_key),
    -  ],
    -  extensions=[
    -  ],
    -  nested_types=[],
    -  enum_types=[
    -  ],
    -  serialized_options=None,
    -  is_extendable=False,
    -  syntax='proto3',
    -  extension_ranges=[],
    -  oneofs=[
    -  ],
    -  serialized_start=38,
    -  serialized_end=118,
    -)
    -
    -
    -_USERCREATERESPONSE = _descriptor.Descriptor(
    -  name='UserCreateResponse',
    -  full_name='nitric.auth.v1.UserCreateResponse',
    -  filename=None,
    -  file=DESCRIPTOR,
    -  containing_type=None,
    -  create_key=_descriptor._internal_create_key,
    -  fields=[
    -  ],
    -  extensions=[
    -  ],
    -  nested_types=[],
    -  enum_types=[
    -  ],
    -  serialized_options=None,
    -  is_extendable=False,
    -  syntax='proto3',
    -  extension_ranges=[],
    -  oneofs=[
    -  ],
    -  serialized_start=120,
    -  serialized_end=140,
    -)
    -
    -DESCRIPTOR.message_types_by_name['UserCreateRequest'] = _USERCREATEREQUEST
    -DESCRIPTOR.message_types_by_name['UserCreateResponse'] = _USERCREATERESPONSE
    -_sym_db.RegisterFileDescriptor(DESCRIPTOR)
    -
    -UserCreateRequest = _reflection.GeneratedProtocolMessageType('UserCreateRequest', (_message.Message,), {
    -  'DESCRIPTOR' : _USERCREATEREQUEST,
    -  '__module__' : 'auth.v1.auth_pb2'
    -  # @@protoc_insertion_point(class_scope:nitric.auth.v1.UserCreateRequest)
    -  })
    -_sym_db.RegisterMessage(UserCreateRequest)
    -
    -UserCreateResponse = _reflection.GeneratedProtocolMessageType('UserCreateResponse', (_message.Message,), {
    -  'DESCRIPTOR' : _USERCREATERESPONSE,
    -  '__module__' : 'auth.v1.auth_pb2'
    -  # @@protoc_insertion_point(class_scope:nitric.auth.v1.UserCreateResponse)
    -  })
    -_sym_db.RegisterMessage(UserCreateResponse)
    -
    -
    -DESCRIPTOR._options = None
    -
    -_USER = _descriptor.ServiceDescriptor(
    -  name='User',
    -  full_name='nitric.auth.v1.User',
    -  file=DESCRIPTOR,
    -  index=0,
    -  serialized_options=None,
    -  create_key=_descriptor._internal_create_key,
    -  serialized_start=142,
    -  serialized_end=229,
    -  methods=[
    -  _descriptor.MethodDescriptor(
    -    name='Create',
    -    full_name='nitric.auth.v1.User.Create',
    -    index=0,
    -    containing_service=None,
    -    input_type=_USERCREATEREQUEST,
    -    output_type=_USERCREATERESPONSE,
    -    serialized_options=None,
    -    create_key=_descriptor._internal_create_key,
    -  ),
    -])
    -_sym_db.RegisterServiceDescriptor(_USER)
    -
    -DESCRIPTOR.services_by_name['User'] = _USER
    -
    -# @@protoc_insertion_point(module_scope)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class UserCreateRequest -(*args, **kwargs) -
    -
    -

    A ProtocolMessage

    -

    Ancestors

    -
      -
    • google.protobuf.pyext._message.CMessage
    • -
    • google.protobuf.message.Message
    • -
    -

    Class variables

    -
    -
    var DESCRIPTOR
    -
    -
    -
    -
    -

    Instance variables

    -
    -
    var email
    -
    -

    Field nitric.auth.v1.UserCreateRequest.email

    -
    -
    var id
    -
    -

    Field nitric.auth.v1.UserCreateRequest.id

    -
    -
    var password
    -
    -

    Field nitric.auth.v1.UserCreateRequest.password

    -
    -
    var tenant
    -
    -

    Field nitric.auth.v1.UserCreateRequest.tenant

    -
    -
    -
    -
    -class UserCreateResponse -(*args, **kwargs) -
    -
    -

    A ProtocolMessage

    -

    Ancestors

    -
      -
    • google.protobuf.pyext._message.CMessage
    • -
    • google.protobuf.message.Message
    • -
    -

    Class variables

    -
    -
    var DESCRIPTOR
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/auth/v1/auth_pb2_grpc.html b/docs/nitric/proto/auth/v1/auth_pb2_grpc.html deleted file mode 100644 index 205735f..0000000 --- a/docs/nitric/proto/auth/v1/auth_pb2_grpc.html +++ /dev/null @@ -1,335 +0,0 @@ - - - - - - -nitric.proto.auth.v1.auth_pb2_grpc API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.auth.v1.auth_pb2_grpc

    -
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
    -"""Client and server classes corresponding to protobuf-defined services."""
    -import grpc
    -
    -from nitric.proto.auth.v1 import auth_pb2 as auth_dot_v1_dot_auth__pb2
    -
    -
    -class UserStub(object):
    -    """Service for user management activities, such as creating and deleting users
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Create = channel.unary_unary(
    -                '/nitric.auth.v1.User/Create',
    -                request_serializer=auth_dot_v1_dot_auth__pb2.UserCreateRequest.SerializeToString,
    -                response_deserializer=auth_dot_v1_dot_auth__pb2.UserCreateResponse.FromString,
    -                )
    -
    -
    -class UserServicer(object):
    -    """Service for user management activities, such as creating and deleting users
    -    """
    -
    -    def Create(self, request, context):
    -        """Create a new user in a tenant
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_UserServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Create': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Create,
    -                    request_deserializer=auth_dot_v1_dot_auth__pb2.UserCreateRequest.FromString,
    -                    response_serializer=auth_dot_v1_dot_auth__pb2.UserCreateResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.auth.v1.User', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class User(object):
    -    """Service for user management activities, such as creating and deleting users
    -    """
    -
    -    @staticmethod
    -    def Create(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.auth.v1.User/Create',
    -            auth_dot_v1_dot_auth__pb2.UserCreateRequest.SerializeToString,
    -            auth_dot_v1_dot_auth__pb2.UserCreateResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def add_UserServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_UserServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Create': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Create,
    -                    request_deserializer=auth_dot_v1_dot_auth__pb2.UserCreateRequest.FromString,
    -                    response_serializer=auth_dot_v1_dot_auth__pb2.UserCreateResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.auth.v1.User', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class User -
    -
    -

    Service for user management activities, such as creating and deleting users

    -
    - -Expand source code - -
    class User(object):
    -    """Service for user management activities, such as creating and deleting users
    -    """
    -
    -    @staticmethod
    -    def Create(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.auth.v1.User/Create',
    -            auth_dot_v1_dot_auth__pb2.UserCreateRequest.SerializeToString,
    -            auth_dot_v1_dot_auth__pb2.UserCreateResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def Create(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Create(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.auth.v1.User/Create',
    -        auth_dot_v1_dot_auth__pb2.UserCreateRequest.SerializeToString,
    -        auth_dot_v1_dot_auth__pb2.UserCreateResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class UserServicer -
    -
    -

    Service for user management activities, such as creating and deleting users

    -
    - -Expand source code - -
    class UserServicer(object):
    -    """Service for user management activities, such as creating and deleting users
    -    """
    -
    -    def Create(self, request, context):
    -        """Create a new user in a tenant
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def Create(self, request, context) -
    -
    -

    Create a new user in a tenant

    -
    - -Expand source code - -
    def Create(self, request, context):
    -    """Create a new user in a tenant
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class UserStub -(channel) -
    -
    -

    Service for user management activities, such as creating and deleting users

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class UserStub(object):
    -    """Service for user management activities, such as creating and deleting users
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Create = channel.unary_unary(
    -                '/nitric.auth.v1.User/Create',
    -                request_serializer=auth_dot_v1_dot_auth__pb2.UserCreateRequest.SerializeToString,
    -                response_deserializer=auth_dot_v1_dot_auth__pb2.UserCreateResponse.FromString,
    -                )
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/auth/v1/index.html b/docs/nitric/proto/auth/v1/index.html deleted file mode 100644 index 80ff29f..0000000 --- a/docs/nitric/proto/auth/v1/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - -nitric.proto.auth.v1 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.auth.v1

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.auth.v1.auth_pb2
    -
    -

    Generated protocol buffer code.

    -
    -
    nitric.proto.auth.v1.auth_pb2_grpc
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/event/v1/event_pb2_grpc.html b/docs/nitric/proto/event/v1/event_pb2_grpc.html deleted file mode 100644 index cde6c86..0000000 --- a/docs/nitric/proto/event/v1/event_pb2_grpc.html +++ /dev/null @@ -1,573 +0,0 @@ - - - - - - -nitric.proto.event.v1.event_pb2_grpc API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.event.v1.event_pb2_grpc

    -
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
    -"""Client and server classes corresponding to protobuf-defined services."""
    -import grpc
    -
    -from nitric.proto.event.v1 import event_pb2 as event_dot_v1_dot_event__pb2
    -
    -
    -class EventStub(object):
    -    """Service for publishing asynchronous event
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Publish = channel.unary_unary(
    -                '/nitric.event.v1.Event/Publish',
    -                request_serializer=event_dot_v1_dot_event__pb2.EventPublishRequest.SerializeToString,
    -                response_deserializer=event_dot_v1_dot_event__pb2.EventPublishResponse.FromString,
    -                )
    -
    -
    -class EventServicer(object):
    -    """Service for publishing asynchronous event
    -    """
    -
    -    def Publish(self, request, context):
    -        """Publishes an message to a given topic
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_EventServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Publish': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Publish,
    -                    request_deserializer=event_dot_v1_dot_event__pb2.EventPublishRequest.FromString,
    -                    response_serializer=event_dot_v1_dot_event__pb2.EventPublishResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.event.v1.Event', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class Event(object):
    -    """Service for publishing asynchronous event
    -    """
    -
    -    @staticmethod
    -    def Publish(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.event.v1.Event/Publish',
    -            event_dot_v1_dot_event__pb2.EventPublishRequest.SerializeToString,
    -            event_dot_v1_dot_event__pb2.EventPublishResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -class TopicStub(object):
    -    """Service for management of event topics
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.List = channel.unary_unary(
    -                '/nitric.event.v1.Topic/List',
    -                request_serializer=event_dot_v1_dot_event__pb2.TopicListRequest.SerializeToString,
    -                response_deserializer=event_dot_v1_dot_event__pb2.TopicListResponse.FromString,
    -                )
    -
    -
    -class TopicServicer(object):
    -    """Service for management of event topics
    -    """
    -
    -    def List(self, request, context):
    -        """Return a list of existing topics in the provider environment
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_TopicServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'List': grpc.unary_unary_rpc_method_handler(
    -                    servicer.List,
    -                    request_deserializer=event_dot_v1_dot_event__pb2.TopicListRequest.FromString,
    -                    response_serializer=event_dot_v1_dot_event__pb2.TopicListResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.event.v1.Topic', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class Topic(object):
    -    """Service for management of event topics
    -    """
    -
    -    @staticmethod
    -    def List(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.event.v1.Topic/List',
    -            event_dot_v1_dot_event__pb2.TopicListRequest.SerializeToString,
    -            event_dot_v1_dot_event__pb2.TopicListResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def add_EventServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_EventServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Publish': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Publish,
    -                    request_deserializer=event_dot_v1_dot_event__pb2.EventPublishRequest.FromString,
    -                    response_serializer=event_dot_v1_dot_event__pb2.EventPublishResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.event.v1.Event', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -def add_TopicServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_TopicServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'List': grpc.unary_unary_rpc_method_handler(
    -                    servicer.List,
    -                    request_deserializer=event_dot_v1_dot_event__pb2.TopicListRequest.FromString,
    -                    response_serializer=event_dot_v1_dot_event__pb2.TopicListResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.event.v1.Topic', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Event -
    -
    -

    Service for publishing asynchronous event

    -
    - -Expand source code - -
    class Event(object):
    -    """Service for publishing asynchronous event
    -    """
    -
    -    @staticmethod
    -    def Publish(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.event.v1.Event/Publish',
    -            event_dot_v1_dot_event__pb2.EventPublishRequest.SerializeToString,
    -            event_dot_v1_dot_event__pb2.EventPublishResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def Publish(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Publish(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.event.v1.Event/Publish',
    -        event_dot_v1_dot_event__pb2.EventPublishRequest.SerializeToString,
    -        event_dot_v1_dot_event__pb2.EventPublishResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class EventServicer -
    -
    -

    Service for publishing asynchronous event

    -
    - -Expand source code - -
    class EventServicer(object):
    -    """Service for publishing asynchronous event
    -    """
    -
    -    def Publish(self, request, context):
    -        """Publishes an message to a given topic
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def Publish(self, request, context) -
    -
    -

    Publishes an message to a given topic

    -
    - -Expand source code - -
    def Publish(self, request, context):
    -    """Publishes an message to a given topic
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class EventStub -(channel) -
    -
    -

    Service for publishing asynchronous event

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class EventStub(object):
    -    """Service for publishing asynchronous event
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Publish = channel.unary_unary(
    -                '/nitric.event.v1.Event/Publish',
    -                request_serializer=event_dot_v1_dot_event__pb2.EventPublishRequest.SerializeToString,
    -                response_deserializer=event_dot_v1_dot_event__pb2.EventPublishResponse.FromString,
    -                )
    -
    -
    -
    -class Topic -
    -
    -

    Service for management of event topics

    -
    - -Expand source code - -
    class Topic(object):
    -    """Service for management of event topics
    -    """
    -
    -    @staticmethod
    -    def List(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.event.v1.Topic/List',
    -            event_dot_v1_dot_event__pb2.TopicListRequest.SerializeToString,
    -            event_dot_v1_dot_event__pb2.TopicListResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def List(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def List(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.event.v1.Topic/List',
    -        event_dot_v1_dot_event__pb2.TopicListRequest.SerializeToString,
    -        event_dot_v1_dot_event__pb2.TopicListResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class TopicServicer -
    -
    -

    Service for management of event topics

    -
    - -Expand source code - -
    class TopicServicer(object):
    -    """Service for management of event topics
    -    """
    -
    -    def List(self, request, context):
    -        """Return a list of existing topics in the provider environment
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def List(self, request, context) -
    -
    -

    Return a list of existing topics in the provider environment

    -
    - -Expand source code - -
    def List(self, request, context):
    -    """Return a list of existing topics in the provider environment
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class TopicStub -(channel) -
    -
    -

    Service for management of event topics

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class TopicStub(object):
    -    """Service for management of event topics
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.List = channel.unary_unary(
    -                '/nitric.event.v1.Topic/List',
    -                request_serializer=event_dot_v1_dot_event__pb2.TopicListRequest.SerializeToString,
    -                response_deserializer=event_dot_v1_dot_event__pb2.TopicListResponse.FromString,
    -                )
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/event/v1/index.html b/docs/nitric/proto/event/v1/index.html deleted file mode 100644 index 771c64c..0000000 --- a/docs/nitric/proto/event/v1/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - -nitric.proto.event.v1 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.event.v1

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.event.v1.event_pb2
    -
    -

    Generated protocol buffer code.

    -
    -
    nitric.proto.event.v1.event_pb2_grpc
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/faas/v1/faas_pb2_grpc.html b/docs/nitric/proto/faas/v1/faas_pb2_grpc.html deleted file mode 100644 index 05f1070..0000000 --- a/docs/nitric/proto/faas/v1/faas_pb2_grpc.html +++ /dev/null @@ -1,335 +0,0 @@ - - - - - - -nitric.proto.faas.v1.faas_pb2_grpc API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.faas.v1.faas_pb2_grpc

    -
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
    -"""Client and server classes corresponding to protobuf-defined services."""
    -import grpc
    -
    -from nitric.proto.faas.v1 import faas_pb2 as faas_dot_v1_dot_faas__pb2
    -
    -
    -class FaasStub(object):
    -    """Service for streaming communication with gRPC FaaS implementations
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.TriggerStream = channel.stream_stream(
    -                '/nitric.faas.v1.Faas/TriggerStream',
    -                request_serializer=faas_dot_v1_dot_faas__pb2.ClientMessage.SerializeToString,
    -                response_deserializer=faas_dot_v1_dot_faas__pb2.ServerMessage.FromString,
    -                )
    -
    -
    -class FaasServicer(object):
    -    """Service for streaming communication with gRPC FaaS implementations
    -    """
    -
    -    def TriggerStream(self, request_iterator, context):
    -        """Begin streaming triggers/response to/from the membrane
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_FaasServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'TriggerStream': grpc.stream_stream_rpc_method_handler(
    -                    servicer.TriggerStream,
    -                    request_deserializer=faas_dot_v1_dot_faas__pb2.ClientMessage.FromString,
    -                    response_serializer=faas_dot_v1_dot_faas__pb2.ServerMessage.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.faas.v1.Faas', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class Faas(object):
    -    """Service for streaming communication with gRPC FaaS implementations
    -    """
    -
    -    @staticmethod
    -    def TriggerStream(request_iterator,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.stream_stream(request_iterator, target, '/nitric.faas.v1.Faas/TriggerStream',
    -            faas_dot_v1_dot_faas__pb2.ClientMessage.SerializeToString,
    -            faas_dot_v1_dot_faas__pb2.ServerMessage.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def add_FaasServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_FaasServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'TriggerStream': grpc.stream_stream_rpc_method_handler(
    -                    servicer.TriggerStream,
    -                    request_deserializer=faas_dot_v1_dot_faas__pb2.ClientMessage.FromString,
    -                    response_serializer=faas_dot_v1_dot_faas__pb2.ServerMessage.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.faas.v1.Faas', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Faas -
    -
    -

    Service for streaming communication with gRPC FaaS implementations

    -
    - -Expand source code - -
    class Faas(object):
    -    """Service for streaming communication with gRPC FaaS implementations
    -    """
    -
    -    @staticmethod
    -    def TriggerStream(request_iterator,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.stream_stream(request_iterator, target, '/nitric.faas.v1.Faas/TriggerStream',
    -            faas_dot_v1_dot_faas__pb2.ClientMessage.SerializeToString,
    -            faas_dot_v1_dot_faas__pb2.ServerMessage.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def TriggerStream(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def TriggerStream(request_iterator,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.stream_stream(request_iterator, target, '/nitric.faas.v1.Faas/TriggerStream',
    -        faas_dot_v1_dot_faas__pb2.ClientMessage.SerializeToString,
    -        faas_dot_v1_dot_faas__pb2.ServerMessage.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class FaasServicer -
    -
    -

    Service for streaming communication with gRPC FaaS implementations

    -
    - -Expand source code - -
    class FaasServicer(object):
    -    """Service for streaming communication with gRPC FaaS implementations
    -    """
    -
    -    def TriggerStream(self, request_iterator, context):
    -        """Begin streaming triggers/response to/from the membrane
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def TriggerStream(self, request_iterator, context) -
    -
    -

    Begin streaming triggers/response to/from the membrane

    -
    - -Expand source code - -
    def TriggerStream(self, request_iterator, context):
    -    """Begin streaming triggers/response to/from the membrane
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class FaasStub -(channel) -
    -
    -

    Service for streaming communication with gRPC FaaS implementations

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class FaasStub(object):
    -    """Service for streaming communication with gRPC FaaS implementations
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.TriggerStream = channel.stream_stream(
    -                '/nitric.faas.v1.Faas/TriggerStream',
    -                request_serializer=faas_dot_v1_dot_faas__pb2.ClientMessage.SerializeToString,
    -                response_deserializer=faas_dot_v1_dot_faas__pb2.ServerMessage.FromString,
    -                )
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/faas/v1/index.html b/docs/nitric/proto/faas/v1/index.html deleted file mode 100644 index e8009d2..0000000 --- a/docs/nitric/proto/faas/v1/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - -nitric.proto.faas.v1 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.faas.v1

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.faas.v1.faas_pb2
    -
    -

    Generated protocol buffer code.

    -
    -
    nitric.proto.faas.v1.faas_pb2_grpc
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/index.html b/docs/nitric/proto/index.html index 3342a7b..185a8d4 100644 --- a/docs/nitric/proto/index.html +++ b/docs/nitric/proto/index.html @@ -43,48 +43,13 @@

    Module nitric.proto

    # 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. -# -from nitric.proto.event.v1 import event_pb2 as event -from nitric.proto.event.v1 import event_pb2_grpc as event_service -from nitric.proto.storage.v1 import storage_pb2 as storage -from nitric.proto.storage.v1 import storage_pb2_grpc as storage_service -from nitric.proto.kv.v1 import kv_pb2 as key_value -from nitric.proto.kv.v1 import kv_pb2_grpc as key_value_service -from nitric.proto.queue.v1 import queue_pb2 as queue -from nitric.proto.queue.v1 import queue_pb2_grpc as queue_service - -__all__ = [ - "event", - "event_service", - "storage", - "storage_service", - "key_value", - "key_value_service", - "queue", - "queue_service", -]
    +#

    Sub-modules

    -
    nitric.proto.event
    -
    -
    -
    -
    nitric.proto.faas
    -
    -
    -
    -
    nitric.proto.kv
    -
    -
    -
    -
    nitric.proto.queue
    -
    -
    -
    -
    nitric.proto.storage
    +
    nitric.proto.nitric
    @@ -110,11 +75,7 @@

    Index

  • Sub-modules

  • diff --git a/docs/nitric/proto/kv/v1/index.html b/docs/nitric/proto/kv/v1/index.html deleted file mode 100644 index 74a569e..0000000 --- a/docs/nitric/proto/kv/v1/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - -nitric.proto.kv.v1 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.kv.v1

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.kv.v1.kv_pb2
    -
    -

    Generated protocol buffer code.

    -
    -
    nitric.proto.kv.v1.kv_pb2_grpc
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/kv/v1/kv_pb2_grpc.html b/docs/nitric/proto/kv/v1/kv_pb2_grpc.html deleted file mode 100644 index 65e2be8..0000000 --- a/docs/nitric/proto/kv/v1/kv_pb2_grpc.html +++ /dev/null @@ -1,563 +0,0 @@ - - - - - - -nitric.proto.kv.v1.kv_pb2_grpc API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.kv.v1.kv_pb2_grpc

    -
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
    -"""Client and server classes corresponding to protobuf-defined services."""
    -import grpc
    -
    -from nitric.proto.kv.v1 import kv_pb2 as kv_dot_v1_dot_kv__pb2
    -
    -
    -class KeyValueStub(object):
    -    """Service for storage and retrieval of simple JSON keyValue
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Get = channel.unary_unary(
    -                '/nitric.kv.v1.KeyValue/Get',
    -                request_serializer=kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.SerializeToString,
    -                response_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.FromString,
    -                )
    -        self.Put = channel.unary_unary(
    -                '/nitric.kv.v1.KeyValue/Put',
    -                request_serializer=kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.SerializeToString,
    -                response_deserializer=kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.FromString,
    -                )
    -        self.Delete = channel.unary_unary(
    -                '/nitric.kv.v1.KeyValue/Delete',
    -                request_serializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.SerializeToString,
    -                response_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.FromString,
    -                )
    -
    -
    -class KeyValueServicer(object):
    -    """Service for storage and retrieval of simple JSON keyValue
    -    """
    -
    -    def Get(self, request, context):
    -        """Get an existing key
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Put(self, request, context):
    -        """Create a new or overwrite and existing key
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Delete(self, request, context):
    -        """Delete an existing
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_KeyValueServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Get': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Get,
    -                    request_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.FromString,
    -                    response_serializer=kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.SerializeToString,
    -            ),
    -            'Put': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Put,
    -                    request_deserializer=kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.FromString,
    -                    response_serializer=kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.SerializeToString,
    -            ),
    -            'Delete': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Delete,
    -                    request_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.FromString,
    -                    response_serializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.kv.v1.KeyValue', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class KeyValue(object):
    -    """Service for storage and retrieval of simple JSON keyValue
    -    """
    -
    -    @staticmethod
    -    def Get(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Get',
    -            kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.SerializeToString,
    -            kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Put(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Put',
    -            kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.SerializeToString,
    -            kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Delete(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Delete',
    -            kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.SerializeToString,
    -            kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def add_KeyValueServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_KeyValueServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Get': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Get,
    -                    request_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.FromString,
    -                    response_serializer=kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.SerializeToString,
    -            ),
    -            'Put': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Put,
    -                    request_deserializer=kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.FromString,
    -                    response_serializer=kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.SerializeToString,
    -            ),
    -            'Delete': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Delete,
    -                    request_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.FromString,
    -                    response_serializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.kv.v1.KeyValue', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class KeyValue -
    -
    -

    Service for storage and retrieval of simple JSON keyValue

    -
    - -Expand source code - -
    class KeyValue(object):
    -    """Service for storage and retrieval of simple JSON keyValue
    -    """
    -
    -    @staticmethod
    -    def Get(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Get',
    -            kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.SerializeToString,
    -            kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Put(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Put',
    -            kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.SerializeToString,
    -            kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Delete(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Delete',
    -            kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.SerializeToString,
    -            kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def Delete(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Delete(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Delete',
    -        kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.SerializeToString,
    -        kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def Get(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Get(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Get',
    -        kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.SerializeToString,
    -        kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def Put(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Put(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.kv.v1.KeyValue/Put',
    -        kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.SerializeToString,
    -        kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class KeyValueServicer -
    -
    -

    Service for storage and retrieval of simple JSON keyValue

    -
    - -Expand source code - -
    class KeyValueServicer(object):
    -    """Service for storage and retrieval of simple JSON keyValue
    -    """
    -
    -    def Get(self, request, context):
    -        """Get an existing key
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Put(self, request, context):
    -        """Create a new or overwrite and existing key
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Delete(self, request, context):
    -        """Delete an existing
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def Delete(self, request, context) -
    -
    -

    Delete an existing

    -
    - -Expand source code - -
    def Delete(self, request, context):
    -    """Delete an existing
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def Get(self, request, context) -
    -
    -

    Get an existing key

    -
    - -Expand source code - -
    def Get(self, request, context):
    -    """Get an existing key
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def Put(self, request, context) -
    -
    -

    Create a new or overwrite and existing key

    -
    - -Expand source code - -
    def Put(self, request, context):
    -    """Create a new or overwrite and existing key
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class KeyValueStub -(channel) -
    -
    -

    Service for storage and retrieval of simple JSON keyValue

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class KeyValueStub(object):
    -    """Service for storage and retrieval of simple JSON keyValue
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Get = channel.unary_unary(
    -                '/nitric.kv.v1.KeyValue/Get',
    -                request_serializer=kv_dot_v1_dot_kv__pb2.KeyValueGetRequest.SerializeToString,
    -                response_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueGetResponse.FromString,
    -                )
    -        self.Put = channel.unary_unary(
    -                '/nitric.kv.v1.KeyValue/Put',
    -                request_serializer=kv_dot_v1_dot_kv__pb2.KeyValuePutRequest.SerializeToString,
    -                response_deserializer=kv_dot_v1_dot_kv__pb2.KeyValuePutResponse.FromString,
    -                )
    -        self.Delete = channel.unary_unary(
    -                '/nitric.kv.v1.KeyValue/Delete',
    -                request_serializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteRequest.SerializeToString,
    -                response_deserializer=kv_dot_v1_dot_kv__pb2.KeyValueDeleteResponse.FromString,
    -                )
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/event/index.html b/docs/nitric/proto/nitric/event/index.html similarity index 93% rename from docs/nitric/proto/event/index.html rename to docs/nitric/proto/nitric/event/index.html index 0754604..29bdace 100644 --- a/docs/nitric/proto/event/index.html +++ b/docs/nitric/proto/nitric/event/index.html @@ -4,7 +4,7 @@ -nitric.proto.event API documentation +nitric.proto.nitric.event API documentation @@ -19,7 +19,7 @@
    -

    Module nitric.proto.event

    +

    Module nitric.proto.nitric.event

    @@ -49,7 +49,7 @@

    Module nitric.proto.event

    Sub-modules

    -
    nitric.proto.event.v1
    +
    nitric.proto.nitric.event.v1
    @@ -70,12 +70,12 @@

    Index

    diff --git a/docs/nitric/proto/nitric/event/v1/index.html b/docs/nitric/proto/nitric/event/v1/index.html new file mode 100644 index 0000000..6f896a6 --- /dev/null +++ b/docs/nitric/proto/nitric/event/v1/index.html @@ -0,0 +1,661 @@ + + + + + + +nitric.proto.nitric.event.v1 API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric.event.v1

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +# Generated by the protocol buffer compiler.  DO NOT EDIT!
    +# sources: event/v1/event.proto
    +# plugin: python-betterproto
    +from dataclasses import dataclass
    +from typing import Dict, List
    +
    +import betterproto
    +from betterproto.grpc.grpclib_server import ServiceBase
    +import grpclib
    +
    +
    +@dataclass(eq=False, repr=False)
    +class EventPublishRequest(betterproto.Message):
    +    """Request to publish an event to a topic"""
    +
    +    # The name of the topic to publish the event to
    +    topic: str = betterproto.string_field(1)
    +    # The event to be published
    +    event: "NitricEvent" = betterproto.message_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class EventPublishResponse(betterproto.Message):
    +    """Result of publishing an event"""
    +
    +    # The id of the published message When an id was not supplied one should be
    +    # automatically generated
    +    id: str = betterproto.string_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class TopicListRequest(betterproto.Message):
    +    """Request for the Topic List method"""
    +
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class TopicListResponse(betterproto.Message):
    +    """Topic List Response"""
    +
    +    # The list of found topics
    +    topics: List["NitricTopic"] = betterproto.message_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class NitricTopic(betterproto.Message):
    +    """Represents an event topic"""
    +
    +    # The Nitric name for the topic
    +    name: str = betterproto.string_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class NitricEvent(betterproto.Message):
    +    """Nitric Event Model"""
    +
    +    # A Unique ID for the Nitric Event
    +    id: str = betterproto.string_field(1)
    +    # A content hint for the events payload
    +    payload_type: str = betterproto.string_field(2)
    +    # The payload of the event
    +    payload: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(3)
    +
    +
    +class EventStub(betterproto.ServiceStub):
    +    async def publish(self, *, topic: str = "", event: "NitricEvent" = None) -> "EventPublishResponse":
    +
    +        request = EventPublishRequest()
    +        request.topic = topic
    +        if event is not None:
    +            request.event = event
    +
    +        return await self._unary_unary("/nitric.event.v1.Event/Publish", request, EventPublishResponse)
    +
    +
    +class TopicStub(betterproto.ServiceStub):
    +    async def list(self) -> "TopicListResponse":
    +
    +        request = TopicListRequest()
    +
    +        return await self._unary_unary("/nitric.event.v1.Topic/List", request, TopicListResponse)
    +
    +
    +class EventBase(ServiceBase):
    +    async def publish(self, topic: str, event: "NitricEvent") -> "EventPublishResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_publish(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "topic": request.topic,
    +            "event": request.event,
    +        }
    +
    +        response = await self.publish(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.event.v1.Event/Publish": grpclib.const.Handler(
    +                self.__rpc_publish,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                EventPublishRequest,
    +                EventPublishResponse,
    +            ),
    +        }
    +
    +
    +class TopicBase(ServiceBase):
    +    async def list(self) -> "TopicListResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_list(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {}
    +
    +        response = await self.list(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.event.v1.Topic/List": grpclib.const.Handler(
    +                self.__rpc_list,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                TopicListRequest,
    +                TopicListResponse,
    +            ),
    +        }
    +
    +
    +import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class EventBase +
    +
    +

    Base class for async gRPC servers.

    +
    + +Expand source code + +
    class EventBase(ServiceBase):
    +    async def publish(self, topic: str, event: "NitricEvent") -> "EventPublishResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_publish(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "topic": request.topic,
    +            "event": request.event,
    +        }
    +
    +        response = await self.publish(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.event.v1.Event/Publish": grpclib.const.Handler(
    +                self.__rpc_publish,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                EventPublishRequest,
    +                EventPublishResponse,
    +            ),
    +        }
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_server.ServiceBase
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def publish(self, topic: str, event: NitricEvent) ‑> EventPublishResponse +
    +
    +
    +
    + +Expand source code + +
    async def publish(self, topic: str, event: "NitricEvent") -> "EventPublishResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +
    +
    +class EventPublishRequest +(topic: str = <object object>, event: NitricEvent = <object object>) +
    +
    +

    Request to publish an event to a topic

    +
    + +Expand source code + +
    class EventPublishRequest(betterproto.Message):
    +    """Request to publish an event to a topic"""
    +
    +    # The name of the topic to publish the event to
    +    topic: str = betterproto.string_field(1)
    +    # The event to be published
    +    event: "NitricEvent" = betterproto.message_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var event : NitricEvent
    +
    +
    +
    +
    var topic : str
    +
    +
    +
    +
    +
    +
    +class EventPublishResponse +(id: str = <object object>) +
    +
    +

    Result of publishing an event

    +
    + +Expand source code + +
    class EventPublishResponse(betterproto.Message):
    +    """Result of publishing an event"""
    +
    +    # The id of the published message When an id was not supplied one should be
    +    # automatically generated
    +    id: str = betterproto.string_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var id : str
    +
    +
    +
    +
    +
    +
    +class EventStub +(channel: Channel, *, timeout: Union[float, NoneType] = None, deadline: Union[ForwardRef('Deadline'), NoneType] = None, metadata: Union[Mapping[str, Union[str, bytes]], Collection[Tuple[str, Union[str, bytes]]], NoneType] = None) +
    +
    +

    Base class for async gRPC clients.

    +
    + +Expand source code + +
    class EventStub(betterproto.ServiceStub):
    +    async def publish(self, *, topic: str = "", event: "NitricEvent" = None) -> "EventPublishResponse":
    +
    +        request = EventPublishRequest()
    +        request.topic = topic
    +        if event is not None:
    +            request.event = event
    +
    +        return await self._unary_unary("/nitric.event.v1.Event/Publish", request, EventPublishResponse)
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_client.ServiceStub
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def publish(self, *, topic: str = '', event: NitricEvent = None) ‑> EventPublishResponse +
    +
    +
    +
    + +Expand source code + +
    async def publish(self, *, topic: str = "", event: "NitricEvent" = None) -> "EventPublishResponse":
    +
    +    request = EventPublishRequest()
    +    request.topic = topic
    +    if event is not None:
    +        request.event = event
    +
    +    return await self._unary_unary("/nitric.event.v1.Event/Publish", request, EventPublishResponse)
    +
    +
    +
    +
    +
    +class NitricEvent +(id: str = <object object>, payload_type: str = <object object>, payload: betterproto_lib_google_protobuf.Struct = <object object>) +
    +
    +

    Nitric Event Model

    +
    + +Expand source code + +
    class NitricEvent(betterproto.Message):
    +    """Nitric Event Model"""
    +
    +    # A Unique ID for the Nitric Event
    +    id: str = betterproto.string_field(1)
    +    # A content hint for the events payload
    +    payload_type: str = betterproto.string_field(2)
    +    # The payload of the event
    +    payload: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(3)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var id : str
    +
    +
    +
    +
    var payload : betterproto.lib.google.protobuf.Struct
    +
    +
    +
    +
    var payload_type : str
    +
    +
    +
    +
    +
    +
    +class NitricTopic +(name: str = <object object>) +
    +
    +

    Represents an event topic

    +
    + +Expand source code + +
    class NitricTopic(betterproto.Message):
    +    """Represents an event topic"""
    +
    +    # The Nitric name for the topic
    +    name: str = betterproto.string_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var name : str
    +
    +
    +
    +
    +
    +
    +class TopicBase +
    +
    +

    Base class for async gRPC servers.

    +
    + +Expand source code + +
    class TopicBase(ServiceBase):
    +    async def list(self) -> "TopicListResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_list(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {}
    +
    +        response = await self.list(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.event.v1.Topic/List": grpclib.const.Handler(
    +                self.__rpc_list,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                TopicListRequest,
    +                TopicListResponse,
    +            ),
    +        }
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_server.ServiceBase
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def list(self) ‑> TopicListResponse +
    +
    +
    +
    + +Expand source code + +
    async def list(self) -> "TopicListResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +
    +
    +class TopicListRequest +
    +
    +

    Request for the Topic List method

    +
    + +Expand source code + +
    class TopicListRequest(betterproto.Message):
    +    """Request for the Topic List method"""
    +
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class TopicListResponse +(topics: List[ForwardRef('NitricTopic')] = <object object>) +
    +
    +

    Topic List Response

    +
    + +Expand source code + +
    class TopicListResponse(betterproto.Message):
    +    """Topic List Response"""
    +
    +    # The list of found topics
    +    topics: List["NitricTopic"] = betterproto.message_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var topics : List[NitricTopic]
    +
    +
    +
    +
    +
    +
    +class TopicStub +(channel: Channel, *, timeout: Union[float, NoneType] = None, deadline: Union[ForwardRef('Deadline'), NoneType] = None, metadata: Union[Mapping[str, Union[str, bytes]], Collection[Tuple[str, Union[str, bytes]]], NoneType] = None) +
    +
    +

    Base class for async gRPC clients.

    +
    + +Expand source code + +
    class TopicStub(betterproto.ServiceStub):
    +    async def list(self) -> "TopicListResponse":
    +
    +        request = TopicListRequest()
    +
    +        return await self._unary_unary("/nitric.event.v1.Topic/List", request, TopicListResponse)
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_client.ServiceStub
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def list(self) ‑> TopicListResponse +
    +
    +
    +
    + +Expand source code + +
    async def list(self) -> "TopicListResponse":
    +
    +    request = TopicListRequest()
    +
    +    return await self._unary_unary("/nitric.event.v1.Topic/List", request, TopicListResponse)
    +
    +
    +
    +
    +
    +
    +
    + +
    + + + \ No newline at end of file diff --git a/docs/nitric/proto/kv/index.html b/docs/nitric/proto/nitric/faas/index.html similarity index 93% rename from docs/nitric/proto/kv/index.html rename to docs/nitric/proto/nitric/faas/index.html index 1b0c2a2..47bf2b3 100644 --- a/docs/nitric/proto/kv/index.html +++ b/docs/nitric/proto/nitric/faas/index.html @@ -4,7 +4,7 @@ -nitric.proto.kv API documentation +nitric.proto.nitric.faas API documentation @@ -19,7 +19,7 @@
    -

    Module nitric.proto.kv

    +

    Module nitric.proto.nitric.faas

    @@ -49,7 +49,7 @@

    Module nitric.proto.kv

    Sub-modules

    -
    nitric.proto.kv.v1
    +
    nitric.proto.nitric.faas.v1
    @@ -70,12 +70,12 @@

    Index

    diff --git a/docs/nitric/proto/nitric/faas/v1/index.html b/docs/nitric/proto/nitric/faas/v1/index.html new file mode 100644 index 0000000..0778488 --- /dev/null +++ b/docs/nitric/proto/nitric/faas/v1/index.html @@ -0,0 +1,777 @@ + + + + + + +nitric.proto.nitric.faas.v1 API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric.faas.v1

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +# Generated by the protocol buffer compiler.  DO NOT EDIT!
    +# sources: faas/v1/faas.proto
    +# plugin: python-betterproto
    +from dataclasses import dataclass
    +from typing import AsyncIterable, AsyncIterator, Dict, Iterable, Union
    +
    +import betterproto
    +from betterproto.grpc.grpclib_server import ServiceBase
    +import grpclib
    +
    +
    +@dataclass(eq=False, repr=False)
    +class ClientMessage(betterproto.Message):
    +    """Messages the client is able to send to the server"""
    +
    +    # Client message ID, used to pair requests/responses
    +    id: str = betterproto.string_field(1)
    +    # Client initialisation request
    +    init_request: "InitRequest" = betterproto.message_field(2, group="content")
    +    # Client responsding with result of a trigger
    +    trigger_response: "TriggerResponse" = betterproto.message_field(3, group="content")
    +
    +
    +@dataclass(eq=False, repr=False)
    +class ServerMessage(betterproto.Message):
    +    """Messages the server is able to send to the client"""
    +
    +    # Server message ID, used to pair requests/responses
    +    id: str = betterproto.string_field(1)
    +    # Server responding with client configuration details to an InitRequest
    +    init_response: "InitResponse" = betterproto.message_field(2, group="content")
    +    # Server requesting client to process a trigger
    +    trigger_request: "TriggerRequest" = betterproto.message_field(3, group="content")
    +
    +
    +@dataclass(eq=False, repr=False)
    +class InitRequest(betterproto.Message):
    +    """Placeholder message"""
    +
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class InitResponse(betterproto.Message):
    +    """Placeholder message"""
    +
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class TriggerRequest(betterproto.Message):
    +    """The server has a trigger for the client to handle"""
    +
    +    # The data in the trigger
    +    data: bytes = betterproto.bytes_field(1)
    +    # Should we supply a mime type for the data? Or rely on context?
    +    mime_type: str = betterproto.string_field(2)
    +    http: "HttpTriggerContext" = betterproto.message_field(3, group="context")
    +    topic: "TopicTriggerContext" = betterproto.message_field(4, group="context")
    +
    +
    +@dataclass(eq=False, repr=False)
    +class HttpTriggerContext(betterproto.Message):
    +    # The request method
    +    method: str = betterproto.string_field(1)
    +    # The path of the request
    +    path: str = betterproto.string_field(2)
    +    # The request headers
    +    headers: Dict[str, str] = betterproto.map_field(3, betterproto.TYPE_STRING, betterproto.TYPE_STRING)
    +    # The query params (if parseable by the membrane)
    +    query_params: Dict[str, str] = betterproto.map_field(4, betterproto.TYPE_STRING, betterproto.TYPE_STRING)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class TopicTriggerContext(betterproto.Message):
    +    # The topic the message was published for
    +    topic: str = betterproto.string_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class TriggerResponse(betterproto.Message):
    +    """The worker has successfully processed a trigger"""
    +
    +    # The data returned in the response
    +    data: bytes = betterproto.bytes_field(1)
    +    # response to a http request
    +    http: "HttpResponseContext" = betterproto.message_field(10, group="context")
    +    # response to a topic trigger
    +    topic: "TopicResponseContext" = betterproto.message_field(11, group="context")
    +
    +
    +@dataclass(eq=False, repr=False)
    +class HttpResponseContext(betterproto.Message):
    +    """
    +    Specific HttpResponse message Note this does not have to be handled by the
    +    User at all but they will have the option of control If they choose...
    +    """
    +
    +    # The request headers...
    +    headers: Dict[str, str] = betterproto.map_field(1, betterproto.TYPE_STRING, betterproto.TYPE_STRING)
    +    # The HTTP status of the request
    +    status: int = betterproto.int32_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class TopicResponseContext(betterproto.Message):
    +    """
    +    Specific event response message We do not accept responses for events only
    +    whether or not they were successfully processed
    +    """
    +
    +    # Success status of the handled event
    +    success: bool = betterproto.bool_field(1)
    +
    +
    +class FaasStub(betterproto.ServiceStub):
    +    async def trigger_stream(
    +        self,
    +        request_iterator: Union[AsyncIterable["ClientMessage"], Iterable["ClientMessage"]],
    +    ) -> AsyncIterator["ServerMessage"]:
    +
    +        async for response in self._stream_stream(
    +            "/nitric.faas.v1.Faas/TriggerStream",
    +            request_iterator,
    +            ClientMessage,
    +            ServerMessage,
    +        ):
    +            yield response
    +
    +
    +class FaasBase(ServiceBase):
    +    async def trigger_stream(self, request_iterator: AsyncIterator["ClientMessage"]) -> AsyncIterator["ServerMessage"]:
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_trigger_stream(self, stream: grpclib.server.Stream) -> None:
    +        request_kwargs = {"request_iterator": stream.__aiter__()}
    +
    +        await self._call_rpc_handler_server_stream(
    +            self.trigger_stream,
    +            stream,
    +            request_kwargs,
    +        )
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.faas.v1.Faas/TriggerStream": grpclib.const.Handler(
    +                self.__rpc_trigger_stream,
    +                grpclib.const.Cardinality.STREAM_STREAM,
    +                ClientMessage,
    +                ServerMessage,
    +            ),
    +        }
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class ClientMessage +(id: str = <object object>, init_request: InitRequest = <object object>, trigger_response: TriggerResponse = <object object>) +
    +
    +

    Messages the client is able to send to the server

    +
    + +Expand source code + +
    class ClientMessage(betterproto.Message):
    +    """Messages the client is able to send to the server"""
    +
    +    # Client message ID, used to pair requests/responses
    +    id: str = betterproto.string_field(1)
    +    # Client initialisation request
    +    init_request: "InitRequest" = betterproto.message_field(2, group="content")
    +    # Client responsding with result of a trigger
    +    trigger_response: "TriggerResponse" = betterproto.message_field(3, group="content")
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var id : str
    +
    +
    +
    +
    var init_request : InitRequest
    +
    +
    +
    +
    var trigger_response : TriggerResponse
    +
    +
    +
    +
    +
    +
    +class FaasBase +
    +
    +

    Base class for async gRPC servers.

    +
    + +Expand source code + +
    class FaasBase(ServiceBase):
    +    async def trigger_stream(self, request_iterator: AsyncIterator["ClientMessage"]) -> AsyncIterator["ServerMessage"]:
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_trigger_stream(self, stream: grpclib.server.Stream) -> None:
    +        request_kwargs = {"request_iterator": stream.__aiter__()}
    +
    +        await self._call_rpc_handler_server_stream(
    +            self.trigger_stream,
    +            stream,
    +            request_kwargs,
    +        )
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.faas.v1.Faas/TriggerStream": grpclib.const.Handler(
    +                self.__rpc_trigger_stream,
    +                grpclib.const.Cardinality.STREAM_STREAM,
    +                ClientMessage,
    +                ServerMessage,
    +            ),
    +        }
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_server.ServiceBase
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def trigger_stream(self, request_iterator: AsyncIterator[ForwardRef('ClientMessage')]) ‑> AsyncIterator[ServerMessage] +
    +
    +
    +
    + +Expand source code + +
    async def trigger_stream(self, request_iterator: AsyncIterator["ClientMessage"]) -> AsyncIterator["ServerMessage"]:
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +
    +
    +class FaasStub +(channel: Channel, *, timeout: Union[float, NoneType] = None, deadline: Union[ForwardRef('Deadline'), NoneType] = None, metadata: Union[Mapping[str, Union[str, bytes]], Collection[Tuple[str, Union[str, bytes]]], NoneType] = None) +
    +
    +

    Base class for async gRPC clients.

    +
    + +Expand source code + +
    class FaasStub(betterproto.ServiceStub):
    +    async def trigger_stream(
    +        self,
    +        request_iterator: Union[AsyncIterable["ClientMessage"], Iterable["ClientMessage"]],
    +    ) -> AsyncIterator["ServerMessage"]:
    +
    +        async for response in self._stream_stream(
    +            "/nitric.faas.v1.Faas/TriggerStream",
    +            request_iterator,
    +            ClientMessage,
    +            ServerMessage,
    +        ):
    +            yield response
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_client.ServiceStub
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def trigger_stream(self, request_iterator: Union[AsyncIterable[ForwardRef('ClientMessage')], Iterable[ForwardRef('ClientMessage')]]) ‑> AsyncIterator[ServerMessage] +
    +
    +
    +
    + +Expand source code + +
    async def trigger_stream(
    +    self,
    +    request_iterator: Union[AsyncIterable["ClientMessage"], Iterable["ClientMessage"]],
    +) -> AsyncIterator["ServerMessage"]:
    +
    +    async for response in self._stream_stream(
    +        "/nitric.faas.v1.Faas/TriggerStream",
    +        request_iterator,
    +        ClientMessage,
    +        ServerMessage,
    +    ):
    +        yield response
    +
    +
    +
    +
    +
    +class HttpResponseContext +(headers: Dict[str, str] = <object object>, status: int = <object object>) +
    +
    +

    Specific HttpResponse message Note this does not have to be handled by the +User at all but they will have the option of control If they choose…

    +
    + +Expand source code + +
    class HttpResponseContext(betterproto.Message):
    +    """
    +    Specific HttpResponse message Note this does not have to be handled by the
    +    User at all but they will have the option of control If they choose...
    +    """
    +
    +    # The request headers...
    +    headers: Dict[str, str] = betterproto.map_field(1, betterproto.TYPE_STRING, betterproto.TYPE_STRING)
    +    # The HTTP status of the request
    +    status: int = betterproto.int32_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var headers : Dict[str, str]
    +
    +
    +
    +
    var status : int
    +
    +
    +
    +
    +
    +
    +class HttpTriggerContext +(method: str = <object object>, path: str = <object object>, headers: Dict[str, str] = <object object>, query_params: Dict[str, str] = <object object>) +
    +
    +

    HttpTriggerContext(method: str = , path: str = , headers: Dict[str, str] = , query_params: Dict[str, str] = )

    +
    + +Expand source code + +
    class HttpTriggerContext(betterproto.Message):
    +    # The request method
    +    method: str = betterproto.string_field(1)
    +    # The path of the request
    +    path: str = betterproto.string_field(2)
    +    # The request headers
    +    headers: Dict[str, str] = betterproto.map_field(3, betterproto.TYPE_STRING, betterproto.TYPE_STRING)
    +    # The query params (if parseable by the membrane)
    +    query_params: Dict[str, str] = betterproto.map_field(4, betterproto.TYPE_STRING, betterproto.TYPE_STRING)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var headers : Dict[str, str]
    +
    +
    +
    +
    var method : str
    +
    +
    +
    +
    var path : str
    +
    +
    +
    +
    var query_params : Dict[str, str]
    +
    +
    +
    +
    + +
    +class InitRequest +
    +
    +

    Placeholder message

    +
    + +Expand source code + +
    class InitRequest(betterproto.Message):
    +    """Placeholder message"""
    +
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class InitResponse +
    +
    +

    Placeholder message

    +
    + +Expand source code + +
    class InitResponse(betterproto.Message):
    +    """Placeholder message"""
    +
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class ServerMessage +(id: str = <object object>, init_response: InitResponse = <object object>, trigger_request: TriggerRequest = <object object>) +
    +
    +

    Messages the server is able to send to the client

    +
    + +Expand source code + +
    class ServerMessage(betterproto.Message):
    +    """Messages the server is able to send to the client"""
    +
    +    # Server message ID, used to pair requests/responses
    +    id: str = betterproto.string_field(1)
    +    # Server responding with client configuration details to an InitRequest
    +    init_response: "InitResponse" = betterproto.message_field(2, group="content")
    +    # Server requesting client to process a trigger
    +    trigger_request: "TriggerRequest" = betterproto.message_field(3, group="content")
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var id : str
    +
    +
    +
    +
    var init_response : InitResponse
    +
    +
    +
    +
    var trigger_request : TriggerRequest
    +
    +
    +
    +
    +
    +
    +class TopicResponseContext +(success: bool = <object object>) +
    +
    +

    Specific event response message We do not accept responses for events only +whether or not they were successfully processed

    +
    + +Expand source code + +
    class TopicResponseContext(betterproto.Message):
    +    """
    +    Specific event response message We do not accept responses for events only
    +    whether or not they were successfully processed
    +    """
    +
    +    # Success status of the handled event
    +    success: bool = betterproto.bool_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var success : bool
    +
    +
    +
    +
    +
    +
    +class TopicTriggerContext +(topic: str = <object object>) +
    +
    +

    TopicTriggerContext(topic: str = )

    +
    + +Expand source code + +
    class TopicTriggerContext(betterproto.Message):
    +    # The topic the message was published for
    +    topic: str = betterproto.string_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var topic : str
    +
    +
    +
    +
    + +
    +class TriggerRequest +(data: bytes = <object object>, mime_type: str = <object object>, http: HttpTriggerContext = <object object>, topic: TopicTriggerContext = <object object>) +
    +
    +

    The server has a trigger for the client to handle

    +
    + +Expand source code + +
    class TriggerRequest(betterproto.Message):
    +    """The server has a trigger for the client to handle"""
    +
    +    # The data in the trigger
    +    data: bytes = betterproto.bytes_field(1)
    +    # Should we supply a mime type for the data? Or rely on context?
    +    mime_type: str = betterproto.string_field(2)
    +    http: "HttpTriggerContext" = betterproto.message_field(3, group="context")
    +    topic: "TopicTriggerContext" = betterproto.message_field(4, group="context")
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var data : bytes
    +
    +
    +
    +
    var http : HttpTriggerContext
    +
    +
    +
    +
    var mime_type : str
    +
    +
    +
    +
    var topic : TopicTriggerContext
    +
    +
    +
    +
    +
    +
    +class TriggerResponse +(data: bytes = <object object>, http: HttpResponseContext = <object object>, topic: TopicResponseContext = <object object>) +
    +
    +

    The worker has successfully processed a trigger

    +
    + +Expand source code + +
    class TriggerResponse(betterproto.Message):
    +    """The worker has successfully processed a trigger"""
    +
    +    # The data returned in the response
    +    data: bytes = betterproto.bytes_field(1)
    +    # response to a http request
    +    http: "HttpResponseContext" = betterproto.message_field(10, group="context")
    +    # response to a topic trigger
    +    topic: "TopicResponseContext" = betterproto.message_field(11, group="context")
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var data : bytes
    +
    +
    +
    +
    var http : HttpResponseContext
    +
    +
    +
    +
    var topic : TopicResponseContext
    +
    +
    +
    +
    +
    + + + + + + + + \ No newline at end of file diff --git a/docs/nitric/proto/nitric/index.html b/docs/nitric/proto/nitric/index.html new file mode 100644 index 0000000..6b92d37 --- /dev/null +++ b/docs/nitric/proto/nitric/index.html @@ -0,0 +1,108 @@ + + + + + + +nitric.proto.nitric API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +
    +
    +

    Sub-modules

    +
    +
    nitric.proto.nitric.event
    +
    +
    +
    +
    nitric.proto.nitric.faas
    +
    +
    +
    +
    nitric.proto.nitric.kv
    +
    +
    +
    +
    nitric.proto.nitric.queue
    +
    +
    +
    +
    nitric.proto.nitric.storage
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    + + + \ No newline at end of file diff --git a/docs/nitric/proto/faas/index.html b/docs/nitric/proto/nitric/kv/index.html similarity index 93% rename from docs/nitric/proto/faas/index.html rename to docs/nitric/proto/nitric/kv/index.html index 50878ee..e5c044e 100644 --- a/docs/nitric/proto/faas/index.html +++ b/docs/nitric/proto/nitric/kv/index.html @@ -4,7 +4,7 @@ -nitric.proto.faas API documentation +nitric.proto.nitric.kv API documentation @@ -19,7 +19,7 @@
    -

    Module nitric.proto.faas

    +

    Module nitric.proto.nitric.kv

    @@ -49,7 +49,7 @@

    Module nitric.proto.faas

    Sub-modules

    -
    nitric.proto.faas.v1
    +
    nitric.proto.nitric.kv.v1
    @@ -70,12 +70,12 @@

    Index

    diff --git a/docs/nitric/proto/nitric/kv/v1/index.html b/docs/nitric/proto/nitric/kv/v1/index.html new file mode 100644 index 0000000..1cf31ba --- /dev/null +++ b/docs/nitric/proto/nitric/kv/v1/index.html @@ -0,0 +1,700 @@ + + + + + + +nitric.proto.nitric.kv.v1 API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric.kv.v1

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +# Generated by the protocol buffer compiler.  DO NOT EDIT!
    +# sources: kv/v1/kv.proto
    +# plugin: python-betterproto
    +from dataclasses import dataclass
    +from typing import Dict
    +
    +import betterproto
    +from betterproto.grpc.grpclib_server import ServiceBase
    +import grpclib
    +
    +
    +@dataclass(eq=False, repr=False)
    +class KeyValueGetRequest(betterproto.Message):
    +    # The collection to retrieve the keyValue from
    +    collection: str = betterproto.string_field(1)
    +    # The unique key of the keyValue to retrieve
    +    key: str = betterproto.string_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class KeyValueGetResponse(betterproto.Message):
    +    # The retrieved value
    +    value: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class KeyValuePutRequest(betterproto.Message):
    +    # The collection containing the existing keyValue to be inserted or updated.
    +    collection: str = betterproto.string_field(1)
    +    # The unique key of the keyValue to put
    +    key: str = betterproto.string_field(2)
    +    # A simple JSON object
    +    value: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(3)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class KeyValuePutResponse(betterproto.Message):
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class KeyValueDeleteRequest(betterproto.Message):
    +    # The collection containing the existing keyValue to be deleted
    +    collection: str = betterproto.string_field(1)
    +    # The unique key of the keyValue to delete
    +    key: str = betterproto.string_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class KeyValueDeleteResponse(betterproto.Message):
    +    pass
    +
    +
    +class KeyValueStub(betterproto.ServiceStub):
    +    async def get(self, *, collection: str = "", key: str = "") -> "KeyValueGetResponse":
    +
    +        request = KeyValueGetRequest()
    +        request.collection = collection
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.kv.v1.KeyValue/Get", request, KeyValueGetResponse)
    +
    +    async def put(
    +        self,
    +        *,
    +        collection: str = "",
    +        key: str = "",
    +        value: "betterproto_lib_google_protobuf.Struct" = None,
    +    ) -> "KeyValuePutResponse":
    +
    +        request = KeyValuePutRequest()
    +        request.collection = collection
    +        request.key = key
    +        if value is not None:
    +            request.value = value
    +
    +        return await self._unary_unary("/nitric.kv.v1.KeyValue/Put", request, KeyValuePutResponse)
    +
    +    async def delete(self, *, collection: str = "", key: str = "") -> "KeyValueDeleteResponse":
    +
    +        request = KeyValueDeleteRequest()
    +        request.collection = collection
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.kv.v1.KeyValue/Delete", request, KeyValueDeleteResponse)
    +
    +
    +class KeyValueBase(ServiceBase):
    +    async def get(self, collection: str, key: str) -> "KeyValueGetResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def put(
    +        self, collection: str, key: str, value: "betterproto_lib_google_protobuf.Struct"
    +    ) -> "KeyValuePutResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def delete(self, collection: str, key: str) -> "KeyValueDeleteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_get(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "collection": request.collection,
    +            "key": request.key,
    +        }
    +
    +        response = await self.get(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_put(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "collection": request.collection,
    +            "key": request.key,
    +            "value": request.value,
    +        }
    +
    +        response = await self.put(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_delete(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "collection": request.collection,
    +            "key": request.key,
    +        }
    +
    +        response = await self.delete(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.kv.v1.KeyValue/Get": grpclib.const.Handler(
    +                self.__rpc_get,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                KeyValueGetRequest,
    +                KeyValueGetResponse,
    +            ),
    +            "/nitric.kv.v1.KeyValue/Put": grpclib.const.Handler(
    +                self.__rpc_put,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                KeyValuePutRequest,
    +                KeyValuePutResponse,
    +            ),
    +            "/nitric.kv.v1.KeyValue/Delete": grpclib.const.Handler(
    +                self.__rpc_delete,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                KeyValueDeleteRequest,
    +                KeyValueDeleteResponse,
    +            ),
    +        }
    +
    +
    +import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class KeyValueBase +
    +
    +

    Base class for async gRPC servers.

    +
    + +Expand source code + +
    class KeyValueBase(ServiceBase):
    +    async def get(self, collection: str, key: str) -> "KeyValueGetResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def put(
    +        self, collection: str, key: str, value: "betterproto_lib_google_protobuf.Struct"
    +    ) -> "KeyValuePutResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def delete(self, collection: str, key: str) -> "KeyValueDeleteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_get(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "collection": request.collection,
    +            "key": request.key,
    +        }
    +
    +        response = await self.get(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_put(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "collection": request.collection,
    +            "key": request.key,
    +            "value": request.value,
    +        }
    +
    +        response = await self.put(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_delete(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "collection": request.collection,
    +            "key": request.key,
    +        }
    +
    +        response = await self.delete(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.kv.v1.KeyValue/Get": grpclib.const.Handler(
    +                self.__rpc_get,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                KeyValueGetRequest,
    +                KeyValueGetResponse,
    +            ),
    +            "/nitric.kv.v1.KeyValue/Put": grpclib.const.Handler(
    +                self.__rpc_put,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                KeyValuePutRequest,
    +                KeyValuePutResponse,
    +            ),
    +            "/nitric.kv.v1.KeyValue/Delete": grpclib.const.Handler(
    +                self.__rpc_delete,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                KeyValueDeleteRequest,
    +                KeyValueDeleteResponse,
    +            ),
    +        }
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_server.ServiceBase
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def delete(self, collection: str, key: str) ‑> KeyValueDeleteResponse +
    +
    +
    +
    + +Expand source code + +
    async def delete(self, collection: str, key: str) -> "KeyValueDeleteResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def get(self, collection: str, key: str) ‑> KeyValueGetResponse +
    +
    +
    +
    + +Expand source code + +
    async def get(self, collection: str, key: str) -> "KeyValueGetResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def put(self, collection: str, key: str, value: betterproto_lib_google_protobuf.Struct) ‑> KeyValuePutResponse +
    +
    +
    +
    + +Expand source code + +
    async def put(
    +    self, collection: str, key: str, value: "betterproto_lib_google_protobuf.Struct"
    +) -> "KeyValuePutResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +
    +
    +class KeyValueDeleteRequest +(collection: str = <object object>, key: str = <object object>) +
    +
    +

    KeyValueDeleteRequest(collection: str = , key: str = )

    +
    + +Expand source code + +
    class KeyValueDeleteRequest(betterproto.Message):
    +    # The collection containing the existing keyValue to be deleted
    +    collection: str = betterproto.string_field(1)
    +    # The unique key of the keyValue to delete
    +    key: str = betterproto.string_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var collection : str
    +
    +
    +
    +
    var key : str
    +
    +
    +
    +
    + +
    +class KeyValueDeleteResponse +
    +
    +

    KeyValueDeleteResponse()

    +
    + +Expand source code + +
    class KeyValueDeleteResponse(betterproto.Message):
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class KeyValueGetRequest +(collection: str = <object object>, key: str = <object object>) +
    +
    +

    KeyValueGetRequest(collection: str = , key: str = )

    +
    + +Expand source code + +
    class KeyValueGetRequest(betterproto.Message):
    +    # The collection to retrieve the keyValue from
    +    collection: str = betterproto.string_field(1)
    +    # The unique key of the keyValue to retrieve
    +    key: str = betterproto.string_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var collection : str
    +
    +
    +
    +
    var key : str
    +
    +
    +
    +
    + +
    +class KeyValueGetResponse +(value: betterproto_lib_google_protobuf.Struct = <object object>) +
    +
    +

    KeyValueGetResponse(value: 'betterproto_lib_google_protobuf.Struct' = )

    +
    + +Expand source code + +
    class KeyValueGetResponse(betterproto.Message):
    +    # The retrieved value
    +    value: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var value : betterproto.lib.google.protobuf.Struct
    +
    +
    +
    +
    + +
    +class KeyValuePutRequest +(collection: str = <object object>, key: str = <object object>, value: betterproto_lib_google_protobuf.Struct = <object object>) +
    +
    +

    KeyValuePutRequest(collection: str = , key: str = , value: 'betterproto_lib_google_protobuf.Struct' = )

    +
    + +Expand source code + +
    class KeyValuePutRequest(betterproto.Message):
    +    # The collection containing the existing keyValue to be inserted or updated.
    +    collection: str = betterproto.string_field(1)
    +    # The unique key of the keyValue to put
    +    key: str = betterproto.string_field(2)
    +    # A simple JSON object
    +    value: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(3)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var collection : str
    +
    +
    +
    +
    var key : str
    +
    +
    +
    +
    var value : betterproto.lib.google.protobuf.Struct
    +
    +
    +
    +
    + +
    +class KeyValuePutResponse +
    +
    +

    KeyValuePutResponse()

    +
    + +Expand source code + +
    class KeyValuePutResponse(betterproto.Message):
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class KeyValueStub +(channel: Channel, *, timeout: Union[float, NoneType] = None, deadline: Union[ForwardRef('Deadline'), NoneType] = None, metadata: Union[Mapping[str, Union[str, bytes]], Collection[Tuple[str, Union[str, bytes]]], NoneType] = None) +
    +
    +

    Base class for async gRPC clients.

    +
    + +Expand source code + +
    class KeyValueStub(betterproto.ServiceStub):
    +    async def get(self, *, collection: str = "", key: str = "") -> "KeyValueGetResponse":
    +
    +        request = KeyValueGetRequest()
    +        request.collection = collection
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.kv.v1.KeyValue/Get", request, KeyValueGetResponse)
    +
    +    async def put(
    +        self,
    +        *,
    +        collection: str = "",
    +        key: str = "",
    +        value: "betterproto_lib_google_protobuf.Struct" = None,
    +    ) -> "KeyValuePutResponse":
    +
    +        request = KeyValuePutRequest()
    +        request.collection = collection
    +        request.key = key
    +        if value is not None:
    +            request.value = value
    +
    +        return await self._unary_unary("/nitric.kv.v1.KeyValue/Put", request, KeyValuePutResponse)
    +
    +    async def delete(self, *, collection: str = "", key: str = "") -> "KeyValueDeleteResponse":
    +
    +        request = KeyValueDeleteRequest()
    +        request.collection = collection
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.kv.v1.KeyValue/Delete", request, KeyValueDeleteResponse)
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_client.ServiceStub
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def delete(self, *, collection: str = '', key: str = '') ‑> KeyValueDeleteResponse +
    +
    +
    +
    + +Expand source code + +
    async def delete(self, *, collection: str = "", key: str = "") -> "KeyValueDeleteResponse":
    +
    +    request = KeyValueDeleteRequest()
    +    request.collection = collection
    +    request.key = key
    +
    +    return await self._unary_unary("/nitric.kv.v1.KeyValue/Delete", request, KeyValueDeleteResponse)
    +
    +
    +
    +async def get(self, *, collection: str = '', key: str = '') ‑> KeyValueGetResponse +
    +
    +
    +
    + +Expand source code + +
    async def get(self, *, collection: str = "", key: str = "") -> "KeyValueGetResponse":
    +
    +    request = KeyValueGetRequest()
    +    request.collection = collection
    +    request.key = key
    +
    +    return await self._unary_unary("/nitric.kv.v1.KeyValue/Get", request, KeyValueGetResponse)
    +
    +
    +
    +async def put(self, *, collection: str = '', key: str = '', value: betterproto_lib_google_protobuf.Struct = None) ‑> KeyValuePutResponse +
    +
    +
    +
    + +Expand source code + +
    async def put(
    +    self,
    +    *,
    +    collection: str = "",
    +    key: str = "",
    +    value: "betterproto_lib_google_protobuf.Struct" = None,
    +) -> "KeyValuePutResponse":
    +
    +    request = KeyValuePutRequest()
    +    request.collection = collection
    +    request.key = key
    +    if value is not None:
    +        request.value = value
    +
    +    return await self._unary_unary("/nitric.kv.v1.KeyValue/Put", request, KeyValuePutResponse)
    +
    +
    +
    +
    + + + + + + + + \ No newline at end of file diff --git a/docs/nitric/proto/auth/index.html b/docs/nitric/proto/nitric/queue/index.html similarity index 93% rename from docs/nitric/proto/auth/index.html rename to docs/nitric/proto/nitric/queue/index.html index 2cabb07..de96adb 100644 --- a/docs/nitric/proto/auth/index.html +++ b/docs/nitric/proto/nitric/queue/index.html @@ -4,7 +4,7 @@ -nitric.proto.auth API documentation +nitric.proto.nitric.queue API documentation @@ -19,7 +19,7 @@
    -

    Module nitric.proto.auth

    +

    Module nitric.proto.nitric.queue

    @@ -49,7 +49,7 @@

    Module nitric.proto.auth

    Sub-modules

    -
    nitric.proto.auth.v1
    +
    nitric.proto.nitric.queue.v1
    @@ -70,12 +70,12 @@

    Index

    diff --git a/docs/nitric/proto/nitric/queue/v1/index.html b/docs/nitric/proto/nitric/queue/v1/index.html new file mode 100644 index 0000000..00f1003 --- /dev/null +++ b/docs/nitric/proto/nitric/queue/v1/index.html @@ -0,0 +1,992 @@ + + + + + + +nitric.proto.nitric.queue.v1 API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric.queue.v1

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +# Generated by the protocol buffer compiler.  DO NOT EDIT!
    +# sources: queue/v1/queue.proto
    +# plugin: python-betterproto
    +from dataclasses import dataclass
    +from typing import Dict, List, Optional
    +
    +import betterproto
    +from betterproto.grpc.grpclib_server import ServiceBase
    +import grpclib
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueSendRequest(betterproto.Message):
    +    """Request to push a single event to a queue"""
    +
    +    # The Nitric name for the queue this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # The task to push to the queue
    +    task: "NitricTask" = betterproto.message_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueSendResponse(betterproto.Message):
    +    """Result of pushing a single task to a queue"""
    +
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueSendBatchRequest(betterproto.Message):
    +    # The Nitric name for the queue this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # Array of tasks to push to the queue
    +    tasks: List["NitricTask"] = betterproto.message_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueSendBatchResponse(betterproto.Message):
    +    """Response for sending a collection of tasks"""
    +
    +    # A list of tasks that failed to be queued
    +    failed_tasks: List["FailedTask"] = betterproto.message_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueReceiveRequest(betterproto.Message):
    +    # The nitric name for the queue this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # The max number of items to pop off the queue, may be capped by provider
    +    # specific limitations
    +    depth: int = betterproto.int32_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueReceiveResponse(betterproto.Message):
    +    # Array of tasks popped off the queue
    +    tasks: List["NitricTask"] = betterproto.message_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueCompleteRequest(betterproto.Message):
    +    # The nitric name for the queue  this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # Lease id of the task to be completed
    +    lease_id: str = betterproto.string_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class QueueCompleteResponse(betterproto.Message):
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class FailedTask(betterproto.Message):
    +    # The task that failed to be pushed
    +    task: "NitricTask" = betterproto.message_field(1)
    +    # A message describing the failure
    +    message: str = betterproto.string_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class NitricTask(betterproto.Message):
    +    """A task to be sent or received from a queue."""
    +
    +    # A unique id for the task
    +    id: str = betterproto.string_field(1)
    +    # The lease id unique to the pop request, this must be used to complete,
    +    # extend the lease or release the task.
    +    lease_id: str = betterproto.string_field(2)
    +    # A content hint for the tasks payload
    +    payload_type: str = betterproto.string_field(3)
    +    # The payload of the task
    +    payload: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(4)
    +
    +
    +class QueueStub(betterproto.ServiceStub):
    +    async def send(self, *, queue: str = "", task: "NitricTask" = None) -> "QueueSendResponse":
    +
    +        request = QueueSendRequest()
    +        request.queue = queue
    +        if task is not None:
    +            request.task = task
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/Send", request, QueueSendResponse)
    +
    +    async def send_batch(
    +        self, *, queue: str = "", tasks: Optional[List["NitricTask"]] = None
    +    ) -> "QueueSendBatchResponse":
    +        tasks = tasks or []
    +
    +        request = QueueSendBatchRequest()
    +        request.queue = queue
    +        if tasks is not None:
    +            request.tasks = tasks
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/SendBatch", request, QueueSendBatchResponse)
    +
    +    async def receive(self, *, queue: str = "", depth: int = 0) -> "QueueReceiveResponse":
    +
    +        request = QueueReceiveRequest()
    +        request.queue = queue
    +        request.depth = depth
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/Receive", request, QueueReceiveResponse)
    +
    +    async def complete(self, *, queue: str = "", lease_id: str = "") -> "QueueCompleteResponse":
    +
    +        request = QueueCompleteRequest()
    +        request.queue = queue
    +        request.lease_id = lease_id
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/Complete", request, QueueCompleteResponse)
    +
    +
    +class QueueBase(ServiceBase):
    +    async def send(self, queue: str, task: "NitricTask") -> "QueueSendResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def send_batch(self, queue: str, tasks: Optional[List["NitricTask"]]) -> "QueueSendBatchResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def receive(self, queue: str, depth: int) -> "QueueReceiveResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def complete(self, queue: str, lease_id: str) -> "QueueCompleteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_send(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "task": request.task,
    +        }
    +
    +        response = await self.send(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_send_batch(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "tasks": request.tasks,
    +        }
    +
    +        response = await self.send_batch(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_receive(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "depth": request.depth,
    +        }
    +
    +        response = await self.receive(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_complete(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "lease_id": request.lease_id,
    +        }
    +
    +        response = await self.complete(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.queue.v1.Queue/Send": grpclib.const.Handler(
    +                self.__rpc_send,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueSendRequest,
    +                QueueSendResponse,
    +            ),
    +            "/nitric.queue.v1.Queue/SendBatch": grpclib.const.Handler(
    +                self.__rpc_send_batch,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueSendBatchRequest,
    +                QueueSendBatchResponse,
    +            ),
    +            "/nitric.queue.v1.Queue/Receive": grpclib.const.Handler(
    +                self.__rpc_receive,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueReceiveRequest,
    +                QueueReceiveResponse,
    +            ),
    +            "/nitric.queue.v1.Queue/Complete": grpclib.const.Handler(
    +                self.__rpc_complete,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueCompleteRequest,
    +                QueueCompleteResponse,
    +            ),
    +        }
    +
    +
    +import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class FailedTask +(task: NitricTask = <object object>, message: str = <object object>) +
    +
    +

    FailedTask(task: 'NitricTask' = , message: str = )

    +
    + +Expand source code + +
    class FailedTask(betterproto.Message):
    +    # The task that failed to be pushed
    +    task: "NitricTask" = betterproto.message_field(1)
    +    # A message describing the failure
    +    message: str = betterproto.string_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var message : str
    +
    +
    +
    +
    var task : NitricTask
    +
    +
    +
    +
    + +
    +class NitricTask +(id: str = <object object>, lease_id: str = <object object>, payload_type: str = <object object>, payload: betterproto_lib_google_protobuf.Struct = <object object>) +
    +
    +

    A task to be sent or received from a queue.

    +
    + +Expand source code + +
    class NitricTask(betterproto.Message):
    +    """A task to be sent or received from a queue."""
    +
    +    # A unique id for the task
    +    id: str = betterproto.string_field(1)
    +    # The lease id unique to the pop request, this must be used to complete,
    +    # extend the lease or release the task.
    +    lease_id: str = betterproto.string_field(2)
    +    # A content hint for the tasks payload
    +    payload_type: str = betterproto.string_field(3)
    +    # The payload of the task
    +    payload: "betterproto_lib_google_protobuf.Struct" = betterproto.message_field(4)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var id : str
    +
    +
    +
    +
    var lease_id : str
    +
    +
    +
    +
    var payload : betterproto.lib.google.protobuf.Struct
    +
    +
    +
    +
    var payload_type : str
    +
    +
    +
    +
    +
    +
    +class QueueBase +
    +
    +

    Base class for async gRPC servers.

    +
    + +Expand source code + +
    class QueueBase(ServiceBase):
    +    async def send(self, queue: str, task: "NitricTask") -> "QueueSendResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def send_batch(self, queue: str, tasks: Optional[List["NitricTask"]]) -> "QueueSendBatchResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def receive(self, queue: str, depth: int) -> "QueueReceiveResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def complete(self, queue: str, lease_id: str) -> "QueueCompleteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_send(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "task": request.task,
    +        }
    +
    +        response = await self.send(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_send_batch(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "tasks": request.tasks,
    +        }
    +
    +        response = await self.send_batch(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_receive(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "depth": request.depth,
    +        }
    +
    +        response = await self.receive(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_complete(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "queue": request.queue,
    +            "lease_id": request.lease_id,
    +        }
    +
    +        response = await self.complete(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.queue.v1.Queue/Send": grpclib.const.Handler(
    +                self.__rpc_send,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueSendRequest,
    +                QueueSendResponse,
    +            ),
    +            "/nitric.queue.v1.Queue/SendBatch": grpclib.const.Handler(
    +                self.__rpc_send_batch,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueSendBatchRequest,
    +                QueueSendBatchResponse,
    +            ),
    +            "/nitric.queue.v1.Queue/Receive": grpclib.const.Handler(
    +                self.__rpc_receive,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueReceiveRequest,
    +                QueueReceiveResponse,
    +            ),
    +            "/nitric.queue.v1.Queue/Complete": grpclib.const.Handler(
    +                self.__rpc_complete,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                QueueCompleteRequest,
    +                QueueCompleteResponse,
    +            ),
    +        }
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_server.ServiceBase
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def complete(self, queue: str, lease_id: str) ‑> QueueCompleteResponse +
    +
    +
    +
    + +Expand source code + +
    async def complete(self, queue: str, lease_id: str) -> "QueueCompleteResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def receive(self, queue: str, depth: int) ‑> QueueReceiveResponse +
    +
    +
    +
    + +Expand source code + +
    async def receive(self, queue: str, depth: int) -> "QueueReceiveResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def send(self, queue: str, task: NitricTask) ‑> QueueSendResponse +
    +
    +
    +
    + +Expand source code + +
    async def send(self, queue: str, task: "NitricTask") -> "QueueSendResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def send_batch(self, queue: str, tasks: Union[List[ForwardRef('NitricTask')], NoneType]) ‑> QueueSendBatchResponse +
    +
    +
    +
    + +Expand source code + +
    async def send_batch(self, queue: str, tasks: Optional[List["NitricTask"]]) -> "QueueSendBatchResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +
    +
    +class QueueCompleteRequest +(queue: str = <object object>, lease_id: str = <object object>) +
    +
    +

    QueueCompleteRequest(queue: str = , lease_id: str = )

    +
    + +Expand source code + +
    class QueueCompleteRequest(betterproto.Message):
    +    # The nitric name for the queue  this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # Lease id of the task to be completed
    +    lease_id: str = betterproto.string_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var lease_id : str
    +
    +
    +
    +
    var queue : str
    +
    +
    +
    +
    + +
    +class QueueCompleteResponse +
    +
    +

    QueueCompleteResponse()

    +
    + +Expand source code + +
    class QueueCompleteResponse(betterproto.Message):
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class QueueReceiveRequest +(queue: str = <object object>, depth: int = <object object>) +
    +
    +

    QueueReceiveRequest(queue: str = , depth: int = )

    +
    + +Expand source code + +
    class QueueReceiveRequest(betterproto.Message):
    +    # The nitric name for the queue this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # The max number of items to pop off the queue, may be capped by provider
    +    # specific limitations
    +    depth: int = betterproto.int32_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var depth : int
    +
    +
    +
    +
    var queue : str
    +
    +
    +
    +
    + +
    +class QueueReceiveResponse +(tasks: List[ForwardRef('NitricTask')] = <object object>) +
    +
    +

    QueueReceiveResponse(tasks: List[ForwardRef('NitricTask')] = )

    +
    + +Expand source code + +
    class QueueReceiveResponse(betterproto.Message):
    +    # Array of tasks popped off the queue
    +    tasks: List["NitricTask"] = betterproto.message_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var tasks : List[NitricTask]
    +
    +
    +
    +
    + +
    +class QueueSendBatchRequest +(queue: str = <object object>, tasks: List[ForwardRef('NitricTask')] = <object object>) +
    +
    +

    QueueSendBatchRequest(queue: str = , tasks: List[ForwardRef('NitricTask')] = )

    +
    + +Expand source code + +
    class QueueSendBatchRequest(betterproto.Message):
    +    # The Nitric name for the queue this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # Array of tasks to push to the queue
    +    tasks: List["NitricTask"] = betterproto.message_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var queue : str
    +
    +
    +
    +
    var tasks : List[NitricTask]
    +
    +
    +
    +
    + +
    +class QueueSendBatchResponse +(failed_tasks: List[ForwardRef('FailedTask')] = <object object>) +
    +
    +

    Response for sending a collection of tasks

    +
    + +Expand source code + +
    class QueueSendBatchResponse(betterproto.Message):
    +    """Response for sending a collection of tasks"""
    +
    +    # A list of tasks that failed to be queued
    +    failed_tasks: List["FailedTask"] = betterproto.message_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var failed_tasks : List[FailedTask]
    +
    +
    +
    +
    +
    +
    +class QueueSendRequest +(queue: str = <object object>, task: NitricTask = <object object>) +
    +
    +

    Request to push a single event to a queue

    +
    + +Expand source code + +
    class QueueSendRequest(betterproto.Message):
    +    """Request to push a single event to a queue"""
    +
    +    # The Nitric name for the queue this will automatically be resolved to the
    +    # provider specific queue identifier.
    +    queue: str = betterproto.string_field(1)
    +    # The task to push to the queue
    +    task: "NitricTask" = betterproto.message_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var queue : str
    +
    +
    +
    +
    var task : NitricTask
    +
    +
    +
    +
    +
    +
    +class QueueSendResponse +
    +
    +

    Result of pushing a single task to a queue

    +
    + +Expand source code + +
    class QueueSendResponse(betterproto.Message):
    +    """Result of pushing a single task to a queue"""
    +
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class QueueStub +(channel: Channel, *, timeout: Union[float, NoneType] = None, deadline: Union[ForwardRef('Deadline'), NoneType] = None, metadata: Union[Mapping[str, Union[str, bytes]], Collection[Tuple[str, Union[str, bytes]]], NoneType] = None) +
    +
    +

    Base class for async gRPC clients.

    +
    + +Expand source code + +
    class QueueStub(betterproto.ServiceStub):
    +    async def send(self, *, queue: str = "", task: "NitricTask" = None) -> "QueueSendResponse":
    +
    +        request = QueueSendRequest()
    +        request.queue = queue
    +        if task is not None:
    +            request.task = task
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/Send", request, QueueSendResponse)
    +
    +    async def send_batch(
    +        self, *, queue: str = "", tasks: Optional[List["NitricTask"]] = None
    +    ) -> "QueueSendBatchResponse":
    +        tasks = tasks or []
    +
    +        request = QueueSendBatchRequest()
    +        request.queue = queue
    +        if tasks is not None:
    +            request.tasks = tasks
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/SendBatch", request, QueueSendBatchResponse)
    +
    +    async def receive(self, *, queue: str = "", depth: int = 0) -> "QueueReceiveResponse":
    +
    +        request = QueueReceiveRequest()
    +        request.queue = queue
    +        request.depth = depth
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/Receive", request, QueueReceiveResponse)
    +
    +    async def complete(self, *, queue: str = "", lease_id: str = "") -> "QueueCompleteResponse":
    +
    +        request = QueueCompleteRequest()
    +        request.queue = queue
    +        request.lease_id = lease_id
    +
    +        return await self._unary_unary("/nitric.queue.v1.Queue/Complete", request, QueueCompleteResponse)
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_client.ServiceStub
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def complete(self, *, queue: str = '', lease_id: str = '') ‑> QueueCompleteResponse +
    +
    +
    +
    + +Expand source code + +
    async def complete(self, *, queue: str = "", lease_id: str = "") -> "QueueCompleteResponse":
    +
    +    request = QueueCompleteRequest()
    +    request.queue = queue
    +    request.lease_id = lease_id
    +
    +    return await self._unary_unary("/nitric.queue.v1.Queue/Complete", request, QueueCompleteResponse)
    +
    +
    +
    +async def receive(self, *, queue: str = '', depth: int = 0) ‑> QueueReceiveResponse +
    +
    +
    +
    + +Expand source code + +
    async def receive(self, *, queue: str = "", depth: int = 0) -> "QueueReceiveResponse":
    +
    +    request = QueueReceiveRequest()
    +    request.queue = queue
    +    request.depth = depth
    +
    +    return await self._unary_unary("/nitric.queue.v1.Queue/Receive", request, QueueReceiveResponse)
    +
    +
    +
    +async def send(self, *, queue: str = '', task: NitricTask = None) ‑> QueueSendResponse +
    +
    +
    +
    + +Expand source code + +
    async def send(self, *, queue: str = "", task: "NitricTask" = None) -> "QueueSendResponse":
    +
    +    request = QueueSendRequest()
    +    request.queue = queue
    +    if task is not None:
    +        request.task = task
    +
    +    return await self._unary_unary("/nitric.queue.v1.Queue/Send", request, QueueSendResponse)
    +
    +
    +
    +async def send_batch(self, *, queue: str = '', tasks: Union[List[ForwardRef('NitricTask')], NoneType] = None) ‑> QueueSendBatchResponse +
    +
    +
    +
    + +Expand source code + +
    async def send_batch(
    +    self, *, queue: str = "", tasks: Optional[List["NitricTask"]] = None
    +) -> "QueueSendBatchResponse":
    +    tasks = tasks or []
    +
    +    request = QueueSendBatchRequest()
    +    request.queue = queue
    +    if tasks is not None:
    +        request.tasks = tasks
    +
    +    return await self._unary_unary("/nitric.queue.v1.Queue/SendBatch", request, QueueSendBatchResponse)
    +
    +
    +
    +
    + + + + + + + + \ No newline at end of file diff --git a/docs/nitric/proto/nitric/storage/index.html b/docs/nitric/proto/nitric/storage/index.html new file mode 100644 index 0000000..d936a53 --- /dev/null +++ b/docs/nitric/proto/nitric/storage/index.html @@ -0,0 +1,88 @@ + + + + + + +nitric.proto.nitric.storage API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric.storage

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +
    +
    +

    Sub-modules

    +
    +
    nitric.proto.nitric.storage.v1
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    + + + \ No newline at end of file diff --git a/docs/nitric/proto/nitric/storage/v1/index.html b/docs/nitric/proto/nitric/storage/v1/index.html new file mode 100644 index 0000000..c5c6abd --- /dev/null +++ b/docs/nitric/proto/nitric/storage/v1/index.html @@ -0,0 +1,698 @@ + + + + + + +nitric.proto.nitric.storage.v1 API documentation + + + + + + + + + + + +
    +
    +
    +

    Module nitric.proto.nitric.storage.v1

    +
    +
    +
    + +Expand source code + +
    #
    +# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    +#
    +# This file is part of Nitric Python 3 SDK.
    +# See https://github.com/nitrictech/python-sdk for further info.
    +#
    +# Licensed 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.
    +#
    +
    +# Generated by the protocol buffer compiler.  DO NOT EDIT!
    +# sources: storage/v1/storage.proto
    +# plugin: python-betterproto
    +from dataclasses import dataclass
    +from typing import Dict
    +
    +import betterproto
    +from betterproto.grpc.grpclib_server import ServiceBase
    +import grpclib
    +
    +
    +@dataclass(eq=False, repr=False)
    +class StorageWriteRequest(betterproto.Message):
    +    """Request to put (create/update) a storage item"""
    +
    +    # Nitric name of the bucket to store in  this will be automatically resolved
    +    # to the provider specific bucket identifier.
    +    bucket_name: str = betterproto.string_field(1)
    +    # Key to store the item under
    +    key: str = betterproto.string_field(2)
    +    # bytes array to store
    +    body: bytes = betterproto.bytes_field(3)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class StorageWriteResponse(betterproto.Message):
    +    """Result of putting a storage item"""
    +
    +    pass
    +
    +
    +@dataclass(eq=False, repr=False)
    +class StorageReadRequest(betterproto.Message):
    +    """Request to retrieve a storage item"""
    +
    +    # Nitric name of the bucket to retrieve from  this will be automatically
    +    # resolved to the provider specific bucket identifier.
    +    bucket_name: str = betterproto.string_field(1)
    +    # Key of item to retrieve
    +    key: str = betterproto.string_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class StorageReadResponse(betterproto.Message):
    +    """Returned storage item"""
    +
    +    # The body bytes of the retrieved storage item
    +    body: bytes = betterproto.bytes_field(1)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class StorageDeleteRequest(betterproto.Message):
    +    """Request to delete a storage item"""
    +
    +    # Name of the bucket to delete from
    +    bucket_name: str = betterproto.string_field(1)
    +    # Key of item to delete
    +    key: str = betterproto.string_field(2)
    +
    +
    +@dataclass(eq=False, repr=False)
    +class StorageDeleteResponse(betterproto.Message):
    +    """Result of deleting a storage item"""
    +
    +    pass
    +
    +
    +class StorageStub(betterproto.ServiceStub):
    +    async def read(self, *, bucket_name: str = "", key: str = "") -> "StorageReadResponse":
    +
    +        request = StorageReadRequest()
    +        request.bucket_name = bucket_name
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.storage.v1.Storage/Read", request, StorageReadResponse)
    +
    +    async def write(self, *, bucket_name: str = "", key: str = "", body: bytes = b"") -> "StorageWriteResponse":
    +
    +        request = StorageWriteRequest()
    +        request.bucket_name = bucket_name
    +        request.key = key
    +        request.body = body
    +
    +        return await self._unary_unary("/nitric.storage.v1.Storage/Write", request, StorageWriteResponse)
    +
    +    async def delete(self, *, bucket_name: str = "", key: str = "") -> "StorageDeleteResponse":
    +
    +        request = StorageDeleteRequest()
    +        request.bucket_name = bucket_name
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.storage.v1.Storage/Delete", request, StorageDeleteResponse)
    +
    +
    +class StorageBase(ServiceBase):
    +    async def read(self, bucket_name: str, key: str) -> "StorageReadResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def write(self, bucket_name: str, key: str, body: bytes) -> "StorageWriteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def delete(self, bucket_name: str, key: str) -> "StorageDeleteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_read(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "bucket_name": request.bucket_name,
    +            "key": request.key,
    +        }
    +
    +        response = await self.read(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_write(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "bucket_name": request.bucket_name,
    +            "key": request.key,
    +            "body": request.body,
    +        }
    +
    +        response = await self.write(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_delete(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "bucket_name": request.bucket_name,
    +            "key": request.key,
    +        }
    +
    +        response = await self.delete(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.storage.v1.Storage/Read": grpclib.const.Handler(
    +                self.__rpc_read,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                StorageReadRequest,
    +                StorageReadResponse,
    +            ),
    +            "/nitric.storage.v1.Storage/Write": grpclib.const.Handler(
    +                self.__rpc_write,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                StorageWriteRequest,
    +                StorageWriteResponse,
    +            ),
    +            "/nitric.storage.v1.Storage/Delete": grpclib.const.Handler(
    +                self.__rpc_delete,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                StorageDeleteRequest,
    +                StorageDeleteResponse,
    +            ),
    +        }
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class StorageBase +
    +
    +

    Base class for async gRPC servers.

    +
    + +Expand source code + +
    class StorageBase(ServiceBase):
    +    async def read(self, bucket_name: str, key: str) -> "StorageReadResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def write(self, bucket_name: str, key: str, body: bytes) -> "StorageWriteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def delete(self, bucket_name: str, key: str) -> "StorageDeleteResponse":
    +        raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +    async def __rpc_read(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "bucket_name": request.bucket_name,
    +            "key": request.key,
    +        }
    +
    +        response = await self.read(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_write(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "bucket_name": request.bucket_name,
    +            "key": request.key,
    +            "body": request.body,
    +        }
    +
    +        response = await self.write(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    async def __rpc_delete(self, stream: grpclib.server.Stream) -> None:
    +        request = await stream.recv_message()
    +
    +        request_kwargs = {
    +            "bucket_name": request.bucket_name,
    +            "key": request.key,
    +        }
    +
    +        response = await self.delete(**request_kwargs)
    +        await stream.send_message(response)
    +
    +    def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
    +        return {
    +            "/nitric.storage.v1.Storage/Read": grpclib.const.Handler(
    +                self.__rpc_read,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                StorageReadRequest,
    +                StorageReadResponse,
    +            ),
    +            "/nitric.storage.v1.Storage/Write": grpclib.const.Handler(
    +                self.__rpc_write,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                StorageWriteRequest,
    +                StorageWriteResponse,
    +            ),
    +            "/nitric.storage.v1.Storage/Delete": grpclib.const.Handler(
    +                self.__rpc_delete,
    +                grpclib.const.Cardinality.UNARY_UNARY,
    +                StorageDeleteRequest,
    +                StorageDeleteResponse,
    +            ),
    +        }
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_server.ServiceBase
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def delete(self, bucket_name: str, key: str) ‑> StorageDeleteResponse +
    +
    +
    +
    + +Expand source code + +
    async def delete(self, bucket_name: str, key: str) -> "StorageDeleteResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def read(self, bucket_name: str, key: str) ‑> StorageReadResponse +
    +
    +
    +
    + +Expand source code + +
    async def read(self, bucket_name: str, key: str) -> "StorageReadResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +async def write(self, bucket_name: str, key: str, body: bytes) ‑> StorageWriteResponse +
    +
    +
    +
    + +Expand source code + +
    async def write(self, bucket_name: str, key: str, body: bytes) -> "StorageWriteResponse":
    +    raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
    +
    +
    +
    +
    +
    +class StorageDeleteRequest +(bucket_name: str = <object object>, key: str = <object object>) +
    +
    +

    Request to delete a storage item

    +
    + +Expand source code + +
    class StorageDeleteRequest(betterproto.Message):
    +    """Request to delete a storage item"""
    +
    +    # Name of the bucket to delete from
    +    bucket_name: str = betterproto.string_field(1)
    +    # Key of item to delete
    +    key: str = betterproto.string_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var bucket_name : str
    +
    +
    +
    +
    var key : str
    +
    +
    +
    +
    +
    +
    +class StorageDeleteResponse +
    +
    +

    Result of deleting a storage item

    +
    + +Expand source code + +
    class StorageDeleteResponse(betterproto.Message):
    +    """Result of deleting a storage item"""
    +
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +class StorageReadRequest +(bucket_name: str = <object object>, key: str = <object object>) +
    +
    +

    Request to retrieve a storage item

    +
    + +Expand source code + +
    class StorageReadRequest(betterproto.Message):
    +    """Request to retrieve a storage item"""
    +
    +    # Nitric name of the bucket to retrieve from  this will be automatically
    +    # resolved to the provider specific bucket identifier.
    +    bucket_name: str = betterproto.string_field(1)
    +    # Key of item to retrieve
    +    key: str = betterproto.string_field(2)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var bucket_name : str
    +
    +
    +
    +
    var key : str
    +
    +
    +
    +
    +
    +
    +class StorageReadResponse +(body: bytes = <object object>) +
    +
    +

    Returned storage item

    +
    + +Expand source code + +
    class StorageReadResponse(betterproto.Message):
    +    """Returned storage item"""
    +
    +    # The body bytes of the retrieved storage item
    +    body: bytes = betterproto.bytes_field(1)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var body : bytes
    +
    +
    +
    +
    +
    +
    +class StorageStub +(channel: Channel, *, timeout: Union[float, NoneType] = None, deadline: Union[ForwardRef('Deadline'), NoneType] = None, metadata: Union[Mapping[str, Union[str, bytes]], Collection[Tuple[str, Union[str, bytes]]], NoneType] = None) +
    +
    +

    Base class for async gRPC clients.

    +
    + +Expand source code + +
    class StorageStub(betterproto.ServiceStub):
    +    async def read(self, *, bucket_name: str = "", key: str = "") -> "StorageReadResponse":
    +
    +        request = StorageReadRequest()
    +        request.bucket_name = bucket_name
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.storage.v1.Storage/Read", request, StorageReadResponse)
    +
    +    async def write(self, *, bucket_name: str = "", key: str = "", body: bytes = b"") -> "StorageWriteResponse":
    +
    +        request = StorageWriteRequest()
    +        request.bucket_name = bucket_name
    +        request.key = key
    +        request.body = body
    +
    +        return await self._unary_unary("/nitric.storage.v1.Storage/Write", request, StorageWriteResponse)
    +
    +    async def delete(self, *, bucket_name: str = "", key: str = "") -> "StorageDeleteResponse":
    +
    +        request = StorageDeleteRequest()
    +        request.bucket_name = bucket_name
    +        request.key = key
    +
    +        return await self._unary_unary("/nitric.storage.v1.Storage/Delete", request, StorageDeleteResponse)
    +
    +

    Ancestors

    +
      +
    • betterproto.grpc.grpclib_client.ServiceStub
    • +
    • abc.ABC
    • +
    +

    Methods

    +
    +
    +async def delete(self, *, bucket_name: str = '', key: str = '') ‑> StorageDeleteResponse +
    +
    +
    +
    + +Expand source code + +
    async def delete(self, *, bucket_name: str = "", key: str = "") -> "StorageDeleteResponse":
    +
    +    request = StorageDeleteRequest()
    +    request.bucket_name = bucket_name
    +    request.key = key
    +
    +    return await self._unary_unary("/nitric.storage.v1.Storage/Delete", request, StorageDeleteResponse)
    +
    +
    +
    +async def read(self, *, bucket_name: str = '', key: str = '') ‑> StorageReadResponse +
    +
    +
    +
    + +Expand source code + +
    async def read(self, *, bucket_name: str = "", key: str = "") -> "StorageReadResponse":
    +
    +    request = StorageReadRequest()
    +    request.bucket_name = bucket_name
    +    request.key = key
    +
    +    return await self._unary_unary("/nitric.storage.v1.Storage/Read", request, StorageReadResponse)
    +
    +
    +
    +async def write(self, *, bucket_name: str = '', key: str = '', body: bytes = b'') ‑> StorageWriteResponse +
    +
    +
    +
    + +Expand source code + +
    async def write(self, *, bucket_name: str = "", key: str = "", body: bytes = b"") -> "StorageWriteResponse":
    +
    +    request = StorageWriteRequest()
    +    request.bucket_name = bucket_name
    +    request.key = key
    +    request.body = body
    +
    +    return await self._unary_unary("/nitric.storage.v1.Storage/Write", request, StorageWriteResponse)
    +
    +
    +
    +
    +
    +class StorageWriteRequest +(bucket_name: str = <object object>, key: str = <object object>, body: bytes = <object object>) +
    +
    +

    Request to put (create/update) a storage item

    +
    + +Expand source code + +
    class StorageWriteRequest(betterproto.Message):
    +    """Request to put (create/update) a storage item"""
    +
    +    # Nitric name of the bucket to store in  this will be automatically resolved
    +    # to the provider specific bucket identifier.
    +    bucket_name: str = betterproto.string_field(1)
    +    # Key to store the item under
    +    key: str = betterproto.string_field(2)
    +    # bytes array to store
    +    body: bytes = betterproto.bytes_field(3)
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +

    Class variables

    +
    +
    var body : bytes
    +
    +
    +
    +
    var bucket_name : str
    +
    +
    +
    +
    var key : str
    +
    +
    +
    +
    +
    +
    +class StorageWriteResponse +
    +
    +

    Result of putting a storage item

    +
    + +Expand source code + +
    class StorageWriteResponse(betterproto.Message):
    +    """Result of putting a storage item"""
    +
    +    pass
    +
    +

    Ancestors

    +
      +
    • betterproto.Message
    • +
    • abc.ABC
    • +
    +
    +
    +
    +
    + +
    + + + \ No newline at end of file diff --git a/docs/nitric/proto/queue/index.html b/docs/nitric/proto/queue/index.html deleted file mode 100644 index 6a565bf..0000000 --- a/docs/nitric/proto/queue/index.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - -nitric.proto.queue API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.queue

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.queue.v1
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/queue/v1/index.html b/docs/nitric/proto/queue/v1/index.html deleted file mode 100644 index da1c281..0000000 --- a/docs/nitric/proto/queue/v1/index.html +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - -nitric.proto.queue.v1 API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.queue.v1

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.queue.v1.queue_pb2
    -
    -

    Generated protocol buffer code.

    -
    -
    nitric.proto.queue.v1.queue_pb2_grpc
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/queue/v1/queue_pb2_grpc.html b/docs/nitric/proto/queue/v1/queue_pb2_grpc.html deleted file mode 100644 index eb3e16c..0000000 --- a/docs/nitric/proto/queue/v1/queue_pb2_grpc.html +++ /dev/null @@ -1,677 +0,0 @@ - - - - - - -nitric.proto.queue.v1.queue_pb2_grpc API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.queue.v1.queue_pb2_grpc

    -
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
    -"""Client and server classes corresponding to protobuf-defined services."""
    -import grpc
    -
    -from nitric.proto.queue.v1 import queue_pb2 as queue_dot_v1_dot_queue__pb2
    -
    -
    -class QueueStub(object):
    -    """The Nitric Queue Service contract
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Send = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/Send',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueSendRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendResponse.FromString,
    -                )
    -        self.SendBatch = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/SendBatch',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.FromString,
    -                )
    -        self.Receive = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/Receive',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.FromString,
    -                )
    -        self.Complete = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/Complete',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.FromString,
    -                )
    -
    -
    -class QueueServicer(object):
    -    """The Nitric Queue Service contract
    -    """
    -
    -    def Send(self, request, context):
    -        """Send a single event to a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def SendBatch(self, request, context):
    -        """Send multiple events to a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Receive(self, request, context):
    -        """Receive event(s) off a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Complete(self, request, context):
    -        """Complete an event previously popped from a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_QueueServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Send': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Send,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueSendResponse.SerializeToString,
    -            ),
    -            'SendBatch': grpc.unary_unary_rpc_method_handler(
    -                    servicer.SendBatch,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.SerializeToString,
    -            ),
    -            'Receive': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Receive,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.SerializeToString,
    -            ),
    -            'Complete': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Complete,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.queue.v1.Queue', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class Queue(object):
    -    """The Nitric Queue Service contract
    -    """
    -
    -    @staticmethod
    -    def Send(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Send',
    -            queue_dot_v1_dot_queue__pb2.QueueSendRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueSendResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def SendBatch(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/SendBatch',
    -            queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Receive(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Receive',
    -            queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Complete(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Complete',
    -            queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def add_QueueServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_QueueServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Send': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Send,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueSendResponse.SerializeToString,
    -            ),
    -            'SendBatch': grpc.unary_unary_rpc_method_handler(
    -                    servicer.SendBatch,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.SerializeToString,
    -            ),
    -            'Receive': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Receive,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.SerializeToString,
    -            ),
    -            'Complete': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Complete,
    -                    request_deserializer=queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.FromString,
    -                    response_serializer=queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.queue.v1.Queue', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Queue -
    -
    -

    The Nitric Queue Service contract

    -
    - -Expand source code - -
    class Queue(object):
    -    """The Nitric Queue Service contract
    -    """
    -
    -    @staticmethod
    -    def Send(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Send',
    -            queue_dot_v1_dot_queue__pb2.QueueSendRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueSendResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def SendBatch(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/SendBatch',
    -            queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Receive(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Receive',
    -            queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Complete(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Complete',
    -            queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.SerializeToString,
    -            queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def Complete(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Complete(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Complete',
    -        queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.SerializeToString,
    -        queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def Receive(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Receive(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Receive',
    -        queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.SerializeToString,
    -        queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def Send(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Send(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/Send',
    -        queue_dot_v1_dot_queue__pb2.QueueSendRequest.SerializeToString,
    -        queue_dot_v1_dot_queue__pb2.QueueSendResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def SendBatch(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def SendBatch(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.queue.v1.Queue/SendBatch',
    -        queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.SerializeToString,
    -        queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class QueueServicer -
    -
    -

    The Nitric Queue Service contract

    -
    - -Expand source code - -
    class QueueServicer(object):
    -    """The Nitric Queue Service contract
    -    """
    -
    -    def Send(self, request, context):
    -        """Send a single event to a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def SendBatch(self, request, context):
    -        """Send multiple events to a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Receive(self, request, context):
    -        """Receive event(s) off a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Complete(self, request, context):
    -        """Complete an event previously popped from a queue
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def Complete(self, request, context) -
    -
    -

    Complete an event previously popped from a queue

    -
    - -Expand source code - -
    def Complete(self, request, context):
    -    """Complete an event previously popped from a queue
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def Receive(self, request, context) -
    -
    -

    Receive event(s) off a queue

    -
    - -Expand source code - -
    def Receive(self, request, context):
    -    """Receive event(s) off a queue
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def Send(self, request, context) -
    -
    -

    Send a single event to a queue

    -
    - -Expand source code - -
    def Send(self, request, context):
    -    """Send a single event to a queue
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def SendBatch(self, request, context) -
    -
    -

    Send multiple events to a queue

    -
    - -Expand source code - -
    def SendBatch(self, request, context):
    -    """Send multiple events to a queue
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class QueueStub -(channel) -
    -
    -

    The Nitric Queue Service contract

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class QueueStub(object):
    -    """The Nitric Queue Service contract
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Send = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/Send',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueSendRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendResponse.FromString,
    -                )
    -        self.SendBatch = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/SendBatch',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueSendBatchResponse.FromString,
    -                )
    -        self.Receive = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/Receive',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueReceiveRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueReceiveResponse.FromString,
    -                )
    -        self.Complete = channel.unary_unary(
    -                '/nitric.queue.v1.Queue/Complete',
    -                request_serializer=queue_dot_v1_dot_queue__pb2.QueueCompleteRequest.SerializeToString,
    -                response_deserializer=queue_dot_v1_dot_queue__pb2.QueueCompleteResponse.FromString,
    -                )
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/storage/index.html b/docs/nitric/proto/storage/index.html deleted file mode 100644 index d1ed0ae..0000000 --- a/docs/nitric/proto/storage/index.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - -nitric.proto.storage API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.storage

    -
    -
    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -
    -
    -

    Sub-modules

    -
    -
    nitric.proto.storage.v1
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/storage/v1/storage_pb2_grpc.html b/docs/nitric/proto/storage/v1/storage_pb2_grpc.html deleted file mode 100644 index 89c8bcb..0000000 --- a/docs/nitric/proto/storage/v1/storage_pb2_grpc.html +++ /dev/null @@ -1,563 +0,0 @@ - - - - - - -nitric.proto.storage.v1.storage_pb2_grpc API documentation - - - - - - - - - - - -
    -
    -
    -

    Module nitric.proto.storage.v1.storage_pb2_grpc

    -
    -
    -

    Client and server classes corresponding to protobuf-defined services.

    -
    - -Expand source code - -
    #
    -# Copyright (c) 2021 Nitric Technologies Pty Ltd.
    -#
    -# This file is part of Nitric Python 3 SDK.
    -# See https://github.com/nitrictech/python-sdk for further info.
    -#
    -# Licensed 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.
    -#
    -
    -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
    -"""Client and server classes corresponding to protobuf-defined services."""
    -import grpc
    -
    -from nitric.proto.storage.v1 import storage_pb2 as storage_dot_v1_dot_storage__pb2
    -
    -
    -class StorageStub(object):
    -    """Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Read = channel.unary_unary(
    -                '/nitric.storage.v1.Storage/Read',
    -                request_serializer=storage_dot_v1_dot_storage__pb2.StorageReadRequest.SerializeToString,
    -                response_deserializer=storage_dot_v1_dot_storage__pb2.StorageReadResponse.FromString,
    -                )
    -        self.Write = channel.unary_unary(
    -                '/nitric.storage.v1.Storage/Write',
    -                request_serializer=storage_dot_v1_dot_storage__pb2.StorageWriteRequest.SerializeToString,
    -                response_deserializer=storage_dot_v1_dot_storage__pb2.StorageWriteResponse.FromString,
    -                )
    -        self.Delete = channel.unary_unary(
    -                '/nitric.storage.v1.Storage/Delete',
    -                request_serializer=storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.SerializeToString,
    -                response_deserializer=storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.FromString,
    -                )
    -
    -
    -class StorageServicer(object):
    -    """Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.
    -    """
    -
    -    def Read(self, request, context):
    -        """Retrieve an item from a bucket
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Write(self, request, context):
    -        """Store an item to a bucket
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Delete(self, request, context):
    -        """Delete an item from a bucket
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -
    -def add_StorageServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Read': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Read,
    -                    request_deserializer=storage_dot_v1_dot_storage__pb2.StorageReadRequest.FromString,
    -                    response_serializer=storage_dot_v1_dot_storage__pb2.StorageReadResponse.SerializeToString,
    -            ),
    -            'Write': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Write,
    -                    request_deserializer=storage_dot_v1_dot_storage__pb2.StorageWriteRequest.FromString,
    -                    response_serializer=storage_dot_v1_dot_storage__pb2.StorageWriteResponse.SerializeToString,
    -            ),
    -            'Delete': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Delete,
    -                    request_deserializer=storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.FromString,
    -                    response_serializer=storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.storage.v1.Storage', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    - # This class is part of an EXPERIMENTAL API.
    -class Storage(object):
    -    """Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.
    -    """
    -
    -    @staticmethod
    -    def Read(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Read',
    -            storage_dot_v1_dot_storage__pb2.StorageReadRequest.SerializeToString,
    -            storage_dot_v1_dot_storage__pb2.StorageReadResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Write(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Write',
    -            storage_dot_v1_dot_storage__pb2.StorageWriteRequest.SerializeToString,
    -            storage_dot_v1_dot_storage__pb2.StorageWriteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Delete(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Delete',
    -            storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.SerializeToString,
    -            storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def add_StorageServicer_to_server(servicer, server) -
    -
    -
    -
    - -Expand source code - -
    def add_StorageServicer_to_server(servicer, server):
    -    rpc_method_handlers = {
    -            'Read': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Read,
    -                    request_deserializer=storage_dot_v1_dot_storage__pb2.StorageReadRequest.FromString,
    -                    response_serializer=storage_dot_v1_dot_storage__pb2.StorageReadResponse.SerializeToString,
    -            ),
    -            'Write': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Write,
    -                    request_deserializer=storage_dot_v1_dot_storage__pb2.StorageWriteRequest.FromString,
    -                    response_serializer=storage_dot_v1_dot_storage__pb2.StorageWriteResponse.SerializeToString,
    -            ),
    -            'Delete': grpc.unary_unary_rpc_method_handler(
    -                    servicer.Delete,
    -                    request_deserializer=storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.FromString,
    -                    response_serializer=storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.SerializeToString,
    -            ),
    -    }
    -    generic_handler = grpc.method_handlers_generic_handler(
    -            'nitric.storage.v1.Storage', rpc_method_handlers)
    -    server.add_generic_rpc_handlers((generic_handler,))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Storage -
    -
    -

    Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.

    -
    - -Expand source code - -
    class Storage(object):
    -    """Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.
    -    """
    -
    -    @staticmethod
    -    def Read(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Read',
    -            storage_dot_v1_dot_storage__pb2.StorageReadRequest.SerializeToString,
    -            storage_dot_v1_dot_storage__pb2.StorageReadResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Write(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Write',
    -            storage_dot_v1_dot_storage__pb2.StorageWriteRequest.SerializeToString,
    -            storage_dot_v1_dot_storage__pb2.StorageWriteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -    @staticmethod
    -    def Delete(request,
    -            target,
    -            options=(),
    -            channel_credentials=None,
    -            call_credentials=None,
    -            insecure=False,
    -            compression=None,
    -            wait_for_ready=None,
    -            timeout=None,
    -            metadata=None):
    -        return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Delete',
    -            storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.SerializeToString,
    -            storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.FromString,
    -            options, channel_credentials,
    -            insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -

    Static methods

    -
    -
    -def Delete(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Delete(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Delete',
    -        storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.SerializeToString,
    -        storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def Read(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Read(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Read',
    -        storage_dot_v1_dot_storage__pb2.StorageReadRequest.SerializeToString,
    -        storage_dot_v1_dot_storage__pb2.StorageReadResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -def Write(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def Write(request,
    -        target,
    -        options=(),
    -        channel_credentials=None,
    -        call_credentials=None,
    -        insecure=False,
    -        compression=None,
    -        wait_for_ready=None,
    -        timeout=None,
    -        metadata=None):
    -    return grpc.experimental.unary_unary(request, target, '/nitric.storage.v1.Storage/Write',
    -        storage_dot_v1_dot_storage__pb2.StorageWriteRequest.SerializeToString,
    -        storage_dot_v1_dot_storage__pb2.StorageWriteResponse.FromString,
    -        options, channel_credentials,
    -        insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
    -
    -
    -
    -
    -
    -class StorageServicer -
    -
    -

    Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.

    -
    - -Expand source code - -
    class StorageServicer(object):
    -    """Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.
    -    """
    -
    -    def Read(self, request, context):
    -        """Retrieve an item from a bucket
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Write(self, request, context):
    -        """Store an item to a bucket
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -    def Delete(self, request, context):
    -        """Delete an item from a bucket
    -        """
    -        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -        context.set_details('Method not implemented!')
    -        raise NotImplementedError('Method not implemented!')
    -
    -

    Methods

    -
    -
    -def Delete(self, request, context) -
    -
    -

    Delete an item from a bucket

    -
    - -Expand source code - -
    def Delete(self, request, context):
    -    """Delete an item from a bucket
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def Read(self, request, context) -
    -
    -

    Retrieve an item from a bucket

    -
    - -Expand source code - -
    def Read(self, request, context):
    -    """Retrieve an item from a bucket
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -def Write(self, request, context) -
    -
    -

    Store an item to a bucket

    -
    - -Expand source code - -
    def Write(self, request, context):
    -    """Store an item to a bucket
    -    """
    -    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    -    context.set_details('Method not implemented!')
    -    raise NotImplementedError('Method not implemented!')
    -
    -
    -
    -
    -
    -class StorageStub -(channel) -
    -
    -

    Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.

    -

    Constructor.

    -

    Args

    -
    -
    channel
    -
    A grpc.Channel.
    -
    -
    - -Expand source code - -
    class StorageStub(object):
    -    """Services for storage and retrieval of files in the form of byte arrays, such as text and binary files.
    -    """
    -
    -    def __init__(self, channel):
    -        """Constructor.
    -
    -        Args:
    -            channel: A grpc.Channel.
    -        """
    -        self.Read = channel.unary_unary(
    -                '/nitric.storage.v1.Storage/Read',
    -                request_serializer=storage_dot_v1_dot_storage__pb2.StorageReadRequest.SerializeToString,
    -                response_deserializer=storage_dot_v1_dot_storage__pb2.StorageReadResponse.FromString,
    -                )
    -        self.Write = channel.unary_unary(
    -                '/nitric.storage.v1.Storage/Write',
    -                request_serializer=storage_dot_v1_dot_storage__pb2.StorageWriteRequest.SerializeToString,
    -                response_deserializer=storage_dot_v1_dot_storage__pb2.StorageWriteResponse.FromString,
    -                )
    -        self.Delete = channel.unary_unary(
    -                '/nitric.storage.v1.Storage/Delete',
    -                request_serializer=storage_dot_v1_dot_storage__pb2.StorageDeleteRequest.SerializeToString,
    -                response_deserializer=storage_dot_v1_dot_storage__pb2.StorageDeleteResponse.FromString,
    -                )
    -
    -
    -
    -
    -
    - -
    - - - \ No newline at end of file diff --git a/docs/nitric/proto/storage/v1/index.html b/docs/nitric/utils.html similarity index 64% rename from docs/nitric/proto/storage/v1/index.html rename to docs/nitric/utils.html index 7e7a385..1b9a4ab 100644 --- a/docs/nitric/proto/storage/v1/index.html +++ b/docs/nitric/utils.html @@ -4,7 +4,7 @@ -nitric.proto.storage.v1 API documentation +nitric.utils API documentation @@ -19,7 +19,7 @@
    -

    Module nitric.proto.storage.v1

    +

    Module nitric.utils

    @@ -43,28 +43,96 @@

    Module nitric.proto.storage.v1

    # 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. -# +# +import re +from betterproto.lib.google.protobuf import Struct +from google.protobuf.json_format import MessageToDict +from google.protobuf.struct_pb2 import Struct as WorkingStruct +from nitric.config import settings +from urllib.parse import urlparse +from grpclib.client import Channel + + +def format_url(url: str): + """Add the default http scheme prefix to urls without one.""" + if not re.match("^((?:http|ftp|https):)?//", url.lower()): + return "http://{0}".format(url) + return url + + +def new_default_channel(): + """Create new gRPC channel from settings.""" + channel_url = urlparse(format_url(settings.SERVICE_BIND)) + return Channel(host=channel_url.hostname, port=channel_url.port) + + +# These functions convert to/from python dict <-> betterproto.lib.google.protobuf.Struct +# the existing Struct().from_dict() method doesn't work for Structs, +# it relies on Message meta information, that isn't available for dynamic structs. +def _dict_from_struct(struct: Struct) -> dict: + """Construct a dict from a Struct.""" + # Convert the bytes representation of the betterproto Struct into a protobuf Struct + # in order to use the MessageToDict function to safely create a dict. + gpb_struct = WorkingStruct() + gpb_struct.ParseFromString(bytes(struct)) + return MessageToDict(gpb_struct) + + +def _struct_from_dict(dictionary: dict) -> Struct: + """Construct a Struct from a dict.""" + # Convert to dict into a Struct class from the protobuf library + # since protobuf Structs are able to be created from a dict + # unlike the Struct class from betterproto. + gpb_struct = WorkingStruct() + gpb_struct.update(dictionary) + # Convert the bytes representation of the protobuf Struct into the betterproto Struct + # so that the returned Struct is compatible with other betterproto generated classes + struct = Struct().parse(gpb_struct.SerializeToString()) + return struct
    -

    Sub-modules

    +
    +
    +
    +
    +

    Functions

    -
    nitric.proto.storage.v1.storage_pb2
    +
    +def format_url(url: str) +
    -

    Generated protocol buffer code.

    +

    Add the default http scheme prefix to urls without one.

    +
    + +Expand source code + +
    def format_url(url: str):
    +    """Add the default http scheme prefix to urls without one."""
    +    if not re.match("^((?:http|ftp|https):)?//", url.lower()):
    +        return "http://{0}".format(url)
    +    return url
    +
    -
    nitric.proto.storage.v1.storage_pb2_grpc
    +
    +def new_default_channel() +
    -

    Client and server classes corresponding to protobuf-defined services.

    +

    Create new gRPC channel from settings.

    +
    + +Expand source code + +
    def new_default_channel():
    +    """Create new gRPC channel from settings."""
    +    channel_url = urlparse(format_url(settings.SERVICE_BIND))
    +    return Channel(host=channel_url.hostname, port=channel_url.port)
    +
    -
    -
    -
    -