foundation_deployment_docker 0.1.3

Docker Engine API v1.53 client over DynNetClient + valtron (bollard-free)
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
//! BuildKit build-context session — serves FileSync back to buildkitd.
//!
//! WHY: A `dockerfile.v0` Solve needs the Dockerfile + build context, which
//! buildkitd pulls from the *client* over a callback gRPC channel (the
//! `Control/Session` bidi stream). buildkitd multiplexes an HTTP/2 connection
//! over that stream and calls the client's `FileSync/DiffCopy`.
//!
//! WHAT: [`SessionServer`] serves the generated FileSync service (backed by a
//! local directory) on a loopback HTTP/2 socket, then bridges that socket to the
//! `Control/Session` bidi stream — so buildkitd's session traffic reaches our
//! own `foundation_connectrpc` server. No bespoke transport: the server is the
//! ordinary `grpc_echo` serving path; only a byte pump sits between it and the
//! session stream.
//!
//! HOW: `SessionServer::start` (1) serves a `Router` with `register_file_sync`
//! on `127.0.0.1:0`, (2) opens `Control/Session` with the required
//! `x-docker-expose-session-*` headers, (3) dials the loopback server and pumps
//! bytes both ways between that socket and the session bidi. Callers then run a
//! Solve carrying the returned session id.

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread::JoinHandle;

use foundation_connectrpc::{
    Client, ClientOptions, ConnectRpcServeH2, Ctx, H2Transport, ProcedureCodecs, Router, Transport,
};
use foundation_core::synca::OnSignal;
use foundation_core::valtron;
use foundation_http::native::serve::H2Serve;
use foundation_http::native::server::HttpServer;
use foundation_http::shared::app::{HttpApp, ServerApp};
use tracing::error;

use crate::buildkit::generated::fsutil::types::packet::PacketType;
use crate::buildkit::generated::fsutil::types::{Packet, Stat};
use crate::buildkit::generated::grpc::health::v1::health_check_response::ServingStatus;
use crate::buildkit::generated::grpc::health::v1::{HealthCheckRequest, HealthCheckResponse};
use crate::buildkit::generated::moby::filesync::v1::BytesMessage as FsBytesMessage;
use crate::buildkit::generated::moby::filesync::v1::{CredentialsRequest, CredentialsResponse};
use crate::buildkit::generated::moby::buildkit::secrets::v1::{
    GetSecretRequest, GetSecretResponse,
};
use crate::buildkit::generated::moby::sshforward::v1::BytesMessage as SshBytesMessage;
use crate::buildkit::generated::moby::sshforward::v1::{CheckAgentRequest, CheckAgentResponse};
use crate::buildkit::services::auth::{self, register_auth, Auth};
use crate::buildkit::services::ssh::{self, register_ssh, SSH as Ssh};
use crate::buildkit::services::secrets::{self, register_secrets, Secrets};
use crate::buildkit::services::filesend::{self, register_file_send, FileSend};
use crate::buildkit::services::filesync::{self, register_file_sync, FileSync};
use crate::buildkit::services::health::{self, register_health, Health};
use crate::buildkit::types::BytesMessage;

use foundation_connectrpc::{ConnectError, ConnectResult, Request, Response};

type BoxErr = Box<dyn std::error::Error + Send + Sync>;

// ── FileSync implementation — serves a local directory ──────────────────────

/// A [`FileSync`] backed by a local build-context directory. Every `DiffCopy`
/// streams the same directory (matching the common `--local context=. --local
/// dockerfile=.` case).
#[derive(Clone)]
pub struct DirFileSync {
    root: Arc<PathBuf>,
}

/// One walked entry: its fsutil [`Stat`] and, for regular files, the bytes to
/// stream on request.
struct Entry {
    stat: Stat,
    content: Option<Vec<u8>>,
}

/// Go `os.FileMode` type bit for directories (`1 << 31`).
const GO_MODE_DIR: u32 = 0x8000_0000;

impl DirFileSync {
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: Arc::new(root.into()) }
    }

    /// Walk the context directory into a deterministic (lexical) list of entries,
    /// each with an fsutil `Stat`; regular files also carry their bytes.
    fn walk(&self) -> Vec<Entry> {
        let mut out = Vec::new();
        walk_dir(&self.root, &self.root, &mut out);
        out.sort_by(|a, b| a.stat.path.cmp(&b.stat.path));
        out
    }
}

