heddle-cli 0.15.0

An AI-native version control system
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
use std::{
    env,
    net::Ipv4Addr,
    time::{Duration, Instant},
};

use api::{
    HOSTED_ALPN_V1,
    framing::{ResponseFrame, decode_response_frame, encode_request_frame},
    heddle::api::v1alpha1::{
        CallContext, CallFailureCode, EndpointDescriptor, SignedEndpointDescriptor,
    },
    signing::endpoint_descriptor_bytes,
};
use crypto::{Ed25519Signer, Signer};
use iroh::{Endpoint, RelayMode, endpoint::presets};
use n0_watcher::Watcher;

use super::{
    DescriptorKeyring, VerifiedEndpointDescriptor,
    claim_protocol::{CLAIM_ALPN_V1, CLAIM_RESOLVE_METHOD},
    connection::HostedConnection,
};

const HOSTED_ENDPOINT_CLOSE_P95_BUDGET: Duration = Duration::from_millis(20);
const DEFAULT_CLOSE_SAMPLE_COUNT: usize = 20;

struct HeddleHomeEnvGuard {
    previous: Option<std::ffi::OsString>,
    _home: tempfile::TempDir,
}

impl HeddleHomeEnvGuard {
    fn isolated() -> Self {
        let home = tempfile::TempDir::new().expect("temp Heddle home");
        let previous = std::env::var_os("HEDDLE_HOME");
        unsafe {
            std::env::set_var("HEDDLE_HOME", home.path());
        }
        Self {
            previous,
            _home: home,
        }
    }
}

impl Drop for HeddleHomeEnvGuard {
    fn drop(&mut self) {
        match self.previous.take() {
            Some(value) => unsafe { std::env::set_var("HEDDLE_HOME", value) },
            None => unsafe { std::env::remove_var("HEDDLE_HOME") },
        }
    }
}

fn require_release_build() {
    #[cfg(debug_assertions)]
    panic!("hosted endpoint close contract must run with --release");
}

fn verified_descriptor(
    endpoint_id: iroh::EndpointId,
    relay_urls: Vec<String>,
    direct_addresses: Vec<String>,
) -> VerifiedEndpointDescriptor {
    let signer = Ed25519Signer::generate().unwrap();
    let now = chrono::Utc::now().timestamp_millis();
    let descriptor = EndpointDescriptor {
        version: 1,
        endpoint_id: endpoint_id.to_string(),
        relay_urls,
        direct_addresses,
        supported_alpns: vec![HOSTED_ALPN_V1.to_vec()],
        issued_at_unix_millis: now - 1_000,
        expires_at_unix_millis: now + 60_000,
        rotation: None,
    };
    let signed = SignedEndpointDescriptor {
        signature: signer
            .sign(&endpoint_descriptor_bytes(&descriptor))
            .unwrap(),
        descriptor: Some(descriptor),
        key_id: "test-key".to_string(),
    };
    let mut keys = DescriptorKeyring::default();
    keys.insert(
        "test-key",
        signer.public_key().try_into().unwrap(),
        i64::MIN,
        i64::MAX,
    )
    .unwrap();
    keys.verify(&signed, now).unwrap()
}

