-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathservice.rs
More file actions
249 lines (227 loc) · 9.26 KB
/
Copy pathservice.rs
File metadata and controls
249 lines (227 loc) · 9.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Copyright (c) 2023 - 2026 Restate Software, Inc., Restate GmbH.
// All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
use std::sync::Arc;
use std::time::Duration;
use axum::error_handling::HandleErrorLayer;
use http::{Request, Response, StatusCode};
use restate_ingestion_client::IngestionClient;
use restate_wal_protocol::Envelope;
use tower::ServiceBuilder;
use tower_http::classify::ServerErrorsFailureClass;
use tower_http::compression::CompressionLayer;
use tower_http::trace::TraceLayer;
use tracing::{Span, debug, info, info_span};
use restate_admin_rest_model::version::AdminApiVersion;
use restate_core::network::{TransportConnect, net_util};
use restate_core::{MetadataWriter, TaskCenter};
use restate_limiter::rule_book::RuleBookObserver;
use restate_metadata_store::MetadataStoreClient;
use restate_service_client::HttpClient;
use restate_service_protocol_v4::discovery::ServiceDiscovery;
use restate_service_protocol_v4::serdes::SerdesClient;
use restate_types::config::AdminOptions;
use restate_types::invocation::client::InvocationClient;
use restate_types::live::LiveLoad;
use restate_types::net::address::AdminPort;
use restate_types::net::listener::Listeners;
use restate_types::schema::registry::SchemaRegistry;
use restate_util_time::DurationExt;
use crate::rest_api::{MAX_ADMIN_API_VERSION, MIN_ADMIN_API_VERSION};
use crate::schema_registry_integration::{MetadataService, TelemetryClient};
use crate::{rest_api, state};
#[derive(Debug, thiserror::Error)]
#[error("could not create the service client: {0}")]
pub struct BuildError(#[from] restate_service_client::BuildError);
pub struct AdminService<Metadata, Discovery, Telemetry, Invocations, Transport> {
listeners: Listeners<AdminPort>,
ingestion_client: IngestionClient<Transport, Envelope>,
schema_registry: SchemaRegistry<Metadata, Discovery, Telemetry>,
serdes_client: SerdesClient,
invocation_client: Invocations,
query_context: Option<restate_storage_query_datafusion::context::QueryContext>,
metadata_client: MetadataStoreClient,
rule_book_observer: Option<Arc<dyn RuleBookObserver>>,
}
impl<Invocations, Transport>
AdminService<MetadataService, ServiceDiscovery, TelemetryClient, Invocations, Transport>
where
Invocations: InvocationClient + Send + Sync + Clone + 'static,
Transport: TransportConnect,
{
pub fn new(
listeners: Listeners<AdminPort>,
metadata_writer: MetadataWriter,
ingestion_client: IngestionClient<Transport, Envelope>,
invocation_client: Invocations,
serdes_client: SerdesClient,
service_discovery: ServiceDiscovery,
telemetry_http_client: Option<HttpClient>,
) -> Self {
let metadata_client = metadata_writer.raw_metadata_store_client().clone();
Self {
listeners,
ingestion_client,
schema_registry: SchemaRegistry::new(
MetadataService(metadata_writer),
service_discovery,
TelemetryClient(telemetry_http_client),
),
serdes_client,
invocation_client,
query_context: None,
metadata_client,
rule_book_observer: None,
}
}
pub fn with_query_context(
self,
query_context: restate_storage_query_datafusion::context::QueryContext,
) -> Self {
Self {
query_context: Some(query_context),
..self
}
}
pub fn with_rule_book_observer(self, observer: Arc<dyn RuleBookObserver>) -> Self {
Self {
rule_book_observer: Some(observer),
..self
}
}
pub async fn run(
self,
mut updateable_config: impl LiveLoad<Live = AdminOptions>,
) -> anyhow::Result<()> {
let opts = updateable_config.live_load();
let rest_state = state::AdminServiceState::new(
self.schema_registry,
self.serdes_client,
self.invocation_client,
self.ingestion_client,
self.metadata_client.clone(),
self.query_context,
self.rule_book_observer,
);
let router = axum::Router::new();
#[cfg(feature = "metadata-api")]
let router = router.merge(crate::metadata_api::router(&self.metadata_client));
// Add now the tracing layer, this makes sure we don't log ui requests
let router = router.layer(
TraceLayer::new_for_http()
.make_span_with(|request: &Request<_>| {
info_span!(
target: "restate_admin::api",
"admin-api-request",
http.version = ?request.version(),
http.request.method = %request.method(),
url.path = request.uri().path(),
url.query = request.uri().query().unwrap_or_default(),
url.scheme = request.uri().scheme_str().unwrap_or("http")
)
})
// Just log on response
.on_request(())
.on_eos(())
.on_body_chunk(())
.on_response(
move |response: &Response<_>, latency: Duration, span: &Span| {
debug!(
name: "access-log",
target: "restate_admin::api",
parent: span,
{ http.response.status_code = response.status().as_u16(), http.response.latency = %latency.friendly().to_seconds_span() },
"Replied"
)
},
)
.on_failure(
move |error: ServerErrorsFailureClass, latency: Duration, span: &Span| {
match error {
ServerErrorsFailureClass::StatusCode(_) => {
// No need to log it, on_response will log it already
}
ServerErrorsFailureClass::Error(error_string) => {
debug!(
name: "access-log",
target: "restate_admin::api",
parent: span,
{ error.type = error_string, http.response.latency = %latency.friendly().to_seconds_span() },
"Failed processing"
)
}
}
},
),
);
// Merge Web UI router
#[cfg(feature = "serve-web-ui")]
let router = if !opts.disable_web_ui {
router.merge(crate::web_ui::web_ui_router())
} else {
router
};
// Merge meta API router
let router = router.merge(rest_api::create_router(rest_state));
let router = axum::Router::new()
.merge(with_api_version_middleware(
router.clone(),
AdminApiVersion::Unknown,
))
.nest("/v1", unsupported_api_version(AdminApiVersion::V1))
.nest(
"/v2",
with_api_version_middleware(router.clone(), AdminApiVersion::V2),
)
.nest(
"/v3",
with_api_version_middleware(router.clone(), AdminApiVersion::V3),
)
.nest(
"/v4",
with_api_version_middleware(router, AdminApiVersion::V4),
)
.layer(CompressionLayer::new())
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_| async {
StatusCode::TOO_MANY_REQUESTS
}))
.layer(tower::load_shed::LoadShedLayer::new())
.layer(tower::limit::GlobalConcurrencyLimitLayer::new(
opts.concurrent_api_requests_limit(),
)),
);
let service = hyper_util::service::TowerToHyperService::new(router.into_service());
info!(
"Admin API starting on: {}",
TaskCenter::with_current(|tc| opts.advertised_address(tc.address_book()))
);
net_util::run_hyper_server(self.listeners, service, || (), None)
.await
.map_err(Into::into)
}
}
fn unsupported_api_version(version: AdminApiVersion) -> axum::Router {
axum::Router::new().fallback((
StatusCode::BAD_REQUEST,
format!(
"Unsupported Admin API version {:?}. This server supports versions between {:?} and {:?}.",
version, MIN_ADMIN_API_VERSION, MAX_ADMIN_API_VERSION,
),
))
}
fn with_api_version_middleware(router: axum::Router, version: AdminApiVersion) -> axum::Router {
router.layer(axum::middleware::from_fn(
move |mut request: axum::extract::Request, next: axum::middleware::Next| {
request.extensions_mut().insert(version);
next.run(request)
},
))
}