fn walk_dir(root: &Path, dir: &Path, out: &mut Vec<Entry>) {
    let Ok(read) = std::fs::read_dir(dir) else { return };
    for entry in read.flatten() {
        let path = entry.path();
        let Ok(meta) = entry.metadata() else { continue };
        // fsutil paths are slash-separated and relative to the context root.
        let rel = match path.strip_prefix(root) {
            Ok(r) => r.to_string_lossy().replace('\\', "/"),
            Err(_) => continue,
        };
        if meta.is_dir() {
            out.push(Entry {
                stat: Stat { path: rel, mode: GO_MODE_DIR | 0o755, ..Default::default() },
                content: None,
            });
            walk_dir(root, &path, out);
        } else if meta.is_file() {
            let content = std::fs::read(&path).unwrap_or_default();
            out.push(Entry {
                stat: Stat {
                    path: rel,
                    mode: 0o644,
                    size: content.len() as i64,
                    ..Default::default()
                },
                content: Some(content),
            });
        }
    }
}

/// State machine driving the fsutil sender side of `DiffCopy` as an output
/// stream that also consumes the incoming request stream.
enum Phase {
    /// Emitting stat packet `i` of the walk.
    Stats(usize),
    /// Emitting the terminating empty-stat packet.
    EndStats,
    /// Serving `PACKET_REQ` → `PACKET_DATA` until the peer sends `PACKET_FIN`.
    Serving,
    Done,
}

struct DiffState<R> {
    entries: Vec<Entry>,
    phase: Phase,
    /// The incoming request stream (`PACKET_REQ` / `PACKET_FIN` from buildkitd).
    reqs: R,
    /// Data/EOF packets queued for the file currently being served.
    pending: std::collections::VecDeque<Packet>,
}

fn stat_packet(stat: Stat) -> Packet {
    Packet {
        r#type: PacketType::PACKET_STAT.into(),
        stat: buffa::MessageField::some(stat),
        ..Default::default()
    }
}

