redup-bootstrap 0.3.3

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
Documentation
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Сценарные тесты телеметрии на настоящем сокете: метрики, страницы сведений, журнал и контекст
//! запроса.

// Помощники теста вызываются из функций `#[test]`: неудачный разбор образца здесь — ошибка теста.
#![allow(clippy::expect_used)]

mod common;

use std::collections::BTreeSet;
use std::error::Error;
use std::net::SocketAddr;
use std::time::Duration;

use common::{Events, LISTENER, get_with};
use prometheus_parse::{Sample, Scrape, Value};
use redup_abstractions::DependencyRole;
use redup_bootstrap::{
    Builder, Context, CustomProbe, Level, LoadKind, Module, ModuleError, Service, Template, Unit,
    async_trait,
};
use redup_config::Config;

type TestResult<T> = std::result::Result<T, Box<dyn Error>>;

/// Настройки модуля `Job`.
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct JobSettings {
    /// Период фоновой работы. Нуль — работы нет.
    tick: Duration,
    /// Секрет, который не должен попасть на страницу сведений.
    api_secret: Option<String>,
}

/// Модуль с прикладной метрикой, зависимостью и учётом фоновой работы.
struct Job;

#[async_trait]
impl Module for Job {
    const NAME: &'static str = "Job";
    type Config = JobSettings;
    type Args = ();

    async fn create(
        settings: JobSettings,
        (): (),
        ctx: &mut Context<'_>,
    ) -> Result<Self, ModuleError> {
        let processed =
            ctx.meter()
                .counter("job_processed", Unit::Count, "Обработанные задачи.")?;
        let neighbour = ctx
            .dependency("neighbour")
            .probe(CustomProbe::new(|_| async move { Ok(true) }))
            .start()?;
        let health = ctx.health();
        health.track(&neighbour, DependencyRole::Critical);
        health.set(redup_abstractions::Phase::Serving);
        if !settings.tick.is_zero() {
            let load = ctx.load();
            let work = load.clone();
            let token = ctx.token();
            let processed = processed.clone();
            let tick = settings.tick;
            tokio::spawn(async move {
                loop {
                    tokio::select! {
                        _ = token.cancelled() => return,
                        _ = tokio::time::sleep(tick) => {}
                    }
                    let _work = work.work(LoadKind::Worker);
                    tokio::time::sleep(tick / 2).await;
                    processed.increment(1);
                }
            });
        }
        Ok(Self)
    }

    fn details(&self) -> Vec<(String, String)> {
        vec![("queue".to_owned(), "0".to_owned())]
    }
}

/// Запускает инстанс с модулем `Job` и слушателем; `bootstrap` дописывается к секции платформы.
async fn start(tick: &str, bootstrap: &str) -> TestResult<redup_bootstrap::Instance> {
    let (_directory, source) = Events::source(&format!(
        "{LISTENER}{bootstrap}jobSettings:\n  tick: {tick}\n  apiSecret: s3cret-value\n"
    ))?;
    let service = Service::new("trial", "0.1.0");
    let mut builder = Builder::new(&source, service)?;
    builder.add::<Job>(()).await?;
    let mut instance = builder.build();
    instance.start().await?;
    Ok(instance)
}

/// Ответ на GET с заголовками запроса: код, тип содержимого и тело.
async fn get(
    address: SocketAddr,
    path: &str,
    headers: &[(&str, &str)],
) -> TestResult<(u16, String, String)> {
    let reply = get_with(address, path, headers).await?;
    Ok((reply.status, reply.content_type, reply.body))
}

/// Разбирает текст Prometheus независимым разборщиком.
fn scrape(body: &str) -> Scrape {
    Scrape::parse(
        body.lines()
            .map(|line| Ok::<String, std::io::Error>(line.to_owned())),
    )
    .expect("the exposition text is parsed by prometheus-parse")
}

/// Ряды выгрузки с именем `metric` и метками `labels`.
fn series<'a>(scrape: &'a Scrape, metric: &str, labels: &[(&str, &str)]) -> Vec<&'a Sample> {
    scrape
        .samples
        .iter()
        .filter(|sample| {
            sample.metric == metric
                && labels.iter().all(|(name, value)| {
                    sample
                        .labels
                        .get(name)
                        .is_some_and(|found| *found == **value)
                })
        })
        .collect()
}

/// Числовое значение единственного ряда метрики с метками `labels`.
fn number(scrape: &Scrape, metric: &str, labels: &[(&str, &str)]) -> f64 {
    let found = series(scrape, metric, labels);
    assert_eq!(found.len(), 1, "expected one series of {metric}");
    match found[0].value {
        Value::Counter(value) | Value::Gauge(value) | Value::Untyped(value) => value,
        _ => unreachable!("{metric} is not a number"),
    }
}

/// Имена всех семейств выгрузки.
fn families(scrape: &Scrape) -> BTreeSet<String> {
    scrape
        .samples
        .iter()
        .map(|sample| {
            let name = sample.metric.as_str();
            let name = name.strip_suffix("_bucket").unwrap_or(name);
            let name = name.strip_suffix("_sum").unwrap_or(name);
            let name = name.strip_suffix("_count").unwrap_or(name);
            name.to_owned()
        })
        .collect()
}

