server.py 1.8 KB
Newer Older
1
2
3
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

4
import asyncio
5
import signal
6
7

import uvloop
Neelay Shah's avatar
Neelay Shah committed
8

Neelay Shah's avatar
Neelay Shah committed
9
from dynamo.runtime import DistributedRuntime, dynamo_worker
10
11
12
13
14
15
16
17
18
19


class RequestHandler:
    """
    Request handler for the generate endpoint
    """

    async def generate(self, request):
        print(f"Received request: {request}")
        for char in request:
20
            await asyncio.sleep(1)
21
22
23
            yield char


24
@dynamo_worker()
25
async def worker(runtime: DistributedRuntime):
26
27
28
29
30
31
32
33
34
35
36
    # Set up signal handler for graceful shutdown
    loop = asyncio.get_running_loop()

    def signal_handler():
        # Schedule the shutdown coroutine instead of calling it directly
        asyncio.create_task(graceful_shutdown(runtime))

    for sig in (signal.SIGTERM, signal.SIGINT):
        loop.add_signal_handler(sig, signal_handler)

    print("Signal handlers registered for graceful shutdown")
Neelay Shah's avatar
Neelay Shah committed
37
    await init(runtime, "dynamo")
38
39


40
41
42
43
44
45
async def graceful_shutdown(runtime: DistributedRuntime):
    print("Received shutdown signal, shutting down DistributedRuntime")
    runtime.shutdown()
    print("DistributedRuntime shutdown complete")


46
47
48
49
50
51
async def init(runtime: DistributedRuntime, ns: str):
    """
    Instantiate a `backend` component and serve the `generate` endpoint
    A `Component` can serve multiple endpoints
    """
    component = runtime.namespace(ns).component("backend")
52
    await component.create_service()
53
54
55

    endpoint = component.endpoint("generate")
    print("Started server instance")
56
57
58

    # the server will gracefully shutdown (i.e., keep opened TCP streams finishes)
    # after the lease is revoked
59
    await endpoint.serve_endpoint(RequestHandler().generate)
60
61
62
63
64


if __name__ == "__main__":
    uvloop.install()
    asyncio.run(worker())