fn data_packet(id: u32, data: Vec<u8>) -> Packet {
    Packet { r#type: PacketType::PACKET_DATA.into(), ID: id, data, ..Default::default() }
}

impl DirFileSync {
    /// The shared `DiffCopy` driver used for both `diff_copy` and `tar_stream`.
    fn diff_copy_stream(
        &self,
        requests: impl futures::Stream<Item = foundation_connectrpc::ConnectResult<Packet>> + Send + 'static,
    ) -> std::pin::Pin<Box<dyn futures::Stream<Item = foundation_connectrpc::ConnectResult<Packet>> + Send>>
    {
        use futures::StreamExt;

        let entries = self.walk();
        let state = DiffState {
            entries,
            phase: Phase::Stats(0),
            reqs: Box::pin(requests),
            pending: std::collections::VecDeque::new(),
        };

        let stream = futures::stream::unfold(state, |mut st| async move {
            loop {
                if let Some(pkt) = st.pending.pop_front() {
                    return Some((Ok(pkt), st));
                }
                match st.phase {
                    Phase::Stats(i) => {
                        if i < st.entries.len() {
                            let pkt = stat_packet(st.entries[i].stat.clone());
                            st.phase = Phase::Stats(i + 1);
                            return Some((Ok(pkt), st));
                        }
                        st.phase = Phase::EndStats;
                    }
                    Phase::EndStats => {
                        // End-of-walk terminator: a PACKET_STAT with NO stat
                        // message (fsutil checks `p.Stat == nil`). Sending a
                        // present-but-default Stat instead makes fsutil treat
                        // it as a real entry and fail with `unclean path ""`.
                        let pkt = Packet {
                            r#type: PacketType::PACKET_STAT.into(),
                            ..Default::default()
                        };
                        st.phase = Phase::Serving;
                        return Some((Ok(pkt), st));
                    }
                    Phase::Serving => {
                        match st.reqs.next().await {
                            Some(Ok(pkt)) => {
                                let kind = pkt.r#type.to_i32();
                                if kind == PacketType::PACKET_REQ as i32 {
                                    let id = pkt.ID;
                                    if let Some(entry) = st.entries.get(id as usize) {
                                        if let Some(content) = &entry.content {
                                            for chunk in content.chunks(32 * 1024) {
                                                st.pending.push_back(data_packet(id, chunk.to_vec()));
                                            }
                                        }
                                    }
                                    // Empty data packet = EOF for this id.
                                    st.pending.push_back(data_packet(id, Vec::new()));
                                } else if kind == PacketType::PACKET_FIN as i32 {
                                    st.pending.push_back(Packet {
                                        r#type: PacketType::PACKET_FIN.into(),
                                        ..Default::default()
                                    });
                                    st.phase = Phase::Done;
                                }
                                // continue the loop to flush pending
                            }
                            _ => {
                                st.phase = Phase::Done;
                            }
                        }
                    }
                    Phase::Done => return None,
                }
            }
        });

        stream.boxed()
    }
}

impl FileSync for DirFileSync {
    fn diff_copy(
        &self,
        _ctx: Ctx,
        requests: impl futures::Stream<Item = foundation_connectrpc::ConnectResult<Packet>> + Send + 'static,
    ) -> impl core::future::Future<
        Output = foundation_connectrpc::ConnectResult<
            std::pin::Pin<Box<dyn futures::Stream<Item = foundation_connectrpc::ConnectResult<Packet>> + Send>>,
        >,
    > + Send {
        let this = self.clone();
        async move { Ok(this.diff_copy_stream(requests)) }
    }

    fn tar_stream(
        &self,
        _ctx: Ctx,
        requests: impl futures::Stream<Item = foundation_connectrpc::ConnectResult<Packet>> + Send + 'static,
    ) -> impl core::future::Future<
        Output = foundation_connectrpc::ConnectResult<
            std::pin::Pin<Box<dyn futures::Stream<Item = foundation_connectrpc::ConnectResult<Packet>> + Send>>,
        >,
    > + Send {
        let this = self.clone();
        async move { Ok(this.diff_copy_stream(requests)) }
    }
}

// ── Health service: always SERVING — satisfies buildkit's monitorHealth ──────

/// Always returns `SERVING` — satisfies buildkit's `monitorHealth` so the
/// session connection stays alive past the HTTP/2 handshake. Without this,
/// buildkit tears down the session ~20ms after connecting.
pub struct HealthService;

impl Health for HealthService {
    async fn check(
        &self,
        _ctx: Ctx,
        _request: Request<HealthCheckRequest>,
    ) -> ConnectResult<Response<HealthCheckResponse>> {
        Ok(Response::new(HealthCheckResponse {
            status: ServingStatus::SERVING.into(),
            ..Default::default()
        }))
    }
    // watch defaults to unimplemented — buildkit only calls Check.
}

// ── Auth: registry credentials for buildkitd's pulls/pushes ─────────────────

/// Registry credentials keyed by host (e.g. `registry-1.docker.io`), with
/// anonymous fallback for unknown hosts.
///
/// Implements the session's `moby.filesync.v1.Auth/Credentials` callback —
/// buildkitd asks the client for credentials before touching a registry. An
/// empty `CredentialsResponse` means "anonymous", which is what public pulls
/// need. `FetchToken`/`GetTokenAuthority`/`VerifyTokenAuthority` keep their
/// generated `unimplemented` defaults: buildkitd's resolver falls back to
/// `Credentials` + its own token flow when the client doesn't do OAuth
/// token exchange itself (the docker-CLI behavior predating FetchToken).
#[derive(Default)]
pub struct StaticRegistryAuth {
    creds: std::collections::HashMap<String, (String, String)>,
    /// How many times buildkitd asked for credentials (any host).
    hits: std::sync::atomic::AtomicU64,
}

impl StaticRegistryAuth {
    /// Anonymous-only provider (public registries).
    #[must_use]
    pub fn anonymous() -> Self {
        Self::default()
    }

    /// Add `username`/`secret` for `host` (e.g. `registry-1.docker.io`).
    #[must_use]
    pub fn with_credentials(
        mut self,
        host: impl Into<String>,
        username: impl Into<String>,
        secret: impl Into<String>,
    ) -> Self {
        self.creds.insert(host.into(), (username.into(), secret.into()));
        self
    }

    /// How many `Credentials` calls buildkitd has made on this provider.
    #[must_use]
    pub fn credential_requests(&self) -> u64 {
        self.hits.load(std::sync::atomic::Ordering::Relaxed)
    }
}

impl Auth for StaticRegistryAuth {
    fn credentials(
        &self,
        _ctx: Ctx,
        request: Request<CredentialsRequest>,
    ) -> impl core::future::Future<Output = ConnectResult<Response<CredentialsResponse>>> + Send
    {
        self.hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let response = match self.creds.get(&request.msg.Host) {
            Some((username, secret)) => CredentialsResponse {
                Username: username.clone(),
                Secret: secret.clone(),
                ..Default::default()
            },
            // Unknown host → anonymous.
            None => CredentialsResponse::default(),
        };
        async move { Ok(Response::new(response)) }
    }
    // fetch_token / get_token_authority / verify_token_authority keep the
    // generated `unimplemented` defaults — see the type docs.
}

// ── Secrets: build secrets served over the session ──────────────────────────

/// Build secrets keyed by id, served over the session's
/// `moby.buildkit.secrets.v1.Secrets/GetSecret` callback — what a
/// `RUN --mount=type=secret,id=…` instruction resolves against.
///
/// Unknown ids return `NotFound`, which buildkitd reports as the standard
/// "secret … not found" build error (same behavior as buildx without a
/// matching `--secret`).
#[derive(Default)]
pub struct StaticSecrets {
    secrets: std::collections::HashMap<String, Vec<u8>>,
}

impl StaticSecrets {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add secret bytes under `id` (the `id=` in `--mount=type=secret,id=…`).
    #[must_use]
    pub fn with_secret(mut self, id: impl Into<String>, data: impl Into<Vec<u8>>) -> Self {
        self.secrets.insert(id.into(), data.into());
        self
    }
}

impl Secrets for StaticSecrets {
    fn get_secret(
        &self,
        _ctx: Ctx,
        request: Request<GetSecretRequest>,
    ) -> impl core::future::Future<Output = ConnectResult<Response<GetSecretResponse>>> + Send
    {
        let result = match self.secrets.get(&request.msg.ID) {
            Some(data) => Ok(Response::new(GetSecretResponse {
                data: data.clone(),
                ..Default::default()
            })),
            None => Err(ConnectError::not_found(format!(
                "secret {:?} not registered on this session",
                request.msg.ID
            ))
            .into()),
        };
        async move { result }
    }
}

// ── SSH: agent forwarding over the session ───────────────────────────────────

/// Forwards `RUN --mount=type=ssh` traffic to a local SSH agent socket
/// (`$SSH_AUTH_SOCK`-style path).
///
/// Implements the session's `moby.sshforward.v1.SSH` callbacks:
/// - `CheckAgent` — succeeds when the agent socket accepts a connection.
/// - `ForwardAgent` — a byte pump between the gRPC bidi (`BytesMessage`
///   chunks from the build container's ssh client) and the local agent
///   socket, same thread↔pipe bridge shape as the session tunnel itself.
pub struct SshAgentProxy {
    socket: Arc<PathBuf>,
}

impl SshAgentProxy {
    /// Proxy to the agent at `socket` (typically `std::env::var("SSH_AUTH_SOCK")`).
    #[must_use]
    pub fn new(socket: impl Into<PathBuf>) -> Self {
        Self { socket: Arc::new(socket.into()) }
    }
}

impl Ssh for SshAgentProxy {
    fn check_agent(
        &self,
        _ctx: Ctx,
        _request: Request<CheckAgentRequest>,
    ) -> impl core::future::Future<Output = ConnectResult<Response<CheckAgentResponse>>> + Send
    {
        let result = match std::os::unix::net::UnixStream::connect(self.socket.as_ref()) {
            Ok(_) => Ok(Response::new(CheckAgentResponse::default())),
            Err(e) => Err(ConnectError::failed_precondition(format!(
                "ssh agent socket {:?} not reachable: {e}",
                self.socket
            ))
            .into()),
        };
        async move { result }
    }

    fn forward_agent(
        &self,
        _ctx: Ctx,
        requests: impl futures::Stream<Item = ConnectResult<SshBytesMessage>> + Send + 'static,
    ) -> impl core::future::Future<
        Output = ConnectResult<
            std::pin::Pin<Box<dyn futures::Stream<Item = ConnectResult<SshBytesMessage>> + Send>>,
        >,
    > + Send {
        let socket = self.socket.clone();
        async move {
            use futures::StreamExt;

            let agent = std::os::unix::net::UnixStream::connect(socket.as_ref())
                .map_err(|e| ConnectError::failed_precondition(format!("dial ssh agent: {e}")))?;
            let mut agent_read = agent
                .try_clone()
                .map_err(|e| ConnectError::internal(format!("clone agent socket: {e}")))?;
            let mut agent_write = agent;

            // gRPC → agent: drain the request stream on the pool; blocking
            // socket writes stay on a dedicated OS thread.
            let (to_agent_tx, to_agent_rx) = std::sync::mpsc::channel::<Vec<u8>>();
            let drain = valtron::from_future(Box::pin(async move {
                let mut requests = Box::pin(requests);
                while let Some(item) = requests.next().await {
                    match item {
                        Ok(msg) => {
                            if to_agent_tx.send(msg.data).is_err() {
                                break;
                            }
                        }
                        Err(e) => {
                            tracing::warn!(err = %e, "ssh forward: request stream error");
                            break;
                        }
                    }
                }
                // Sender drop closes the channel; the write thread half-closes
                // the agent socket so the agent sees EOF.
            }));
            valtron::send(drain)
                .map_err(|e| ConnectError::internal(format!("spawn ssh drain task: {e}")))?;
            std::thread::spawn(move || {
                while let Ok(data) = to_agent_rx.recv() {
                    if agent_write.write_all(&data).is_err() || agent_write.flush().is_err() {
                        break;
                    }
                }
                let _ = agent_write.shutdown(std::net::Shutdown::Write);
            });

            // agent → gRPC: blocking reads on an OS thread feed a valtron pipe;
            // the response stream drains it with readiness-parked awaits.
            let (from_agent_tx, from_agent_rx) = valtron::Pipe::<Vec<u8>>::new();
            std::thread::spawn(move || {
                let mut buf = vec![0u8; 32 * 1024];
                loop {
                    match agent_read.read(&mut buf) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            if from_agent_tx.try_send(buf[..n].to_vec()).is_err() {
                                // Bounded pipe full or receiver gone. Agent
                                // replies are tiny (key lists/signatures), so
                                // full means the consumer hung up.
                                break;
                            }
                        }
                    }
                }
            });

            let out = futures::stream::unfold(from_agent_rx, |rx| async move {
                rx.receive()
                    .await
                    .map(|data| (Ok(SshBytesMessage { data, ..Default::default() }), rx))
            });
            let boxed: std::pin::Pin<
                Box<dyn futures::Stream<Item = ConnectResult<SshBytesMessage>> + Send>,
            > = Box::pin(out);
            Ok(boxed)
        }
    }
}

