service_v2.rs 3.91 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// 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.

use super::metrics;
use super::ModelManager;
18
use anyhow::Result;
19
use derive_builder::Builder;
20
use tokio::task::JoinHandle;
21
22
23
24
25
26
27
use tokio_util::sync::CancellationToken;

#[derive(Clone)]
pub struct HttpService {
    models: ModelManager,
    router: axum::Router,
    port: u16,
28
    host: String,
29
30
31
}

#[derive(Clone, Builder)]
32
#[builder(pattern = "owned", build_fn(private, name = "build_internal"))]
33
34
35
36
pub struct HttpServiceConfig {
    #[builder(default = "8787")]
    port: u16,

37
38
39
    #[builder(setter(into), default = "String::from(\"0.0.0.0\")")]
    host: String,

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    // #[builder(default)]
    // custom: Vec<axum::Router>
    #[builder(default = "true")]
    enable_chat_endpoints: bool,

    #[builder(default = "true")]
    enable_cmpl_endpoints: bool,
}

impl HttpService {
    pub fn builder() -> HttpServiceConfigBuilder {
        HttpServiceConfigBuilder::default()
    }

    pub fn model_manager(&self) -> &ModelManager {
        &self.models
    }

58
59
60
61
62
63
    pub async fn spawn(&self, cancel_token: CancellationToken) -> JoinHandle<Result<()>> {
        let this = self.clone();
        tokio::spawn(async move { this.run(cancel_token).await })
    }

    pub async fn run(&self, cancel_token: CancellationToken) -> Result<()> {
64
        let address = format!("{}:{}", self.host, self.port);
65
66
67
68
69
70
71
72
73
        tracing::info!(address, "Starting HTTP service on: {address}");

        let listener = tokio::net::TcpListener::bind(address.as_str())
            .await
            .unwrap_or_else(|_| panic!("could not bind to address: {address}"));

        let router = self.router.clone();
        let observer = cancel_token.child_token();

74
        axum::serve(listener, router)
75
76
            .with_graceful_shutdown(observer.cancelled_owned())
            .await
77
78
79
            .inspect_err(|_| cancel_token.cancel())?;

        Ok(())
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    }
}

impl HttpServiceConfigBuilder {
    pub fn build(self) -> Result<HttpService, anyhow::Error> {
        let config = self.build_internal()?;

        let model_manager = ModelManager::new();

        // enable prometheus metrics
        let registry = metrics::Registry::new();
        model_manager.metrics().register(&registry)?;

        let mut router = axum::Router::new();
        let mut all_docs = Vec::new();

        let mut routes = vec![
            metrics::router(registry, None),
            super::openai::list_models_router(model_manager.state(), None),
        ];

        if config.enable_chat_endpoints {
            routes.push(super::openai::completions_router(
                model_manager.state(),
                None,
            ));
        }

        if config.enable_cmpl_endpoints {
            routes.push(super::openai::chat_completions_router(
                model_manager.state(),
                None,
            ));
        }

        // for (route_docs, route) in routes.into_iter().chain(self.routes.into_iter()) {
        //     router = router.merge(route);
        //     all_docs.extend(route_docs);
        // }

        for (route_docs, route) in routes.into_iter() {
            router = router.merge(route);
            all_docs.extend(route_docs);
        }

        Ok(HttpService {
            models: model_manager,
            router,
            port: config.port,
129
            host: config.host,
130
131
132
        })
    }
}