/// Имена метрик из эталона `contracts/metrics/prometheus.txt`.
fn contract() -> BTreeSet<String> {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../contracts/metrics/prometheus.txt"
    );
    let text = std::fs::read_to_string(path).expect("the reference file of metrics");
    text.lines()
        .filter_map(|line| line.strip_prefix("# TYPE "))
        .filter_map(|line| line.split_whitespace().next())
        .map(str::to_owned)
        .collect()
}

#[tokio::test]
async fn metrics_follow_the_contract() -> TestResult<()> {
    let mut instance = start("20ms", "").await?;
    let address = instance.address().ok_or("the listener is not started")?;
    assert_eq!(get(address, "/readyz", &[]).await?.0, 200);
    // Фоновая работа модуля должна успеть попасть в нагрузку.
    tokio::time::sleep(Duration::from_millis(120)).await;
    let (status, content_type, body) = get(address, "/metrics", &[]).await?;
    instance.stop().await;
    assert_eq!(status, 200);
    assert!(
        content_type.starts_with("text/plain; version=0.0.4"),
        "{content_type}"
    );
    let scrape = scrape(&body);

    // Служба и платформа.
    let build = [("version", "0.1.0"), ("bootstrap_version", "0.3.3")];
    assert_eq!(number(&scrape, "build_info", &build), 1.0);
    let target = [("service_name", "trial"), ("service_version", "0.1.0")];
    assert_eq!(number(&scrape, "target_info", &target), 1.0);

    // Зависимость: одна проба в режиме `once` прошла.
    let dependency = [("module", "Job"), ("dependency", "neighbour")];
    assert_eq!(number(&scrape, "dependency_state", &dependency), 2.0);
    assert_eq!(number(&scrape, "dependency_up", &dependency), 1.0);

    // Прикладная метрика — с префиксом службы; нагрузка — от фоновой работы модуля.
    assert!(
        number(&scrape, "trial_job_processed_total", &[]) >= 1.0,
        "{body}"
    );
    let worker = number(&scrape, "worker_load_total", &[]);
    assert!(worker > 0.0, "{body}");
    assert_eq!(number(&scrape, "incoming_load_total", &[]), 0.0);
    assert_eq!(number(&scrape, "outgoing_load_total", &[]), 0.0);
    assert_eq!(number(&scrape, "load_total", &[]), worker);
    assert_eq!(number(&scrape, "service_load_total", &[]), worker);

    // Процесс.
    assert!(number(&scrape, "mem_working_set_bytes", &[]) > 0.0);
    assert!(number(&scrape, "process_resident_memory_bytes", &[]) > 0.0);
    assert!(number(&scrape, "process_cpu_seconds_total", &[]) >= 0.0);
    assert!(number(&scrape, "process_start_time_seconds", &[]) > 1.7e9);
    assert!(number(&scrape, "process_threads", &[]) >= 1.0);
    assert!(number(&scrape, "process_open_fds", &[]) >= 1.0);
    assert!(number(&scrape, "process_max_fds", &[]) > 0.0);

    // Запрос к слушателю попал в гистограмму HTTP и в `rest_call`.
    let http = [
        ("http_request_method", "GET"),
        ("http_response_status_code", "200"),
        ("http_route", "/readyz"),
        ("network_protocol_version", "1.1"),
        ("url_scheme", "http"),
    ];
    assert_eq!(
        series(&scrape, "http_server_request_duration_seconds_count", &http).len(),
        1,
        "{body}"
    );
    assert_eq!(number(&scrape, "rest_call_count", &[]), 1.0);

    // Все метрики эталона, у которых уже есть источник, выходят под своими именами.
    let expected: BTreeSet<String> = contract()
        .into_iter()
        .filter(|name| !name.starts_with("grpc_server_") && name != "load_average_optimal")
        .collect();
    let present = families(&scrape);
    let missing: Vec<&String> = expected.difference(&present).collect();
    assert!(missing.is_empty(), "missing: {missing:?}\n{body}");
    Ok(())
}

#[tokio::test]
async fn metrics_follow_the_configuration() -> TestResult<()> {
    let mut instance = start(
        "20ms",
        "  metrics:\n    optimalAverageLoad: 0.7\n    load:\n      denominator: 2\n",
    )
    .await?;
    let address = instance.address().ok_or("the listener is not started")?;
    tokio::time::sleep(Duration::from_millis(120)).await;
    let body = get(address, "/metrics", &[]).await?.2;
    instance.stop().await;
    let scrape = scrape(&body);
    assert_eq!(number(&scrape, "load_average_optimal", &[]), 0.7);
    let worker = number(&scrape, "worker_load_total", &[]);
    assert!(worker >= 2.0, "{body}");
    assert_eq!(number(&scrape, "load_total", &[]), (worker / 2.0).floor());
    Ok(())
}