// ── FileSend sink: receive exported artifacts from buildkitd ─────────────────

/// A [`FileSend`] sink that writes exported build artifacts to a file.
///
/// buildkitd's `oci` / `docker` / `tar` exporters call
/// `moby.filesync.v1.FileSend/DiffCopy` on the session and stream the archive
/// as `BytesMessage` chunks; the receiver writes each chunk and acknowledges
/// by ending its (empty) response stream once the input reaches EOF — the
/// same shape as buildkit's own `writeTargetFile`.
#[derive(Clone)]
pub struct FileExportSink {
    path: Arc<PathBuf>,
}

impl FileExportSink {
    #[must_use]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: Arc::new(path.into()) }
    }
}

impl FileSend for FileExportSink {
    fn diff_copy(
        &self,
        _ctx: Ctx,
        requests: impl futures::Stream<Item = ConnectResult<FsBytesMessage>> + Send + 'static,
    ) -> impl core::future::Future<
        Output = ConnectResult<
            std::pin::Pin<Box<dyn futures::Stream<Item = ConnectResult<FsBytesMessage>> + Send>>,
        >,
    > + Send {
        let path = self.path.clone();
        async move {
            use futures::StreamExt;

            let file = std::fs::File::create(path.as_ref())
                .map_err(|e| ConnectError::internal(format!("create export file: {e}")))?;

            // Drive the input inside the response stream so writing is pull-based:
            // each poll of our (never-yielding) output consumes input chunks. The
            // stream ends — sending clean trailers — when the input reaches EOF.
            let state = (Box::pin(requests), file);
            let out = futures::stream::unfold(state, |(mut reqs, mut file)| async move {
                use std::io::Write;
                loop {
                    match reqs.next().await {
                        Some(Ok(msg)) => {
                            if let Err(e) = file.write_all(&msg.data) {
                                error!(err = %e, "filesend: export write failed");
                                return Some((
                                    Err(ConnectError::internal(format!("export write: {e}"))
                                        .into()),
                                    (reqs, file),
                                ));
                            }
                        }
                        Some(Err(e)) => {
                            error!(err = %e, "filesend: request stream error");
                            return None;
                        }
                        None => {
                            if let Err(e) = file.flush() {
                                error!(err = %e, "filesend: export flush failed");
                            }
                            return None;
                        }
                    }
                }
            });
            let boxed: std::pin::Pin<
                Box<dyn futures::Stream<Item = ConnectResult<FsBytesMessage>> + Send>,
            > = Box::pin(out);
            Ok(boxed)
        }
    }
}

