Skip to content

Commit

Permalink
More tests and fixups
Browse files Browse the repository at this point in the history
  • Loading branch information
caspervonb committed Jul 18, 2024
1 parent 7ccc454 commit 2d71992
Show file tree
Hide file tree
Showing 6 changed files with 167 additions and 186 deletions.
49 changes: 49 additions & 0 deletions examples/micro/service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import asyncio
import contextlib
import signal

from nats import Client, micro

async def echo(req) -> None:
"""Echo the request data back to the client."""
await req.respond(req.data())


async def main():
# Define an event to signal when to quit
quit_event = asyncio.Event()
# Attach signal handler to the event loop
loop = asyncio.get_event_loop()
for sig in (signal.Signals.SIGINT, signal.Signals.SIGTERM):
loop.add_signal_handler(sig, lambda *_: quit_event.set())
# Create an async exit stack
async with contextlib.AsyncExitStack() as stack:
# Create a NATS client
nc = Client()
# Connect to NATS
await nc.connect("nats://localhost:4222")
# Push the client.close() method into the stack to be called on exit
stack.push_async_callback(nc.close)
# Push a new micro service into the stack to be stopped on exit
# The service will be stopped and drain its subscriptions before
# closing the connection.
service = await stack.enter_async_context(
await micro.add_service(
nc,
name="demo-service",
version="1.0.0",
description="Demo service",
)
)
group = service.add_group("demo")
# Add an endpoint to the service
await group.add_endpoint(
name="echo",
handler=echo,
)
# Wait for the quit event
await quit_event.wait()


if __name__ == "__main__":
asyncio.run(main())
4 changes: 3 additions & 1 deletion nats/micro/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
from .request import Request, Handler


async def add_service(nc: Client, config: Optional[ServiceConfig] = None, **kwargs) -> Service:
async def add_service(
nc: Client, config: Optional[ServiceConfig] = None, **kwargs
) -> Service:
"""Add a service."""
if config:
config = replace(config, **kwargs)
Expand Down
34 changes: 0 additions & 34 deletions nats/micro/api.py

This file was deleted.

6 changes: 3 additions & 3 deletions nats/micro/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
# limitations under the License.
#

import abc

from dataclasses import dataclass
from enum import Enum
from typing import Dict, Awaitable, Callable, TypeAlias, Optional

from nats.aio.msg import Msg
from nats.micro.api import ERROR_HEADER, ERROR_CODE_HEADER

ERROR_HEADER = "Nats-Service-Error"
ERROR_CODE_HEADER = "Nats-Service-Error-Code"


class Request:
Expand Down
Loading

0 comments on commit 2d71992

Please # to comment.