forked from coast-guard/coasts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rs
More file actions
1744 lines (1592 loc) · 61.9 KB
/
Copy pathserver.rs
File metadata and controls
1744 lines (1592 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
/// Unix domain socket server for the coast daemon.
///
/// Accepts connections on `~/.coast/coastd.sock`, reads JSON requests,
/// dispatches them to handlers, and writes JSON responses back.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
use coast_core::error::{CoastError, Result};
use coast_core::protocol::{
self, BuildProgressEvent, CoastEvent, ErrorResponse, LogsResponse, Request, Response,
};
use crate::analytics::{self, AnalyticsClient, CommandSource};
use crate::api::streaming::spawn_agent_shell_if_configured;
use crate::handlers;
use crate::state::StateDb;
use coast_docker::host::{docker_endpoint_source_label, DockerEndpoint};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateOperationKind {
Build,
RerunExtractors,
Run,
Assign,
Unassign,
Start,
Stop,
Rm,
Checkout,
Rebuild,
RestartServices,
RmBuild,
ArchiveProject,
UnarchiveProject,
SharedStart,
SharedStop,
SharedRestart,
SharedRm,
SecretSet,
ServiceStart,
ServiceStop,
ServiceRestart,
ServiceRm,
BareServiceStart,
BareServiceStop,
BareServiceRestart,
ClearLogs,
UploadToContainer,
UploadToHost,
}
impl UpdateOperationKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::Build => "build",
Self::RerunExtractors => "rerun_extractors",
Self::Run => "run",
Self::Assign => "assign",
Self::Unassign => "unassign",
Self::Start => "start",
Self::Stop => "stop",
Self::Rm => "rm",
Self::Checkout => "checkout",
Self::Rebuild => "rebuild",
Self::RestartServices => "restart_services",
Self::RmBuild => "rm_build",
Self::ArchiveProject => "archive_project",
Self::UnarchiveProject => "unarchive_project",
Self::SharedStart => "shared_start",
Self::SharedStop => "shared_stop",
Self::SharedRestart => "shared_restart",
Self::SharedRm => "shared_rm",
Self::SecretSet => "secret_set",
Self::ServiceStart => "service_start",
Self::ServiceStop => "service_stop",
Self::ServiceRestart => "service_restart",
Self::ServiceRm => "service_rm",
Self::BareServiceStart => "bare_service_start",
Self::BareServiceStop => "bare_service_stop",
Self::BareServiceRestart => "bare_service_restart",
Self::ClearLogs => "clear_logs",
Self::UploadToContainer => "upload_to_container",
Self::UploadToHost => "upload_to_host",
}
}
}
#[derive(Debug, Clone)]
pub struct ActiveUpdateOperation {
pub id: uuid::Uuid,
pub kind: UpdateOperationKind,
pub project: Option<String>,
pub instance: Option<String>,
pub started_at: chrono::DateTime<chrono::Utc>,
}
pub struct UpdateOperationGuard {
active_ops: Arc<std::sync::Mutex<HashMap<uuid::Uuid, ActiveUpdateOperation>>>,
id: uuid::Uuid,
}
impl Drop for UpdateOperationGuard {
fn drop(&mut self) {
if let Ok(mut ops) = self.active_ops.lock() {
ops.remove(&self.id);
}
}
}
/// Shared application state accessible from all handler tasks.
pub struct AppState {
/// The SQLite state database.
pub db: Mutex<StateDb>,
/// Bollard Docker client connected to the host daemon.
/// None in test environments where Docker is not available.
pub docker: Option<bollard::Docker>,
/// Resolved Docker endpoint metadata, if endpoint resolution succeeded.
pub docker_endpoint: Option<DockerEndpoint>,
/// Last Docker connection error captured at daemon startup, if any.
pub docker_connect_error: Option<String>,
/// Broadcast channel for WebSocket event notifications.
pub event_bus: tokio::sync::broadcast::Sender<CoastEvent>,
/// Persistent PTY sessions for the host terminal feature.
pub pty_sessions:
Mutex<std::collections::HashMap<String, crate::api::ws_host_terminal::PtySession>>,
/// Persistent exec sessions for coast instance terminals.
pub exec_sessions:
Mutex<std::collections::HashMap<String, crate::api::ws_host_terminal::PtySession>>,
/// Persistent exec sessions for inner compose service terminals.
pub service_exec_sessions:
Mutex<std::collections::HashMap<String, crate::api::ws_host_terminal::PtySession>>,
/// Ring buffer of recent stats per container (keyed by "project:name").
pub stats_history:
Mutex<std::collections::HashMap<String, std::collections::VecDeque<serde_json::Value>>>,
/// Live stats broadcast channels per container (keyed by "project:name").
pub stats_broadcasts:
Mutex<std::collections::HashMap<String, tokio::sync::broadcast::Sender<serde_json::Value>>>,
/// Background stats collector task handles per container (keyed by "project:name").
pub stats_collectors: Mutex<std::collections::HashMap<String, tokio::task::JoinHandle<()>>>,
/// Ring buffer of recent stats per inner service (keyed by "project:name:service").
pub service_stats_history:
Mutex<std::collections::HashMap<String, std::collections::VecDeque<serde_json::Value>>>,
/// Live service stats broadcast channels (keyed by "project:name:service").
pub service_stats_broadcasts:
Mutex<std::collections::HashMap<String, tokio::sync::broadcast::Sender<serde_json::Value>>>,
/// Background service stats collector task handles (keyed by "project:name:service").
pub service_stats_collectors:
Mutex<std::collections::HashMap<String, tokio::task::JoinHandle<()>>>,
/// Active LSP server sessions (keyed by "project:name:language").
pub lsp_sessions: Mutex<std::collections::HashMap<String, crate::api::ws_lsp::LspSession>>,
/// Cached shared services responses (keyed by project name).
/// Each entry stores the response and the time it was computed.
pub shared_services_cache: Mutex<
std::collections::HashMap<
String,
(tokio::time::Instant, coast_core::protocol::SharedResponse),
>,
>,
/// Cached count of non-running inner services per instance (keyed by "project:name").
pub service_health_cache: Mutex<std::collections::HashMap<String, u32>>,
/// Cached port health status per instance (keyed by "project:name").
pub port_health_cache:
Mutex<std::collections::HashMap<String, Vec<coast_core::types::PortHealthStatus>>>,
/// Per-project operation semaphores. Mutating operations (run, assign, start,
/// stop, rm, rebuild) acquire a permit before proceeding, serializing heavy
/// Docker workflows within the same project.
pub project_ops: Mutex<std::collections::HashMap<String, Arc<tokio::sync::Semaphore>>>,
/// Current display language. Updated when the user sets a language via the
/// CLI or API. Handlers read from the `watch::Receiver` side.
pub language_tx: tokio::sync::watch::Sender<String>,
/// Receiver side for the language watch channel.
pub language_rx: tokio::sync::watch::Receiver<String>,
/// Non-blocking analytics client. Events are batched and flushed to PostHog.
pub analytics: AnalyticsClient,
/// Watch channel sender for the analytics toggle. The background worker
/// checks this at flush time.
pub analytics_enabled_tx: tokio::sync::watch::Sender<bool>,
/// Reject new mutating requests while the daemon is preparing for self-update.
pub update_quiescing: Arc<AtomicBool>,
/// Explicit registry of currently active mutating operations.
pub active_update_operations: Arc<std::sync::Mutex<HashMap<uuid::Uuid, ActiveUpdateOperation>>>,
}
impl AppState {
/// Create a new `AppState` with the given state database and Docker client.
pub fn new(db: StateDb) -> Self {
let probe = coast_docker::host::probe_host_docker();
let docker_endpoint = probe.endpoint.clone();
let (docker, docker_connect_error) = match probe.docker {
Ok(docker) => (Some(docker), None),
Err(error) => {
if let Some(ref endpoint) = docker_endpoint {
warn!(
source = docker_endpoint_source_label(&endpoint.source),
host = %endpoint.host,
context = endpoint.context.as_deref().unwrap_or(""),
error = %error,
"Docker is unavailable at daemon startup"
);
} else {
warn!(error = %error, "Docker is unavailable at daemon startup");
}
(None, Some(error.to_string()))
}
};
let (event_bus, _) = tokio::sync::broadcast::channel(256);
let initial_lang = db.get_language().unwrap_or_else(|_| "en".to_string());
let (language_tx, language_rx) = tokio::sync::watch::channel(initial_lang);
// Analytics: read or generate a stable anonymous ID, read current toggle
let anonymous_id = match db.get_user_config("anonymous_id") {
Ok(Some(id)) => id,
_ => {
let id = uuid::Uuid::new_v4().to_string();
let _ = db.set_user_config("anonymous_id", &id);
id
}
};
let analytics_initial = db.get_analytics_enabled().unwrap_or(true);
let (analytics_enabled_tx, analytics_enabled_rx) =
tokio::sync::watch::channel(analytics_initial);
let analytics_client = analytics::spawn_worker(anonymous_id, analytics_enabled_rx);
Self {
db: Mutex::new(db),
docker,
docker_endpoint,
docker_connect_error,
event_bus,
pty_sessions: Mutex::new(std::collections::HashMap::new()),
exec_sessions: Mutex::new(std::collections::HashMap::new()),
service_exec_sessions: Mutex::new(std::collections::HashMap::new()),
stats_history: Mutex::new(std::collections::HashMap::new()),
stats_broadcasts: Mutex::new(std::collections::HashMap::new()),
stats_collectors: Mutex::new(std::collections::HashMap::new()),
service_stats_history: Mutex::new(std::collections::HashMap::new()),
service_stats_broadcasts: Mutex::new(std::collections::HashMap::new()),
service_stats_collectors: Mutex::new(std::collections::HashMap::new()),
lsp_sessions: Mutex::new(std::collections::HashMap::new()),
shared_services_cache: Mutex::new(std::collections::HashMap::new()),
service_health_cache: Mutex::new(std::collections::HashMap::new()),
port_health_cache: Mutex::new(std::collections::HashMap::new()),
project_ops: Mutex::new(std::collections::HashMap::new()),
language_tx,
language_rx,
analytics: analytics_client,
analytics_enabled_tx,
update_quiescing: Arc::new(AtomicBool::new(false)),
active_update_operations: Arc::new(std::sync::Mutex::new(HashMap::new())),
}
}
/// Create a new `AppState` for testing (no Docker client).
///
/// Port availability and socat sections are skipped (`docker` is `None`).
#[cfg(test)]
pub fn new_for_testing(db: StateDb) -> Self {
let (event_bus, _) = tokio::sync::broadcast::channel(256);
let (language_tx, language_rx) = tokio::sync::watch::channel("en".to_string());
let (analytics_enabled_tx, _analytics_enabled_rx) = tokio::sync::watch::channel(true);
Self {
db: Mutex::new(db),
docker: None,
docker_endpoint: None,
docker_connect_error: None,
event_bus,
pty_sessions: Mutex::new(std::collections::HashMap::new()),
exec_sessions: Mutex::new(std::collections::HashMap::new()),
service_exec_sessions: Mutex::new(std::collections::HashMap::new()),
stats_history: Mutex::new(std::collections::HashMap::new()),
stats_broadcasts: Mutex::new(std::collections::HashMap::new()),
stats_collectors: Mutex::new(std::collections::HashMap::new()),
service_stats_history: Mutex::new(std::collections::HashMap::new()),
service_stats_broadcasts: Mutex::new(std::collections::HashMap::new()),
service_stats_collectors: Mutex::new(std::collections::HashMap::new()),
lsp_sessions: Mutex::new(std::collections::HashMap::new()),
shared_services_cache: Mutex::new(std::collections::HashMap::new()),
service_health_cache: Mutex::new(std::collections::HashMap::new()),
port_health_cache: Mutex::new(std::collections::HashMap::new()),
project_ops: Mutex::new(std::collections::HashMap::new()),
language_tx,
language_rx,
analytics: AnalyticsClient::noop(),
analytics_enabled_tx,
update_quiescing: Arc::new(AtomicBool::new(false)),
active_update_operations: Arc::new(std::sync::Mutex::new(HashMap::new())),
}
}
/// Create a new `AppState` for testing with a Docker client stub.
///
/// Points at `/dev/null` so no real Docker socket is contacted and Docker
/// Desktop is not woken up. The client is never called — it only needs to
/// exist so that `state.docker.is_some()` returns true for code paths like
/// port availability checks.
#[cfg(test)]
pub fn new_for_testing_with_docker(db: StateDb) -> Self {
let mut s = Self::new_for_testing(db);
s.docker = Some(
bollard::Docker::connect_with_http(
"http://127.0.0.1:0",
1,
bollard::API_DEFAULT_VERSION,
)
.expect("bollard stub client creation should not fail"),
);
s.docker_endpoint = Some(DockerEndpoint {
host: "http://127.0.0.1:0".to_string(),
source: coast_docker::host::DockerEndpointSource::EnvHost,
context: None,
});
s
}
/// Get or create the per-project operation semaphore.
///
/// Mutating operations (run, assign, start, stop, rm, rebuild) acquire a
/// permit from this semaphore before proceeding, ensuring only one heavy
/// operation runs per project at a time.
pub async fn project_semaphore(&self, project: &str) -> Arc<tokio::sync::Semaphore> {
let mut map = self.project_ops.lock().await;
map.entry(project.to_string())
.or_insert_with(|| Arc::new(tokio::sync::Semaphore::new(1)))
.clone()
}
/// Whether the daemon is currently blocking new mutating work for self-update.
pub fn is_update_quiescing(&self) -> bool {
self.update_quiescing.load(Ordering::SeqCst)
}
/// Enable or disable self-update quiescing.
pub fn set_update_quiescing(&self, value: bool) {
self.update_quiescing.store(value, Ordering::SeqCst);
}
/// Register a mutating operation so update preparation can wait for it.
pub fn begin_update_operation(
&self,
kind: UpdateOperationKind,
project: Option<&str>,
instance: Option<&str>,
) -> Result<UpdateOperationGuard> {
if self.is_update_quiescing() {
return Err(CoastError::state(
"coastd is preparing for an update. Wait for the update to finish before starting another mutating operation.",
));
}
let id = uuid::Uuid::new_v4();
let operation = ActiveUpdateOperation {
id,
kind,
project: project.map(std::string::ToString::to_string),
instance: instance.map(std::string::ToString::to_string),
started_at: chrono::Utc::now(),
};
let mut ops = self
.active_update_operations
.lock()
.map_err(|_| CoastError::state("failed to lock update-operation registry"))?;
ops.insert(id, operation);
drop(ops);
Ok(UpdateOperationGuard {
active_ops: Arc::clone(&self.active_update_operations),
id,
})
}
/// Snapshot the currently active mutating operations.
pub fn active_update_operations(&self) -> Vec<ActiveUpdateOperation> {
self.active_update_operations
.lock()
.map(|ops| ops.values().cloned().collect())
.unwrap_or_default()
}
/// Emit an event to all connected WebSocket clients.
/// Silently ignores errors (no subscribers connected).
pub fn emit_event(&self, event: CoastEvent) {
let _ = self.event_bus.send(event);
}
/// Get the current display language.
pub fn language(&self) -> String {
self.language_rx.borrow().clone()
}
}
/// The default socket path: `$COAST_HOME/coastd.sock`.
pub fn default_socket_path() -> Result<PathBuf> {
Ok(coast_core::artifact::coast_home()?.join("coastd.sock"))
}
/// The default PID file path: `$COAST_HOME/coastd.pid`.
pub fn default_pid_path() -> Result<PathBuf> {
Ok(coast_core::artifact::coast_home()?.join("coastd.pid"))
}
/// Ensure the coast home directory exists.
pub fn ensure_coast_dir() -> Result<PathBuf> {
let coast_dir = coast_core::artifact::coast_home()?;
std::fs::create_dir_all(&coast_dir).map_err(|e| CoastError::Io {
message: format!("failed to create {} directory: {e}", coast_dir.display()),
path: coast_dir.clone(),
source: Some(e),
})?;
Ok(coast_dir)
}
/// Start the Unix socket server.
///
/// Listens on the given socket path, accepts connections concurrently,
/// and dispatches requests to handlers via the shared `AppState`.
///
/// The server runs until the `shutdown` signal is received.
#[allow(clippy::cognitive_complexity)]
pub async fn run_server(
socket_path: &Path,
state: Arc<AppState>,
mut shutdown: tokio::sync::broadcast::Receiver<()>,
) -> Result<()> {
// Remove stale socket file if it exists
if socket_path.exists() {
std::fs::remove_file(socket_path).map_err(|e| CoastError::Io {
message: format!(
"failed to remove stale socket file '{}': {e}",
socket_path.display()
),
path: socket_path.to_path_buf(),
source: Some(e),
})?;
}
let listener = UnixListener::bind(socket_path).map_err(|e| CoastError::Io {
message: format!(
"failed to bind Unix socket at '{}'. \
Is another coastd instance running? Error: {e}",
socket_path.display()
),
path: socket_path.to_path_buf(),
source: Some(e),
})?;
info!(socket = %socket_path.display(), "coastd server listening");
loop {
tokio::select! {
accept_result = listener.accept() => {
match accept_result {
Ok((stream, _addr)) => {
let state = Arc::clone(&state);
tokio::spawn(async move {
if let Err(e) = handle_connection(stream, state).await {
error!("connection handler error: {e}");
}
});
}
Err(e) => {
error!("failed to accept connection: {e}");
}
}
}
_ = shutdown.recv() => {
info!("shutdown signal received, stopping server");
break;
}
}
}
// Clean up socket file
if socket_path.exists() {
let _ = std::fs::remove_file(socket_path);
}
info!("coastd server stopped");
Ok(())
}
/// Handle a single client connection.
///
/// Reads one JSON request line, dispatches to the appropriate handler,
/// and writes the JSON response back.
#[allow(clippy::cognitive_complexity)]
async fn handle_connection(stream: tokio::net::UnixStream, state: Arc<AppState>) -> Result<()> {
let (reader, mut writer) = stream.into_split();
let mut buf_reader = BufReader::new(reader);
let mut line = String::new();
// Read one line (newline-terminated JSON)
let bytes_read = buf_reader
.read_line(&mut line)
.await
.map_err(|e| CoastError::io_simple(format!("failed to read request from client: {e}")))?;
if bytes_read == 0 {
debug!("client disconnected without sending data");
return Ok(());
}
let trimmed = line.trim();
if trimmed.is_empty() {
debug!("received empty request");
return Ok(());
}
debug!(request_bytes = bytes_read, "received request");
// Decode the request
let request = match protocol::decode_request(trimmed.as_bytes()) {
Ok(r) => r,
Err(e) => {
warn!("malformed request: {e}");
let resp = Response::Error(ErrorResponse {
error: format!("malformed request: {e}"),
});
write_response(&mut writer, &resp).await?;
return Ok(());
}
};
// Capture command name, context, metadata, and start time for analytics
let request_for_meta = request.clone();
let command_name = analytics::request_command_name(&request);
let (ctx_project, ctx_instance) = analytics::request_context(&request);
let base_metadata = analytics::request_metadata(&request_for_meta);
let ctx_project = ctx_project.map(String::from);
let ctx_instance = ctx_instance.map(String::from);
let start = tokio::time::Instant::now();
// Helper: record an analytics event for the CLI path
let track = |success: bool, metadata: analytics::AnalyticsMetadata| {
state.analytics.track_command_with_context(
&command_name,
CommandSource::Cli,
success,
start.elapsed().as_millis() as u64,
ctx_project.as_deref(),
ctx_instance.as_deref(),
if metadata.is_empty() {
None
} else {
Some(metadata)
},
);
};
// Build and run requests get special streaming treatment: progress events
// are sent as individual JSON lines before the final response.
if let Request::Build(req) = request {
let result = handle_build_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::RerunExtractors(req) = request {
let result = handle_rerun_extractors_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::Run(req) = request {
let result = handle_run_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::Assign(req) = request {
if req.explain {
let result = handlers::assign::handle_explain(req, &state).await;
let response = match result {
Ok(resp) => Response::AssignExplain(resp),
Err(e) => Response::Error(coast_core::protocol::ErrorResponse {
error: e.to_string(),
}),
};
track(
matches!(&response, Response::AssignExplain(_)),
base_metadata.clone(),
);
return write_response(&mut writer, &response).await;
}
let result = handle_assign_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::Unassign(req) = request {
let result = handle_unassign_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::Start(req) = request {
let result = handle_start_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::Stop(req) = request {
let result = handle_stop_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::RmBuild(req) = request {
let result = handle_rm_build_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::AgentShell(req @ coast_core::protocol::AgentShellRequest::Tty { .. }) = request
{
let result =
handlers::agent_shell::handle_tty_stream(req, &state, &mut buf_reader, &mut writer)
.await;
track(result.is_ok(), base_metadata.clone());
return result;
}
if let Request::Logs(req) = request {
if req.follow {
let result = handle_logs_streaming(req, &state, &mut writer).await;
track(result.is_ok(), base_metadata.clone());
return result;
}
let response = handlers::handle_logs(req, &state).await;
let success = !matches!(&response, Response::Error(_));
let mut metadata = base_metadata.clone();
metadata.extend(analytics::response_metadata(&request_for_meta, &response));
write_response(&mut writer, &response).await?;
track(success, metadata);
return Ok(());
}
let response = dispatch_request(request, &state).await;
let success = !matches!(&response, Response::Error(_));
let mut metadata = base_metadata;
metadata.extend(analytics::response_metadata(&request_for_meta, &response));
write_response(&mut writer, &response).await?;
track(success, metadata);
Ok(())
}
/// Encode and write a single response line, then flush.
async fn write_response(
writer: &mut tokio::net::unix::OwnedWriteHalf,
resp: &Response,
) -> Result<()> {
let bytes = protocol::encode_response(resp)
.map_err(|e| CoastError::protocol(format!("failed to encode response: {e}")))?;
writer
.write_all(&bytes)
.await
.map_err(|e| CoastError::io_simple(format!("failed to write response to client: {e}")))?;
writer
.flush()
.await
.map_err(|e| CoastError::io_simple(format!("failed to flush response to client: {e}")))?;
Ok(())
}
async fn begin_streaming_update_operation(
state: &AppState,
kind: UpdateOperationKind,
project: Option<&str>,
instance: Option<&str>,
writer: &mut tokio::net::unix::OwnedWriteHalf,
) -> Result<Option<UpdateOperationGuard>> {
match state.begin_update_operation(kind, project, instance) {
Ok(guard) => Ok(Some(guard)),
Err(error) => {
let response = Response::Error(ErrorResponse {
error: error.to_string(),
});
write_response(writer, &response).await?;
Ok(None)
}
}
}
/// Handle a build request with streaming progress output.
///
/// Creates an mpsc channel, runs the build handler concurrently with a
/// loop that forwards progress events to the client as JSON lines.
#[allow(clippy::cognitive_complexity)]
async fn handle_build_streaming(
req: coast_core::protocol::BuildRequest,
state: &AppState,
writer: &mut tokio::net::unix::OwnedWriteHalf,
) -> Result<()> {
// Derive project name from the coastfile to acquire the per-project semaphore.
let project_name = coast_core::coastfile::Coastfile::from_file(&req.coastfile_path)
.map(|cf| cf.name)
.unwrap_or_default();
let sem = if !project_name.is_empty() {
Some(state.project_semaphore(&project_name).await)
} else {
None
};
let Some(_operation_guard) = begin_streaming_update_operation(
state,
UpdateOperationKind::Build,
(!project_name.is_empty()).then_some(project_name.as_str()),
None,
writer,
)
.await?
else {
return Ok(());
};
let _permit = match &sem {
Some(s) => Some(
s.acquire()
.await
.map_err(|_| CoastError::state("operation queue closed"))?,
),
None => None,
};
let (tx, mut rx) = tokio::sync::mpsc::channel::<BuildProgressEvent>(64);
let mut build_future = std::pin::pin!(handlers::handle_build_with_progress(req, state, tx));
let mut build_done = false;
let mut build_result: Option<
std::result::Result<coast_core::protocol::BuildResponse, coast_core::error::CoastError>,
> = None;
loop {
if build_done {
// Drain remaining buffered events after handler finished
while let Ok(event) = rx.try_recv() {
let resp = Response::BuildProgress(event);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send build progress: {e}");
break;
}
}
break;
}
tokio::select! {
result = &mut build_future => {
build_result = Some(result);
build_done = true;
// Don't break yet — drain remaining events in next iteration
}
event = rx.recv() => {
if let Some(event) = event {
let resp = Response::BuildProgress(event);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send build progress: {e}");
}
}
}
}
}
let final_response = match build_result.unwrap() {
Ok(resp) => Response::Build(resp),
Err(e) => Response::Error(ErrorResponse {
error: e.to_string(),
}),
};
write_response(writer, &final_response).await
}
/// Handle a logs request with streaming output chunks.
async fn handle_logs_streaming(
req: coast_core::protocol::LogsRequest,
state: &AppState,
writer: &mut tokio::net::unix::OwnedWriteHalf,
) -> Result<()> {
let (tx, mut rx) = tokio::sync::mpsc::channel::<LogsResponse>(64);
let mut logs_future = std::pin::pin!(handlers::handle_logs_with_progress(req, state, tx));
let mut logs_done = false;
let mut logs_result: Option<
std::result::Result<coast_core::protocol::LogsResponse, coast_core::error::CoastError>,
> = None;
loop {
if logs_done {
while let Ok(chunk) = rx.try_recv() {
let resp = Response::LogsProgress(chunk);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send logs progress: {e}");
return Ok(());
}
}
break;
}
tokio::select! {
result = &mut logs_future => {
logs_result = Some(result);
logs_done = true;
}
chunk = rx.recv() => {
if let Some(chunk) = chunk {
let resp = Response::LogsProgress(chunk);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send logs progress: {e}");
return Ok(());
}
}
}
}
}
let final_response = match logs_result.unwrap() {
Ok(resp) => Response::Logs(resp),
Err(e) => Response::Error(ErrorResponse {
error: e.to_string(),
}),
};
write_response(writer, &final_response).await
}
/// Handle a run request with streaming progress output.
#[allow(clippy::cognitive_complexity)]
async fn handle_run_streaming(
req: coast_core::protocol::RunRequest,
state: &Arc<AppState>,
writer: &mut tokio::net::unix::OwnedWriteHalf,
) -> Result<()> {
let Some(_operation_guard) = begin_streaming_update_operation(
state,
UpdateOperationKind::Run,
Some(&req.project),
Some(&req.name),
writer,
)
.await?
else {
return Ok(());
};
{
let db = state.db.lock().await;
let enqueued_inst = coast_core::types::CoastInstance {
name: req.name.clone(),
project: req.project.clone(),
status: coast_core::types::InstanceStatus::Enqueued,
branch: req.branch.clone(),
commit_sha: req.commit_sha.clone(),
container_id: None,
runtime: coast_core::types::RuntimeType::Dind,
created_at: chrono::Utc::now(),
worktree_name: None,
build_id: req.build_id.clone(),
coastfile_type: req.coastfile_type.clone(),
};
db.insert_instance(&enqueued_inst)?;
}
state.emit_event(coast_core::protocol::CoastEvent::InstanceStatusChanged {
name: req.name.clone(),
project: req.project.clone(),
status: "enqueued".to_string(),
});
let sem = state.project_semaphore(&req.project).await;
let _permit = sem
.acquire()
.await
.map_err(|_| CoastError::state("operation queue closed"))?;
{
let db = state.db.lock().await;
let still_exists = db.get_instance(&req.project, &req.name).ok().flatten();
if still_exists.is_none() {
return Ok(());
}
}
let project = req.project.clone();
let name = req.name.clone();
let coastfile_type = req.coastfile_type.clone();
let (tx, mut rx) = tokio::sync::mpsc::channel::<BuildProgressEvent>(64);
let mut run_future = std::pin::pin!(handlers::handle_run_with_progress(req, state, tx));
let mut run_done = false;
let mut run_result: Option<
std::result::Result<coast_core::protocol::RunResponse, coast_core::error::CoastError>,
> = None;
loop {
if run_done {
while let Ok(event) = rx.try_recv() {
let resp = Response::RunProgress(event);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send run progress: {e}");
break;
}
}
break;
}
tokio::select! {
result = &mut run_future => {
run_result = Some(result);
run_done = true;
}
event = rx.recv() => {
if let Some(event) = event {
let resp = Response::RunProgress(event);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send run progress: {e}");
}
}
}
}
}
let final_response = match run_result.unwrap() {
Ok(resp) => {
spawn_agent_shell_if_configured(
state,
&project,
&name,
&resp.container_id,
coastfile_type.as_deref(),
)
.await;
Response::Run(resp)
}
Err(e) => Response::Error(ErrorResponse {
error: e.to_string(),
}),
};
write_response(writer, &final_response).await
}
/// Handle a rerun-extractors request with streaming progress output.
async fn handle_rerun_extractors_streaming(
req: coast_core::protocol::RerunExtractorsRequest,
state: &AppState,
writer: &mut tokio::net::unix::OwnedWriteHalf,
) -> Result<()> {
let Some(_operation_guard) = begin_streaming_update_operation(
state,
UpdateOperationKind::RerunExtractors,
Some(&req.project),
None,
writer,
)
.await?
else {
return Ok(());
};
let (tx, mut rx) = tokio::sync::mpsc::channel::<BuildProgressEvent>(64);
let mut rerun_future = std::pin::pin!(handlers::handle_rerun_extractors_with_progress(
req, state, tx
));
let mut rerun_done = false;
let mut rerun_result: Option<
std::result::Result<
coast_core::protocol::RerunExtractorsResponse,
coast_core::error::CoastError,
>,
> = None;
loop {
if rerun_done {
while let Ok(event) = rx.try_recv() {
let resp = Response::RerunExtractorsProgress(event);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send rerun-extractors progress: {e}");
break;
}
}
break;
}
tokio::select! {
result = &mut rerun_future => {
rerun_result = Some(result);
rerun_done = true;
}
event = rx.recv() => {
if let Some(event) = event {
let resp = Response::RerunExtractorsProgress(event);
if let Err(e) = write_response(writer, &resp).await {
warn!("failed to send rerun-extractors progress: {e}");
}
}
}
}
}
let final_response = match rerun_result.unwrap() {
Ok(resp) => Response::RerunExtractors(resp),
Err(e) => Response::Error(ErrorResponse {
error: e.to_string(),
}),
};
write_response(writer, &final_response).await