// ── Session server: serve FileSync on loopback + pump to the Session bidi ───

/// A running build-context session. Holds the session id (to pass in
/// `SolveRequest.Session`) and the resources kept alive for the build's
/// duration; dropping it tears the session down.
pub struct SessionServer {
    /// The BuildKit session id — set `SolveRequest.Session` to this.
    pub id: String,
    shutdown: Arc<OnSignal>,
    _server: Option<JoinHandle<()>>,
    _pump_down: Option<JoinHandle<()>>,
    _pump_up: Option<JoinHandle<()>>,
    _pump_send: Option<JoinHandle<()>>,
    /// Temp dir owned by an inline-dockerfile session; removed on drop.
    owned_tmp: Option<PathBuf>,
}

/// Configures the sidecar services a [`SessionServer`] exposes to buildkitd.
///
/// The context directory (FileSync) and Health are always served; everything
/// else is opt-in. Finish with [`start`](Self::start) (fresh `H2Transport`
/// per the control authority) or [`start_with`](Self::start_with) (caller-
/// supplied transport — e.g. to share `BuildKitClient`'s Unix-socket or
/// pooled transport).
pub struct SessionBuilder {
    context_dir: PathBuf,
    export_file: Option<PathBuf>,
    auth: Option<Arc<StaticRegistryAuth>>,
    secrets: Option<Arc<StaticSecrets>>,
    ssh: Option<Arc<SshAgentProxy>>,
    /// A session-owned temp dir (inline dockerfile) removed on session drop.
    owned_tmp: Option<PathBuf>,
}