#[tokio::test]
#[ignore = "release-only hosted endpoint close performance contract"]
#[allow(clippy::await_holding_lock)]
async fn hosted_endpoint_close_release_contract() {
    let _env_guard = cli_shared::credentials::lock_test_env();
    let _home = HeddleHomeEnvGuard::isolated();
    require_release_build();
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_test_writer()
        .try_init();
    let sample_count = env::var("HEDDLE_HOSTED_CLOSE_SAMPLES")
        .map(|value| {
            value
                .parse::<usize>()
                .expect("sample count must be an integer")
        })
        .unwrap_or(DEFAULT_CLOSE_SAMPLE_COUNT);
    assert!(
        sample_count >= 5,
        "close contract requires at least 5 samples"
    );
    let negative_control = match env::var("HEDDLE_HOSTED_CLOSE_NEGATIVE_CONTROL").as_deref() {
        Ok("latency") => true,
        Ok(value) => panic!("unknown HEDDLE_HOSTED_CLOSE_NEGATIVE_CONTROL `{value}`"),
        Err(_) => false,
    };
    let server = Endpoint::builder(presets::Minimal)
        .alpns(vec![api::HOSTED_ALPN_V1.to_vec()])
        .relay_mode(RelayMode::Disabled)
        .bind_addr((Ipv4Addr::LOCALHOST, 0))
        .unwrap()
        .bind()
        .await
        .unwrap();
    let descriptor = verified_descriptor(
        server.id(),
        vec![
            "https://usw1-1.relay.n0.iroh.link.".to_string(),
            "https://aps1-1.relay.n0.iroh.link.".to_string(),
            "https://use1-1.relay.n0.iroh.link.".to_string(),
            "https://euc1-1.relay.n0.iroh.link.".to_string(),
        ],
        server.addr().ip_addrs().map(ToString::to_string).collect(),
    );
    let server_task = tokio::spawn(async move {
        for _ in 0..sample_count {
            let connection = server
                .accept()
                .await
                .expect("incoming connection")
                .await
                .unwrap();
            connection.closed().await;
        }
        server.close().await;
    });

    let mut close_ms = Vec::with_capacity(sample_count);
    for _ in 0..sample_count {
        let connection =
            HostedConnection::connect_verified(&descriptor, &cli_shared::ClientConfig::default())
                .await
                .unwrap();
        let endpoint_observer = connection.endpoint.clone();
        let close_started = Instant::now();
        if negative_control {
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
        connection.close().await;
        close_ms.push(close_started.elapsed().as_secs_f64() * 1_000.0);
        assert!(
            endpoint_observer.is_closed(),
            "successful hosted teardown must close the endpoint before drop"
        );
        drop(connection);
        drop(endpoint_observer);
    }
    server_task.await.unwrap();

    close_ms.sort_by(f64::total_cmp);
    let middle = close_ms.len() / 2;
    let median = if close_ms.len().is_multiple_of(2) {
        (close_ms[middle - 1] + close_ms[middle]) / 2.0
    } else {
        close_ms[middle]
    };
    let p95 = percentile_ms(&close_ms, 95);
    let min = close_ms[0];
    let max = close_ms[close_ms.len() - 1];
    let budget_ms = HOSTED_ENDPOINT_CLOSE_P95_BUDGET.as_secs_f64() * 1_000.0;
    println!(
        "HOSTED_CLOSE samples={sample_count} median_ms={median:.3} p95_ms={p95:.3} min_ms={min:.3} max_ms={max:.3} budget_p95_ms={budget_ms:.3} negative_control={negative_control}"
    );
    assert!(
        p95 <= budget_ms,
        "HOSTED CLOSE GATE RED: p95 {p95:.3} ms > {budget_ms:.3} ms budget"
    );
    println!("HOSTED_CLOSE_GATES green");
}

fn percentile_ms(sorted_values: &[f64], percentile: usize) -> f64 {
    let rank = (sorted_values.len() * percentile).div_ceil(100);
    sorted_values[rank.saturating_sub(1)]
}

#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn reachable_direct_address_keeps_the_claim_relay_online() {
    use iroh_relay::server::{RelayConfig as RelayServerConfig, Server, ServerConfig};

    let _env_guard = cli_shared::credentials::lock_test_env();
    let _home = HeddleHomeEnvGuard::isolated();
    let mut relay_config = ServerConfig::default();
    relay_config.relay = Some(RelayServerConfig::new((Ipv4Addr::LOCALHOST, 0)));
    let relay = Server::spawn(relay_config).await.unwrap();
    let relay_url: iroh::RelayUrl = format!("http://{}", relay.http_addr().unwrap())
        .parse()
        .unwrap();
    let server = Endpoint::builder(presets::Minimal)
        .alpns(vec![api::HOSTED_ALPN_V1.to_vec()])
        .relay_mode(RelayMode::Disabled)
        .bind_addr((Ipv4Addr::LOCALHOST, 0))
        .unwrap()
        .bind()
        .await
        .unwrap();
    let descriptor = verified_descriptor(
        server.id(),
        vec![relay_url.to_string()],
        server.addr().ip_addrs().map(ToString::to_string).collect(),
    );
    let server_task = tokio::spawn(async move {
        let connection = server
            .accept()
            .await
            .expect("incoming connection")
            .await
            .unwrap();
        connection.closed().await;
        server.close().await;
    });

    let connection =
        HostedConnection::connect_verified(&descriptor, &cli_shared::ClientConfig::default())
            .await
            .unwrap();
    tokio::time::timeout(Duration::from_secs(5), connection.endpoint.online())
        .await
        .expect("claim listener should register with the signed relay");
    assert!(
        !connection.endpoint.home_relay_status().get().is_empty(),
        "a direct hosted path must keep the inbound claim relay initialized"
    );
    connection.close().await;
    server_task.await.unwrap();
    drop(relay);
}

#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn direct_only_descriptor_uses_the_normal_connection_path() {
    let _env_guard = cli_shared::credentials::lock_test_env();
    let _home = HeddleHomeEnvGuard::isolated();
    let server = Endpoint::builder(presets::Minimal)
        .alpns(vec![api::HOSTED_ALPN_V1.to_vec()])
        .relay_mode(RelayMode::Disabled)
        .bind_addr((Ipv4Addr::LOCALHOST, 0))
        .unwrap()
        .bind()
        .await
        .unwrap();
    let descriptor = verified_descriptor(
        server.id(),
        Vec::new(),
        server.addr().ip_addrs().map(ToString::to_string).collect(),
    );
    let server_task = tokio::spawn(async move {
        let connection = server
            .accept()
            .await
            .expect("incoming direct-only connection")
            .await
            .unwrap();
        connection.closed().await;
        server.close().await;
    });

    let connection =
        HostedConnection::connect_verified(&descriptor, &cli_shared::ClientConfig::default())
            .await
            .unwrap();
    connection.close().await;
    server_task.await.unwrap();
}

