Skip to content

Commit

Permalink
feat(backend-python): improve api of lib for custom NatsClients by se…
Browse files Browse the repository at this point in the history
…tting up the health check in designated function
  • Loading branch information
cb0s committed Mar 14, 2024
1 parent 944d2d0 commit 6ec272b
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions backend-python/src/telestion/backend/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,24 @@ def with_custom_nc(self, nats_client: NatsClient) -> 'Options':
return replace(self, custom_nc=nats_client)


async def setup_healthcheck(nc: NatsClient, service_name: str) -> NatsClient:
"""Sets up __telestion__.health for a NatsClient. Returns NatsClient for fluent API."""
async def _respond_hc(msg):
msg.respond(
json_encode({
"errors": 0,
"name": service_name
})
)

await nc.subscribe(
'__telestion__.health',
cb=_respond_hc
)

return nc


async def start_service(opts: Options = None) -> Service:
if opts is None:
opts = Options()
Expand All @@ -73,25 +91,9 @@ async def start_service(opts: Options = None) -> Service:
if not opts.nats or opts.custom_nc is not None:
return service

async def error_cb(err):
print(err)

nc = await nats.connect(servers=_prepare_nats_url(config), error_cb=error_cb)
# Setup healthcheck
async def respond(msg):
msg.respond(
json_encode({
"errors": 0,
"name": config.service_name
})
)

await nc.subscribe(
'__telestion__.health',
cb=respond
)
nc = await nats.connect(servers=_prepare_nats_url(config))

return replace(service, nc=nc)
return replace(service, nc=await setup_healthcheck(nc, config.service_name))


# Macros
Expand Down

0 comments on commit 6ec272b

Please sign in to comment.