impl SessionBuilder {
    /// Receive exported build artifacts into `path`. Registers the
    /// `FileSend/DiffCopy` sidecar service — required for the `oci`, `docker`
    /// and `tar` exporters, which stream the archive back over the session.
    #[must_use]
    pub fn export_to_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.export_file = Some(path.into());
        self
    }

    /// Serve build secrets over the session (`Secrets/GetSecret`) — what
    /// `RUN --mount=type=secret,id=…` instructions resolve against.
    #[must_use]
    pub fn secrets(mut self, secrets: Arc<StaticSecrets>) -> Self {
        self.secrets = Some(secrets);
        self
    }

    /// Forward `RUN --mount=type=ssh` traffic to a local SSH agent socket
    /// over the session (`SSH/CheckAgent` + `SSH/ForwardAgent`).
    #[must_use]
    pub fn ssh_agent(mut self, proxy: Arc<SshAgentProxy>) -> Self {
        self.ssh = Some(proxy);
        self
    }

    /// Serve registry credentials over the session (`Auth/Credentials`) —
    /// buildkitd asks the client before pulling from / pushing to a registry.
    /// Pass a shared handle if you want to inspect
    /// [`StaticRegistryAuth::credential_requests`] afterwards.
    #[must_use]
    pub fn registry_auth(mut self, auth: Arc<StaticRegistryAuth>) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Start the session against `control_authority` on a fresh
    /// [`H2Transport`] (one TCP connection per call).
    ///
    /// # Errors
    ///
    /// Returns an error if the loopback server cannot bind, the Session
    /// stream cannot be opened, or the loopback dial fails.
    pub async fn start(self, control_authority: &str) -> Result<SessionServer, BoxErr> {
        let transport: Arc<dyn Transport> = Arc::new(H2Transport::new());
        self.start_with(transport, control_authority).await
    }

    /// Start the session on a **caller-supplied** [`Transport`] — e.g.
    /// [`BuildKitClient::transport`], so the Session bidi dials the same
    /// Unix socket / pooled connection as the control-plane RPCs.
    ///
    /// # Errors
    ///
    /// Returns an error if the loopback server cannot bind, the Session
    /// stream cannot be opened, or the loopback dial fails.
    pub async fn start_with(
        self,
        control_transport: Arc<dyn Transport>,
        control_authority: &str,
    ) -> Result<SessionServer, BoxErr> {
        let id = new_session_id();

        // 1. Session gRPC server on a loopback h2c socket. Every registered
        //    method is routed AND advertised via a repeated
        //    `x-docker-expose-session-grpc-method` header — buildkitd only
        //    calls methods the session declares.
        let mut methods: Vec<&'static str> = Vec::new();
        let mut router = Router::new();
        register_file_sync(&mut router, Arc::new(DirFileSync::new(self.context_dir)));
        methods.push(filesync::procedure::DIFF_COPY);
        methods.push(filesync::procedure::TAR_STREAM);
        register_health(&mut router, Arc::new(HealthService));
        methods.push(health::procedure::CHECK);
        methods.push(health::procedure::WATCH);
        if let Some(path) = &self.export_file {
            register_file_send(&mut router, Arc::new(FileExportSink::new(path)));
            methods.push(filesend::procedure::DIFF_COPY);
        }
        if let Some(provider) = &self.auth {
            register_auth(&mut router, Arc::clone(provider));
            methods.push(auth::procedure::CREDENTIALS);
        }
        if let Some(provider) = &self.secrets {
            register_secrets(&mut router, Arc::clone(provider));
            methods.push(secrets::procedure::GET_SECRET);
        }
        if let Some(proxy) = &self.ssh {
            register_ssh(&mut router, Arc::clone(proxy));
            methods.push(ssh::procedure::CHECK_AGENT);
            methods.push(ssh::procedure::FORWARD_AGENT);
        }

        let rpc: Arc<dyn H2Serve> = Arc::new(ConnectRpcServeH2::new(router.into_handler()));
        let mut app = HttpApp::new_h2_serve();
        for method in &methods {
            app.route_any_h2(method, rpc.clone());
        }

        let listener = TcpListener::bind("127.0.0.1:0")?;
        let local_addr = listener.local_addr()?;
        let shutdown = Arc::new(OnSignal::new());

        let server_shutdown = shutdown.clone();
        let server = HttpServer::from_app(ServerApp::http2(app), &local_addr.to_string());
        let server_handle = std::thread::spawn(move || {
            server.serve_with_listener(&listener, &server_shutdown);
        });

        // 2. Open Control/Session with the required session metadata headers.
        let mut options = ClientOptions::new()
            .with_grpc()
            .with_header("x-docker-expose-session-uuid".to_string(), id.clone())
            .with_header("x-docker-expose-session-name".to_string(), "ewe");
        for method in &methods {
            options = options.with_header(
                "x-docker-expose-session-grpc-method".to_string(),
                *method,
            );
        }
        let session_client = Client::<BytesMessage, BytesMessage>::new(
            control_transport,
            &format!("http://{control_authority}/moby.buildkit.v1.Control/Session"),
            ProcedureCodecs::defaults(),
            options,
        )?;

        let mut bidi = session_client
            .bidi_stream(Ctx::background(), futures::stream::pending::<BytesMessage>())
            .await?;

        // Check the gRPC response headers — do we have grpc-status?
        match bidi.response_headers().await {
            Ok(h) => {
                let mut s = String::new();
                for (k, vs) in h.iter() { s.push_str(&format!("{k}={vs:?} ")); }
                tracing::debug!(headers = %s, "session bidi response headers");
            }
            Err(e) => tracing::warn!(err = %e, "session bidi response headers failed"),
        }
        // NOTE: never send anything on the bidi before the loopback server's
        // SETTINGS. RFC 7540 §3.5: the first frame the server sends MUST be
        // SETTINGS — grpc-go treats any other first frame (e.g. a PING) as a
        // connection error and tears the Level 2 transport down.
        let (mut sender, mut receiver) = bidi.split();
        // 3. Dial our own loopback server.
        let tcp = TcpStream::connect(local_addr)?;
        let mut tcp_read = tcp.try_clone()?;
        let mut tcp_write = tcp;

        // buildkitd → loopback: async receive → std channel → blocking write.
        let (down_tx, down_rx) = std::sync::mpsc::channel::<Vec<u8>>();
        let read_pool = valtron::from_future(Box::pin(async move {
            loop {
                match receiver.receive().await {
                    Ok(Some(msg)) => {
                        let tag = h2_frame_tag(&msg.data);
                        let hex: String = msg.data.iter()
                            .map(|b| format!("{b:02x}")).collect();
                        tracing::trace!(bytes = msg.data.len(), frame = tag, hex = %hex, "session: buildkitd -> loopback");
                        if let Err(e) = down_tx.send(msg.data) {
                            error!(err = %e, "[sess] down_tx send failed");
                            break;
                        }
                    }
                    Ok(None) => {
                        tracing::debug!("session bidi: buildkitd stream ended");
                        break;
                    }
                    Err(e) => {
                        error!(err = %e, "[sess] bk->me: receive error");
                        break;
                    }
                }
            }
        }));
        valtron::send(read_pool).map_err(|e| format!("spawn session receive task: {e}"))?;
        let write_thread = std::thread::spawn(move || {
            while let Ok(data) = down_rx.recv() {
                if let Err(e) = tcp_write.write_all(&data) {
                    error!(err = %e, "[sess] tcp_write failed");
                    break;
                }
                if let Err(e) = tcp_write.flush() {
                    error!(err = %e, "[sess] tcp_write flush failed");
                    break;
                }
            }
            if let Err(e) = tcp_write.shutdown(std::net::Shutdown::Both) {
                tracing::debug!(err = %e, "session loopback tcp shutdown");
            }
        });

        // loopback → buildkitd: blocking read → std::sync::mpsc → DEDICATED
        // OS thread that calls sender.send() via futures_lite::block_on. This
        // eliminates valtron pool-polling latency — the thread sleeps on recv()
        // and wakes instantly when data arrives, keeping the tunnel's added
        // round-trip latency to a minimum.
        let (up_tx, up_rx) = std::sync::mpsc::channel::<Vec<u8>>();
        let start = std::time::Instant::now();
        let read_thread = std::thread::spawn(move || {
            let mut buf = vec![0u8; 32 * 1024];
            loop {
                match tcp_read.read(&mut buf) {
                    Ok(0) => { tracing::debug!(elapsed = ?start.elapsed(), "session loopback closed"); break; }
                    Err(e) => { tracing::warn!(elapsed = ?start.elapsed(), err = %e, "session loopback read error"); break; }
                    Ok(n) => {
                        let tag = h2_frame_tag(&buf[..n]);
                        tracing::trace!(bytes = n, frame = tag, elapsed_ms = start.elapsed().as_secs_f64() * 1000.0, "session: loopback -> buildkitd (read)");
                        if up_tx.send(buf[..n].to_vec()).is_err() {
                            break;
                        }
                    }
                }
            }
        });
        // Dedicated thread: recv() blocks the OS thread, wakes instantly,
        // block_on drives the async send future to completion synchronously.
        let send_thread = std::thread::spawn(move || {
            // sender is moved in via `move` closure — it is now owned here.
            while let Ok(data) = up_rx.recv() {
                let tag = h2_frame_tag(&data);
                tracing::trace!(bytes = data.len(), frame = tag, "session: loopback -> buildkitd (send)");
                let msg = BytesMessage { data, ..Default::default() };
                if let Err(e) = futures_lite::future::block_on(sender.send(&msg)) {
                    error!(err = %e, "[sess] me->buildkit send failed");
                    break;
                }
            }
            tracing::debug!("session send pump done — closing sender");
            let _ = futures_lite::future::block_on(sender.close_request());
        });

        Ok(SessionServer {
            id,
            shutdown,
            _server: Some(server_handle),
            _pump_down: Some(write_thread),
            _pump_up: Some(read_thread),
            _pump_send: Some(send_thread),
            owned_tmp: self.owned_tmp,
        })
    }
}

