Files
crank/crates/crank-metrics/tests/schema_v1.rs
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

632 lines
24 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::collections::BTreeSet;
use crank_metrics::{
HTTP_ROUTE_DOMAIN, HttpRoute, LabelClass, LabelDomain, MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS, METRIC_SCHEMA_VERSION,
MetricDefinition, MetricKind, MetricProcess, MetricService, MetricUnit, metric_schema,
metric_schema_for_service, render_metric_schema_json, schema_budget, validate_budget,
validate_schema,
};
#[test]
fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
assert_eq!(METRIC_SCHEMA_VERSION, 2);
assert_eq!(metric_schema().len(), 23);
for service in [MetricService::AdminApi, MetricService::McpServer] {
let budget = schema_budget(service).expect("canonical schema must be valid");
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
}
for definition in metric_schema() {
assert!(!definition.description.trim().is_empty());
assert!(definition.labels.len() <= MAX_PRODUCT_LABELS_PER_FAMILY);
assert!(!definition.processes.is_empty());
assert_eq!(definition.labels.len(), definition.label_domains.len());
assert!(definition.label_domains.iter().all(|domain| {
!domain.values.is_empty()
&& domain.values.iter().all(|value| !value.is_empty())
&& domain.values.iter().copied().collect::<BTreeSet<_>>().len()
== domain.values.len()
}));
if definition.kind.as_str() == "histogram" {
assert!(!definition.buckets.is_empty());
assert!(definition.buckets.windows(2).all(|pair| pair[0] < pair[1]));
} else {
assert!(definition.buckets.is_empty());
}
}
let first = render_metric_schema_json().expect("schema renders");
let second = render_metric_schema_json().expect("schema renders deterministically");
assert_eq!(first, second);
assert!(first.len() < 65_536);
assert!(!first.contains("trace_id"));
assert!(!first.contains("request_id"));
}
#[test]
fn frozen_budget_edges_are_exact() {
assert!(validate_budget(6_284, 19_514).is_ok());
assert!(validate_budget(6_285, 19_515).is_ok());
assert!(validate_budget(6_286, 16_000).is_err());
assert!(validate_budget(6_000, 19_516).is_err());
assert_eq!(
crank_metrics::max_exemplar_slots(MetricService::AdminApi),
12_348
);
assert_eq!(
crank_metrics::max_exemplar_slots(MetricService::McpServer),
2_310
);
assert!(crank_metrics::validate_exemplar_budget(12_348).is_ok());
assert!(crank_metrics::validate_exemplar_budget(12_349).is_err());
}
#[test]
fn every_registered_route_round_trips_without_dynamic_segments() {
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 91);
for route in HTTP_ROUTE_DOMAIN {
assert_eq!(HttpRoute::from_matched_path(route).as_str(), *route);
assert!(!route.contains("trace_id"));
assert!(!route.contains("request_id"));
}
}
#[test]
fn canonical_schema_validation_reports_its_category() {
assert_eq!(
schema_budget(MetricService::AdminApi),
Ok(crank_metrics::SchemaBudget {
logical_series: 6_285,
rendered_series: 19_515
})
);
assert_eq!(
schema_budget(MetricService::McpServer),
Ok(crank_metrics::SchemaBudget {
logical_series: 1_083,
rendered_series: 3_558
})
);
}
#[test]
fn exact_budget_math_counts_histogram_bucket_sum_and_count_series() {
for definition in metric_schema() {
let logical = definition
.label_domains
.iter()
.map(|domain| domain.values.len())
.product::<usize>();
let logical = logical.max(1);
let rendered = if definition.kind.as_str() == "histogram" {
logical * (definition.buckets.len() + 3)
} else {
logical
};
assert_eq!(
definition.max_logical_series, logical,
"{}",
definition.name
);
assert_eq!(
definition.max_rendered_series, rendered,
"{}",
definition.name
);
}
}
#[test]
fn prometheus_reserved_and_digit_prefixed_label_names_are_rejected() {
static DOMAIN: LabelDomain = LabelDomain {
name: "valid",
class: LabelClass::ProductClosed,
values: &["value"],
};
for label in ["1invalid", "__reserved"] {
let mut domain = DOMAIN;
domain.name = label;
let definition = MetricDefinition {
name: "crank_test_total",
kind: MetricKind::Counter,
unit: MetricUnit::Count,
labels: Box::leak(vec![label].into_boxed_slice()),
label_domains: Box::leak(vec![domain].into_boxed_slice()),
buckets: &[],
processes: &[MetricProcess::AdminApi],
max_logical_series: 1,
max_rendered_series: 1,
description: "test metric",
};
assert!(validate_schema(&[definition]).is_err(), "accepted {label}");
}
}
#[test]
fn process_projection_excludes_mcp_only_metrics_from_admin() {
let admin = metric_schema_for_service(MetricService::AdminApi)
.map(|definition| definition.name)
.collect::<BTreeSet<_>>();
let mcp = metric_schema_for_service(MetricService::McpServer)
.map(|definition| definition.name)
.collect::<BTreeSet<_>>();
assert!(!admin.contains("crank_mcp_active_sessions"));
assert!(!admin.contains("crank_catalog_tools"));
assert!(mcp.contains("crank_mcp_active_sessions"));
assert!(admin.contains("crank_http_requests_total"));
assert!(mcp.contains("crank_http_requests_total"));
}
#[test]
fn registered_admin_and_mcp_routes_are_exactly_the_schema_domain() {
let admin_source = include_str!("../../../apps/admin-api/src/app.rs");
let mcp_source = include_str!("../../crank-community-mcp/src/app.rs");
let auth = [
"/bootstrap/status",
"/bootstrap/complete",
"/login",
"/logout",
"/session",
"/session/csrf",
"/profile",
"/password",
];
let admin_root = ["/capabilities", "/workspaces", "/workspaces/{workspace_id}"];
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
for route in route_literals(admin_source) {
let canonical = if matches!(route.as_str(), "/health" | "/ready") {
route
} else if auth.contains(&route.as_str()) {
format!("/api/auth{route}")
} else if admin_root.contains(&route.as_str()) {
format!("/api/admin{route}")
} else {
format!("/api/admin/workspaces/{{workspace_id}}{route}")
};
actual.insert(canonical);
}
actual.extend(route_literals(mcp_source));
let expected = HTTP_ROUTE_DOMAIN
.iter()
.map(|route| (*route).to_owned())
.collect::<BTreeSet<_>>();
assert_eq!(actual, expected);
}
fn route_literals(source: &str) -> Vec<String> {
let mut routes = Vec::new();
let mut remaining = source;
while let Some(offset) = remaining.find(".route(") {
remaining = &remaining[offset + ".route(".len()..];
let Some(start) = remaining.find('"') else {
break;
};
let after_start = &remaining[start + 1..];
let Some(end) = after_start.find('"') else {
break;
};
routes.push(after_start[..end].to_owned());
remaining = &after_start[end + 1..];
}
routes
}
/// TD-C5: замороженный v1-снимок `docs/schemas/metrics-registry-v1.json` остаётся
/// byte-for-byte compatibility input'ом, а не пере-генерируется под новый контракт.
///
/// Оракул — sha256 + точная длина самих байтов файла. sha256 реализован здесь
/// локально (без новой dependency), поэтому первым шагом проверяются контрольные
/// векторы FIPS 180-4: без них byte-oracle был бы вакуумным.
#[test]
fn v1_snapshot_is_retained_byte_for_byte() {
// Self-control локального хэшера (FIPS 180-4).
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
const FROZEN_V1_SNAPSHOT: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
assert_eq!(
sha256_hex(FROZEN_V1_SNAPSHOT.as_bytes()),
"b2ff5f31187559d1095df76fa685e4a9b68db8252523d3a844f5db5da3f48560",
"замороженный v1-снимок обязан оставаться byte-for-byte неизменным"
);
assert_eq!(
FROZEN_V1_SNAPSHOT.len(),
18_512,
"длина замороженного v1-снимка обязана оставаться неизменной"
);
assert!(
FROZEN_V1_SNAPSHOT.contains("\"schema_version\": 1"),
"v1-снимок обязан объявлять свою версию контракта"
);
assert!(
!FROZEN_V1_SNAPSHOT.contains("\"schema_version\": 2"),
"v1-снимок не пере-генерируется под v2-контракт"
);
}
fn sha256_hex(input: &[u8]) -> String {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut state: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let bit_length = (input.len() as u64).wrapping_mul(8);
let mut message = input.to_vec();
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&bit_length.to_be_bytes());
for block in message.chunks_exact(64) {
let mut schedule = [0_u32; 64];
for (index, chunk) in block.chunks_exact(4).enumerate() {
schedule[index] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
for index in 16..64 {
let s0 = schedule[index - 15].rotate_right(7)
^ schedule[index - 15].rotate_right(18)
^ (schedule[index - 15] >> 3);
let s1 = schedule[index - 2].rotate_right(17)
^ schedule[index - 2].rotate_right(19)
^ (schedule[index - 2] >> 10);
schedule[index] = schedule[index - 16]
.wrapping_add(s0)
.wrapping_add(schedule[index - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = state;
for index in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let choice = (e & f) ^ ((!e) & g);
let temp1 = h
.wrapping_add(s1)
.wrapping_add(choice)
.wrapping_add(K[index])
.wrapping_add(schedule[index]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let majority = (a & b) ^ (a & c) ^ (b & c);
let temp2 = s0.wrapping_add(majority);
h = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
for (slot, value) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
*slot = slot.wrapping_add(value);
}
}
state.iter().map(|word| format!("{word:08x}")).collect()
}
/// F7 (CONTRACT §6) — v1↔v2 metric-by-metric compatibility на реальных байтах
/// обоих замороженных документов: kind/unit/help/processes/порядок labels/class/
/// non-route домены/buckets обязаны совпадать, а v1 route-домен — быть
/// подмножеством v2 union (`domain_ref: http_routes`). Парсер минимальный:
/// никакой новой dependency, оба документа machine-generated.
#[test]
fn v1_and_v2_registries_are_metric_by_metric_compatible() {
const V1: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
const V2: &str = include_str!("../../../docs/schemas/metrics-registry-v2.json");
let v1 = metric_objects(V1);
let v2 = metric_objects(V2);
assert_eq!(v1.len(), 23);
assert_eq!(
v1.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
v2.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
"v2 обязан сохранить тот же набор и порядок family"
);
for ((name, v1_object), (_, v2_object)) in v1.iter().zip(v2.iter()) {
for field in ["kind", "unit", "help", "processes", "buckets_seconds"] {
assert_eq!(
json_field(v1_object, field),
json_field(v2_object, field),
"{name}: поле {field} обязано быть совместимым между v1 и v2"
);
}
let v1_labels = label_entries(v1_object);
let v2_labels = label_entries(v2_object);
assert_eq!(
v1_labels
.iter()
.map(|label| label.name.clone())
.collect::<Vec<_>>(),
v2_labels
.iter()
.map(|label| label.name.clone())
.collect::<Vec<_>>(),
"{name}: порядок labels обязан совпадать"
);
for (v1_label, v2_label) in v1_labels.iter().zip(v2_labels.iter()) {
assert_eq!(v1_label.class, v2_label.class, "{name}/{}", v1_label.name);
if v1_label.name == "route" {
assert_eq!(v1_label.domain_ref, None);
assert_eq!(
v2_label.domain_ref.as_deref(),
Some("http_routes"),
"{name}: v2 обязан ссылаться на единый union маршрутов"
);
continue;
}
assert_eq!(
v1_label.domain, v2_label.domain,
"{name}/{}: домен обязан совпадать между v1 и v2",
v1_label.name
);
assert_eq!(v2_label.domain_ref, None);
}
}
let v1_routes = route_domain_v1(V1);
let v2_routes = union_routes_v2(V2);
assert_eq!(v1_routes.len(), 72, "замороженный v1 route-домен");
assert_eq!(v2_routes.len(), 91);
for route in &v1_routes {
assert!(
v2_routes.contains(route),
"v1 route `{route}` отсутствует в v2 union"
);
}
let added = v2_routes
.iter()
.filter(|route| !v1_routes.contains(*route))
.collect::<Vec<_>>();
assert_eq!(
added.len(),
19,
"v2 обязан добавить тринадцать Resource и шесть Prompt шаблонов"
);
assert_eq!(
added
.iter()
.filter(|route| route.contains("/resources"))
.count(),
13
);
assert_eq!(
added
.iter()
.filter(|route| route.contains("/prompts"))
.count(),
6
);
}
/// F7/R2 — контроль самого compatibility helper'а: пробелы вне строк
/// незначимы, изменение HELP внутри строки обязано обнаруживаться, а значимый
/// пробел внутри строки — сохраняться.
#[test]
fn help_compatibility_helper_preserves_string_content() {
let compact = "{\"help\":\"Total HTTP requests.\",\"unit\":\"1\"}";
let pretty = "{\n \"help\": \"Total HTTP requests.\",\n \"unit\": \"1\"\n}";
assert_eq!(
compact_json(pretty),
compact,
"format-only пробелы вне строк обязаны игнорироваться"
);
assert_eq!(
json_field(&compact_json(pretty), "help"),
json_field(&compact_json(compact), "help")
);
assert!(
compact_json(compact).contains("\"Total HTTP requests.\""),
"значимый пробел HELP обязан сохраняться в компакте: {}",
compact_json(compact)
);
let changed_help = "{\"help\":\"TotalHTTP requests.\",\"unit\":\"1\"}";
assert_ne!(
json_field(&compact_json(compact), "help"),
json_field(&compact_json(changed_help), "help"),
"изменение HELP внутри строки обязано быть обнаружено"
);
let reflowed_help = "{\"help\":\"Total HTTP requests.\",\"unit\":\"1\"}";
assert_ne!(
json_field(&compact_json(compact), "help"),
json_field(&compact_json(reflowed_help), "help"),
"внутренние пробелы HELP значимы и обязаны различаться"
);
}
struct RegistryLabel {
name: String,
class: String,
domain: Vec<String>,
domain_ref: Option<String>,
}
/// Компактизация JSON: пробелы удаляются только ВНЕ строк. Содержимое
/// quoted/escaped string сохраняется байт-в-байт, иначе значимые пробелы HELP
/// (`"Total HTTP requests."` против `"TotalHTTP requests."`) стали бы
/// неразличимыми и per-metric oracle пропустил бы drift (F7 / R2).
fn compact_json(text: &str) -> String {
let mut compact = String::with_capacity(text.len());
let mut in_string = false;
let mut escaped = false;
for ch in text.chars() {
if in_string {
compact.push(ch);
if escaped {
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == '"' {
in_string = false;
}
continue;
}
if ch == '"' {
in_string = true;
compact.push(ch);
} else if !ch.is_whitespace() {
compact.push(ch);
}
}
compact
}
/// `(name, compact object)` для каждой family из секции `"metrics":[`.
/// Секция ограничивается парным `]`, поэтому `budgets`/`http_routes` в неё не
/// попадают, а top-level объекты выделяются балансировкой скобок.
fn metric_objects(document: &str) -> Vec<(String, String)> {
let compact = compact_json(document);
let marker = "\"metrics\":[";
let metrics_at = compact.find(marker).expect("metrics section");
let array_start = metrics_at + marker.len() - 1;
let array_end = array_start + balanced_end(&compact[array_start..], b'[', b']');
let section = &compact[array_start + 1..array_end - 1];
let mut objects = Vec::new();
let mut cursor = 0_usize;
while let Some(offset) = section[cursor..].find('{') {
let at = cursor + offset;
let end = at + balanced_end(&section[at..], b'{', b'}');
let object = &section[at..end];
let name = unquote(&json_field(object, "name"));
objects.push((name, object.to_owned()));
cursor = end;
}
objects
}
/// Значение поля как compact JSON text: строка, массив, объект или scalar.
fn json_field(object: &str, key: &str) -> String {
let needle = format!("\"{key}\":");
let at = object
.find(&needle)
.unwrap_or_else(|| panic!("поле {key} отсутствует"));
let value = &object[at + needle.len()..];
match value.as_bytes().first() {
Some(b'"') => {
let end = value[1..].find('"').expect("string terminator");
value[..end + 2].to_owned()
}
Some(b'[') => value[..balanced_end(value, b'[', b']')].to_owned(),
Some(b'{') => value[..balanced_end(value, b'{', b'}')].to_owned(),
_ => value
.find([',', '}'])
.map_or_else(|| value.to_owned(), |end| value[..end].to_owned()),
}
}
fn balanced_end(value: &str, open: u8, close: u8) -> usize {
let mut depth = 0_usize;
for (index, byte) in value.bytes().enumerate() {
if byte == open {
depth += 1;
} else if byte == close {
depth = depth.saturating_sub(1);
if depth == 0 {
return index + 1;
}
}
}
panic!("unbalanced JSON value");
}
fn unquote(value: &str) -> String {
value.trim_matches('"').to_owned()
}
fn string_array(value: &str) -> Vec<String> {
let inner = &value[1..value.len() - 1];
let mut values = Vec::new();
let mut cursor = 0_usize;
while let Some(at) = inner[cursor..].find('"') {
let at = cursor + at;
let after = &inner[at + 1..];
let end = after.find('"').expect("string terminator");
values.push(after[..end].to_owned());
cursor = at + 1 + end + 1;
}
values
}
fn label_entries(object: &str) -> Vec<RegistryLabel> {
let array = json_field(object, "labels");
let inner = array[1..array.len() - 1].to_owned();
let mut labels = Vec::new();
let mut cursor = 0_usize;
while let Some(at) = inner[cursor..].find("{\"name\":") {
let at = cursor + at;
let end = at + balanced_end(&inner[at..], b'{', b'}');
let entry = &inner[at..end];
labels.push(RegistryLabel {
name: unquote(&json_field(entry, "name")),
class: unquote(&json_field(entry, "class")),
domain: if entry.contains("\"domain\":[") {
string_array(&json_field(entry, "domain"))
} else {
Vec::new()
},
domain_ref: entry
.contains("\"domain_ref\":")
.then(|| unquote(&json_field(entry, "domain_ref"))),
});
cursor = end;
}
labels
}
fn route_domain_v1(document: &str) -> Vec<String> {
let objects = metric_objects(document);
let (_, object) = objects
.iter()
.find(|(name, _)| name == "crank_http_requests_total")
.expect("v1 HTTP counter");
label_entries(object)
.into_iter()
.find(|label| label.name == "route")
.expect("v1 route label")
.domain
}
fn union_routes_v2(document: &str) -> Vec<String> {
let compact = compact_json(document);
let section = &compact[compact
.find("\"http_routes\":[")
.expect("http_routes section")..];
let needle = "\"route\":\"";
let mut routes = Vec::new();
let mut cursor = 0_usize;
while let Some(at) = section[cursor..].find(needle) {
let at = cursor + at + needle.len();
let end = section[at..].find('"').expect("route terminator");
routes.push(section[at..at + end].to_owned());
cursor = at + end + 1;
}
routes
}