#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn unreachable_direct_address_falls_back_to_signed_relay() {
    let _env_guard = cli_shared::credentials::lock_test_env();
    let _home = HeddleHomeEnvGuard::isolated();
    use iroh_relay::server::{RelayConfig as RelayServerConfig, Server, ServerConfig};

    let mut relay_config = ServerConfig::default();
    relay_config.relay = Some(RelayServerConfig::new((Ipv4Addr::LOCALHOST, 0)));
    let relay = Server::spawn(relay_config).await.unwrap();
    let relay_url: iroh::RelayUrl = format!("http://{}", relay.http_addr().unwrap())
        .parse()
        .unwrap();
    let server = Endpoint::builder(presets::Minimal)
        .alpns(vec![api::HOSTED_ALPN_V1.to_vec()])
        .relay_mode(RelayMode::custom([relay_url.clone()]))
        .bind_addr((Ipv4Addr::LOCALHOST, 0))
        .unwrap()
        .bind()
        .await
        .unwrap();
    tokio::time::timeout(Duration::from_secs(5), server.online())
        .await
        .expect("server should register with the relay");
    let descriptor = verified_descriptor(
        server.id(),
        vec![relay_url.to_string()],
        vec!["127.0.0.1:9".to_string()],
    );
    let server_task = tokio::spawn(async move {
        let connection = server
            .accept()
            .await
            .expect("incoming relay connection")
            .await
            .unwrap();
        connection.closed().await;
        server.close().await;
    });

    let connection = tokio::time::timeout(
        Duration::from_secs(5),
        HostedConnection::connect_verified(&descriptor, &cli_shared::ClientConfig::default()),
    )
    .await
    .expect("relay fallback should connect")
    .unwrap();
    tokio::time::timeout(Duration::from_secs(5), connection.endpoint.online())
        .await
        .expect("client should register with the signed relay");
    assert!(
        !connection.endpoint.home_relay_status().get().is_empty(),
        "relay fallback must initialize the signed relay transport"
    );
    connection.close().await;
    server_task.await.unwrap();
    drop(relay);
}

#[tokio::test]
#[allow(clippy::await_holding_lock)]
async fn hosted_connection_uses_persisted_id_and_accepts_claim_alpn() {
    let _env_guard = cli_shared::credentials::lock_test_env();
    let _home = HeddleHomeEnvGuard::isolated();
    let server = Endpoint::builder(presets::Minimal)
        .alpns(vec![api::HOSTED_ALPN_V1.to_vec()])
        .relay_mode(RelayMode::Disabled)
        .bind_addr((Ipv4Addr::LOCALHOST, 0))
        .unwrap()
        .bind()
        .await
        .unwrap();
    let descriptor = verified_descriptor(
        server.id(),
        Vec::new(),
        server.addr().ip_addrs().map(ToString::to_string).collect(),
    );
    let server_task = tokio::spawn(async move {
        let connection = server
            .accept()
            .await
            .expect("incoming hosted connection")
            .await
            .unwrap();
        connection.closed().await;
        server.close().await;
    });

    let connection =
        HostedConnection::connect_verified(&descriptor, &cli_shared::ClientConfig::default())
            .await
            .unwrap();
    let persisted = crate::hosted_runtime::agent_node_identity::load_or_create()
        .expect("persisted agent node identity");
    assert_eq!(connection.endpoint_id(), persisted.node_id());

    let claim_client = Endpoint::builder(presets::Minimal)
        .relay_mode(RelayMode::Disabled)
        .bind_addr((Ipv4Addr::LOCALHOST, 0))
        .unwrap()
        .bind()
        .await
        .unwrap();
    let claim_connection = claim_client
        .connect(connection.endpoint.addr(), CLAIM_ALPN_V1)
        .await
        .expect("claim ALPN connection");
    let (mut send, mut recv) = claim_connection.open_bi().await.unwrap();
    let frame = encode_request_frame(CLAIM_RESOLVE_METHOD, &CallContext::default(), b"resolve")
        .expect("claim request frame");
    send.write_all(&frame).await.unwrap();
    send.finish().unwrap();
    let response = recv.read_to_end(64 * 1024).await.unwrap();
    let ResponseFrame::Failure(failure) = decode_response_frame(&response).unwrap() else {
        panic!("missing Biscuit authentication must be refused");
    };
    assert_eq!(failure.code, CallFailureCode::Unauthenticated as i32);

    claim_client.close().await;
    connection.close().await;
    server_task.await.unwrap();
}