impl SessionServer {
    /// Start configuring a session for `context_dir` — see [`SessionBuilder`]
    /// for the optional sidecar services (artifact export, …).
    pub fn builder(context_dir: impl Into<PathBuf>) -> SessionBuilder {
        SessionBuilder {
            context_dir: context_dir.into(),
            export_file: None,
            auth: None,
            secrets: None,
            ssh: None,
            owned_tmp: None,
        }
    }

    /// Configure a session that serves `dockerfile` **inline** — no file or
    /// context directory needed from the caller. The content is materialized
    /// as `Dockerfile` in a session-owned temp directory (buildkitd's
    /// `dockerfile.v0` frontend always pulls the Dockerfile through the
    /// session's FileSync `dockerfile` local; there is no request-attr path
    /// for it in plain buildkitd), and the directory is removed when the
    /// session drops.
    ///
    /// # Errors
    ///
    /// Returns an error if the temp directory or Dockerfile cannot be created.
    pub fn builder_inline(dockerfile: &str) -> std::io::Result<SessionBuilder> {
        let dir = std::env::temp_dir().join(format!(
            "ewe-bk-inline-{}-{}",
            std::process::id(),
            &new_session_id()[..8]
        ));
        std::fs::create_dir_all(&dir)?;
        std::fs::write(dir.join("Dockerfile"), dockerfile)?;
        Ok(SessionBuilder {
            context_dir: dir.clone(),
            export_file: None,
            auth: None,
            secrets: None,
            ssh: None,
            owned_tmp: Some(dir),
        })
    }