#[tokio::test]
async fn pages_show_the_instance_modules_and_configurations() -> TestResult<()> {
    let mut instance = start("0s", "").await?;
    let address = instance.address().ok_or("the listener is not started")?;

    let (status, content_type, body) = get(address, "/info", &[]).await?;
    assert_eq!(
        (status, content_type.as_str()),
        (200, "text/html; charset=utf-8")
    );
    assert!(body.starts_with("<!DOCTYPE html>"), "{body}");
    for text in [
        "trial",
        "0.1.0",
        "/info/Job",
        "/readyz/Job",
        "/config/JobSettings",
    ] {
        assert!(body.contains(text), "/info lacks {text}:\n{body}");
    }

    let (status, _, body) = get(address, "/info/Job", &[]).await?;
    assert_eq!(status, 200);
    for text in [
        "Модуль Job",
        "neighbour",
        "Up",
        "queue",
        "/config/JobSettings",
    ] {
        assert!(body.contains(text), "/info/Job lacks {text}:\n{body}");
    }

    let (status, content_type, body) = get(address, "/config", &[]).await?;
    assert_eq!(
        (status, content_type.as_str()),
        (200, "text/html; charset=utf-8")
    );
    assert!(
        body.contains("/config/JobSettings") && body.contains("/config/Bootstrap"),
        "{body}"
    );

    let (status, _, body) = get(address, "/config/JobSettings", &[]).await?;
    assert_eq!(status, 200);
    assert!(
        body.contains("Tick") && body.contains("ApiSecret") && body.contains("*****"),
        "{body}"
    );
    assert!(
        !body.contains("s3cret-value"),
        "the secret is shown:\n{body}"
    );

    for path in ["/info/Nobody", "/config/Nobody"] {
        let (status, content_type, body) = get(address, path, &[]).await?;
        assert_eq!(
            (status, content_type.as_str()),
            (404, "text/plain; charset=utf-8")
        );
        assert_eq!(body, "Not found");
    }
    instance.stop().await;
    Ok(())
}

#[tokio::test]
async fn journal_is_controlled_by_its_handle() -> TestResult<()> {
    let (_directory, source) = Events::none()?;
    let service = Service::new("trial", "0.1.0");
    let mut builder = Builder::new(&source, service)?;
    builder.add::<Job>(()).await?;
    let instance = builder.build();
    let logging = instance.logging();
    assert_eq!(logging.level(), Level::Info);
    assert_eq!(logging.template(), Template::Auto);

    let mut capture = logging.capture(Level::Trace);
    tracing::info!("captured message");
    tracing::debug!("too detailed");
    let first = capture.next().await.ok_or("no message is captured")?;
    assert_eq!(
        (first.level(), first.message()),
        (Level::Info, "captured message")
    );

    logging.set_level(Level::Trace);
    tracing::debug!("now detailed");
    let second = capture
        .next()
        .await
        .ok_or("the debug message is not captured")?;
    assert_eq!(
        (second.level(), second.message()),
        (Level::Debug, "now detailed")
    );

    logging.set_level(Level::Off);
    tracing::error!("silenced");
    assert!(
        tokio::time::timeout(Duration::from_millis(50), capture.next())
            .await
            .is_err()
    );
    Ok(())
}

/// Сборка без экспорта: заданный коллектор — ошибка сборки, а не молчаливое отсутствие отрезков.
#[cfg(not(feature = "otlp"))]
#[tokio::test]
async fn collector_needs_the_export_feature() -> TestResult<()> {
    let (_directory, source) = Events::source(&format!(
        "{LISTENER}  tracing:\n    collector: 127.0.0.1:4317\n"
    ))?;
    let error = Builder::new(&source, Service::new("trial", "0.1.0"))
        .err()
        .ok_or("the collector is accepted without the trace export")?;
    let text = error.to_string();
    assert!(
        text.contains("127.0.0.1:4317") && text.contains("trace export"),
        "{text}"
    );
    Ok(())
}

#[tokio::test]
async fn request_context_reaches_the_journal() -> TestResult<()> {
    let mut instance = start("0s", "").await?;
    let address = instance.address().ok_or("the listener is not started")?;
    let logging = instance.logging();
    logging.set_level(Level::Trace);
    let mut capture = logging.capture(Level::Debug);
    let correlation = "6f107bf6-289b-4421-acee-40e1b9f5b4c9";
    let headers = [
        ("X-Correlation-ID", correlation),
        (
            "traceparent",
            "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
        ),
    ];
    assert_eq!(get(address, "/readyz", &headers).await?.0, 200);
    let found = tokio::time::timeout(Duration::from_secs(5), async {
        while let Some(message) = capture.next().await {
            if message.message() == "request handled" {
                return message;
            }
        }
        unreachable!("the journal outlives the instance")
    })
    .await;
    instance.stop().await;
    let message = found.map_err(|_| "the request event did not reach the journal in time")?;
    assert_eq!(message.level(), Level::Debug);
    assert_eq!(message.correlation_id(), Some(correlation));
    Ok(())
}