Skip to content

Commit 09d3e63

Browse files
Merge pull request #61 from nitrictech/feat/refresh-cac
Update to use configuration as code
2 parents a01e762 + caa0f2f commit 09d3e63

33 files changed

Lines changed: 1945 additions & 64 deletions

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,3 +143,5 @@ dmypy.json
143143
# Cython debug symbols
144144
cython_debug/
145145

146+
147+
.vscode/

.pre-commit-config.yaml

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,11 @@ repos:
88
rev: 3.7.9
99
hooks:
1010
- id: flake8
11-
exclude: ^(venv|tests|build|dist|nitric/proto|examples)/
11+
exclude: ^(venv|tests|build|dist|nitric/proto|examples)/
12+
- repo: https://github.com/pycqa/pydocstyle
13+
rev: 6.0.0
14+
hooks:
15+
- id: pydocstyle
16+
args:
17+
- --ignore=D100, D105, D203, D212, D415
18+
exclude: ^(venv|tests|build|dist|nitric/proto|examples)/

examples/queues/failed.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,21 @@
22
from typing import List
33
from nitric.api import Queues, Task
44
from nitric.api.queues import FailedTask
5+
56
# [END import]
67
async def queues_failed():
7-
# [START snippet]
8-
# Construct a new queue client with default settings
8+
# [START snippet]
9+
# Construct a new queue client with default settings
910
queues = Queues()
1011

1112
payload = {"content": "of task"}
1213

1314
# Publish tasks to queue
1415
failed_task = await queues.queue("my-queue").send([Task(payload=payload) for i in range(2)])
15-
16+
1617
# Process the failed task
1718
for task in failed_task:
18-
print(task.message)
19-
# [END snippet]
19+
print(task.message)
20+
21+
22+
# [END snippet]

nitric/api/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# limitations under the License.
1818
#
1919
"""Nitric API SDK."""
20-
from nitric.api.events import Events, Event, Topic
20+
from nitric.api.events import Events, Event, TopicRef
2121
from nitric.api.queues import Queues, Task, FailedTask
2222
from nitric.api.storage import Storage
2323
from nitric.api.documents import Documents
@@ -31,6 +31,6 @@
3131
"Event",
3232
"Task",
3333
"FailedTask",
34-
"Topic",
34+
"TopicRef",
3535
"Secrets",
3636
]

nitric/api/events.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def _event_to_wire(event: Event) -> NitricEvent:
4646

4747

4848
@dataclass(frozen=True, order=True)
49-
class Topic(object):
49+
class TopicRef(object):
5050
"""A reference to a topic on an event service, used to perform operations on that topic."""
5151

5252
_events: Events
@@ -94,14 +94,14 @@ def __del__(self):
9494
if self.channel is not None:
9595
self.channel.close()
9696

97-
async def topics(self) -> List[Topic]:
97+
async def topics(self) -> List[TopicRef]:
9898
"""Get a list of topics available for publishing or subscription."""
9999
try:
100100
response = await self._topic_stub.list()
101101
return [self.topic(topic.name) for topic in response.topics]
102102
except GRPCError as grpc_err:
103103
raise exception_from_grpc_error(grpc_err)
104104

105-
def topic(self, name: str) -> Topic:
105+
def topic(self, name: str) -> TopicRef:
106106
"""Return a reference to a topic."""
107-
return Topic(_events=self, name=name)
107+
return TopicRef(_events=self, name=name)

nitric/api/queues.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ class ReceivedTask(object):
4646
payload: dict = field(default_factory=dict)
4747
lease_id: str = field(default=None)
4848
_queueing: Queues = field(default=None)
49-
_queue: Queue = field(default=None)
49+
_queue: QueueRef = field(default=None)
5050

5151
async def complete(self):
5252
"""
@@ -85,7 +85,7 @@ def _task_to_wire(task: Task) -> NitricTask:
8585
)
8686

8787

88-
def _wire_to_received_task(task: NitricTask, queueing: Queues = None, queue: Queue = None) -> ReceivedTask:
88+
def _wire_to_received_task(task: NitricTask, queueing: Queues = None, queue: QueueRef = None) -> ReceivedTask:
8989
"""
9090
Convert a Nitric Queue Task (protobuf) to a Nitric Task (python SDK).
9191
@@ -120,7 +120,7 @@ def _wire_to_failed_task(failed_task: WireFailedTask) -> FailedTask:
120120

121121

122122
@dataclass(frozen=True, order=True)
123-
class Queue(object):
123+
class QueueRef(object):
124124
"""A reference to a queue from a queue service, used to perform operations on that queue."""
125125