    /// Serve a FileSync session for `context_dir` and attach it to the
    /// Control/Session stream at `control_authority` on a fresh
    /// [`H2Transport`]. Shorthand for `builder(context_dir).start(..)`.
    ///
    /// # Errors
    ///
    /// Returns an error if the loopback server cannot bind, the Session
    /// stream cannot be opened, or the loopback dial fails.
    pub async fn start(
        control_authority: &str,
        context_dir: impl Into<PathBuf>,
    ) -> Result<Self, BoxErr> {
        Self::builder(context_dir).start(control_authority).await
    }

    /// Like [`start`](Self::start), but on a **caller-supplied**
    /// [`Transport`] (e.g. [`BuildKitClient::transport`] for Unix-socket or
    /// pooled connections). Shorthand for `builder(..).start_with(..)`.
    ///
    /// # Errors
    ///
    /// Returns an error if the loopback server cannot bind, the Session
    /// stream cannot be opened, or the loopback dial fails.
    pub async fn start_with(
        transport: Arc<dyn Transport>,
        control_authority: &str,
        context_dir: impl Into<PathBuf>,
    ) -> Result<Self, BoxErr> {
        Self::builder(context_dir).start_with(transport, control_authority).await
    }
}

impl Drop for SessionServer {
    fn drop(&mut self) {
        self.shutdown.turn_on();
        if let Some(dir) = self.owned_tmp.take() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}

/// A random BuildKit identifier (32 lowercase-hex chars, like buildx's
/// `identity.NewID()`). Used for session ids and build refs alike.
pub(crate) fn new_session_id() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
    let mut x = seed as u64 ^ 0x9E37_79B9_7F4A_7C15;
    let mut s = String::with_capacity(32);
    for _ in 0..4 {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        s.push_str(&format!("{x:016x}"));
    }
    s.truncate(32);
    s
}

/// Quick H2 frame type tag for debug hex dumps.
fn h2_frame_tag(data: &[u8]) -> &'static str {
    if data == b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" {
        return "[H2 PREFACE]";
    }
    if data.len() < 9 {
        return "[?short]";
    }
    let ty = data[3];
    let flags = data[4];
    match ty {
        0x00 => "[DATA]",
        0x01 => "[HEADERS]",
        0x04 if flags & 0x01 != 0 => "[SETTINGS ACK]",
        0x04 => "[SETTINGS]",
        0x07 => "[GOAWAY]",
        0x08 => "[WINDOW_UPDATE]",
        _ => "[?]",
    }
}