126126
_queueing: Queues
@@ -212,4 +212,4 @@ def __del__(self):
212212

213213
def queue(self, name: str):
214214
"""Return a reference to a queue from the connected queue service."""
215-
return Queue(_queueing=self, name=name)
215+
return QueueRef(_queueing=self, name=name)

nitric/api/secrets.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,15 @@ def __del__(self):
4646

4747
def secret(self, name: str):
4848
"""Return a reference to a secret container from the connected secrets management service."""
49-
return SecretContainer(_secrets=self, name=name)
49+
return SecretContainerRef(_secrets=self, name=name)
5050

5151

52-
def _secret_to_wire(secret: SecretContainer) -> SecretMessage:
52+
def _secret_to_wire(secret: SecretContainerRef) -> SecretMessage:
5353
return SecretMessage(name=secret.name)
5454

5555

5656
@dataclass(frozen=True)
57-
class SecretContainer(object):
57+
class SecretContainerRef(object):
5858
"""A reference to a secret container, used to store and retrieve secret versions."""
5959

6060
_secrets: Secrets
@@ -104,7 +104,7 @@ class SecretVersion(object):
104104
"""A reference to a version of a secret, used to access the value of the version."""
105105

106106
_secrets: Secrets
107-
secret: SecretContainer
107+
secret: SecretContainerRef
108108
id: str
109109

110110
async def access(self) -> SecretValue:

nitric/api/storage.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,11 @@ def __del__(self):
4545

4646
def bucket(self, name: str):
4747
"""Return a reference to a bucket from the connected storage service."""
48-
return Bucket(_storage=self, name=name)
48+
return BucketRef(_storage=self, name=name)
4949

5050

5151
@dataclass(frozen=True, order=True)
52-
class Bucket(object):
52+
class BucketRef(object):
5353
"""A reference to a bucket in a storage service, used to the perform operations on that bucket."""
5454

5555
_storage: Storage
@@ -67,7 +67,7 @@ class FileMode(Enum):
6767
WRITE = 1
6868

6969
def to_request_operation(self) -> StoragePreSignUrlRequestOperation:
70-
"""Convert FileMode to a StoragePreSignUrlRequestOperation"""
70+
"""Convert FileMode to a StoragePreSignUrlRequestOperation."""
7171
if self == FileMode.READ:
7272
return StoragePreSignUrlRequestOperation.READ
7373
elif self == FileMode.WRITE:
@@ -111,8 +111,7 @@ async def delete(self):
111111
raise exception_from_grpc_error(grpc_err)
112112

113113
async def sign_url(self, mode: FileMode = FileMode.READ, expiry: int = 3600):
114-
"""Generated a signed url for reading or writing to a file"""
115-
114+
"""Generate a signed URL for reading or writing to a file."""
116115
try:
117116
await self._storage._storage_stub.pre_sign_url(
118117
bucket_name=self._bucket, key=self.key, operation=mode.to_request_operation(), expiry=expiry

nitric/application.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import asyncio
2+
from nitric.faas import FunctionServer
3+
# from nitric.resources.base import BaseResource
4+
from typing import Dict, List, Type, Any, TypeVar
5+
6+
7+
BT = TypeVar('BT')
8+
9+
class Nitric:
10+
_workers: List[FunctionServer] = []
11+
_cache: Dict[str, Dict[str, Any]] = {
12+
"api": {},
13+
"bucket": {},
14+
"topic": {},
15+
"secret": {},
16+
"queue": {},
17+
"collection": {}
18+
}
19+
20+
@classmethod
21+
def _register_worker(cls, srv: FunctionServer):
22+
"""
23+
Register a worker for this
24+
"""
25+
cls._workers.append(srv)
26+
27+
@classmethod
28+
def _create_resource(cls, resource: Type[BT], name: str) -> BT:
29+
resource_type = resource.__name__.lower()
30+
if cls._cache.get(resource_type).get(name) is None:
31+
cls._cache[resource_type][name] = resource.make(name)
32+
33+
return cls._cache[resource_type][name]
34+
35+
@classmethod
36+
def run(cls):
37+
"""
38+
Start the nitric application, this will execute in an existing event loop if there is one, otherwise it will
39+
attempt to create its own
40+
"""
41+
try:
42+
try:
43+
loop = asyncio.get_running_loop()
44+
except RuntimeError:
45+
loop = asyncio.get_event_loop()
46+
47+
loop.run_until_complete(asyncio.gather(*[wkr.start() for wkr in cls._workers]))
48+
except KeyboardInterrupt:
49+
print("\nexiting")

0 commit comments

Comments
 (0)