-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.rs
More file actions
1420 lines (1256 loc) · 44 KB
/
store.rs
File metadata and controls
1420 lines (1256 loc) · 44 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
//! SQLite persistence layer via sqlx.
//!
//! Provides [`Store`] — a connection-pool wrapper with CRUD operations for
//! three domain entities: [`Project`], [`Session`], and [`Terminal`].
//!
//! WAL mode is enabled at pool-open time so concurrent async readers do not
//! block writers. Foreign-key enforcement is also turned on.
//!
//! Optimistic concurrency: state-update helpers include a WHERE clause that
//! matches the caller's last-known `updated_at` timestamp. A return value of
//! `false` means either the row was not found or a concurrent writer already
//! changed it — the caller should re-read and retry.
use chrono::{DateTime, Utc};
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
SqlitePool,
};
use std::str::FromStr;
use uuid::Uuid;
// ---------------------------------------------------------------------------
// Domain types
// ---------------------------------------------------------------------------
/// State of a cloned git project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectState {
Cloning,
Ready,
Failed,
}
impl ProjectState {
fn as_str(&self) -> &'static str {
match self {
Self::Cloning => "Cloning",
Self::Ready => "Ready",
Self::Failed => "Failed",
}
}
/// Lowercase state string for REST API responses.
pub fn as_api_str(&self) -> &'static str {
match self {
Self::Cloning => "cloning",
Self::Ready => "ready",
Self::Failed => "failed",
}
}
}
impl FromStr for ProjectState {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Cloning" => Ok(Self::Cloning),
"Ready" => Ok(Self::Ready),
"Failed" => Ok(Self::Failed),
other => Err(format!("unknown ProjectState: {other}")),
}
}
}
/// A cloned git repository tracked by the runner.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Project {
pub id: String,
pub name: String,
pub git_url: String,
pub local_path: String,
/// Default Docker image for sessions in this project (image resolution chain level 2).
pub default_image: Option<String>,
pub state: ProjectState,
pub clone_error: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub deleted_at: Option<DateTime<Utc>>,
}
/// Parameters required to create a new project.
#[derive(Debug, Clone)]
pub struct CreateProject {
pub name: String,
pub git_url: String,
pub local_path: String,
}
// ---------------------------------------------------------------------------
/// State of a container session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionState {
Starting,
Running,
Stopped,
Failed,
}
impl SessionState {
fn as_str(&self) -> &'static str {
match self {
Self::Starting => "Starting",
Self::Running => "Running",
Self::Stopped => "Stopped",
Self::Failed => "Failed",
}
}
/// Lowercase state string used in REST API responses.
pub fn as_api_str(&self) -> &'static str {
match self {
Self::Starting => "starting",
Self::Running => "running",
Self::Stopped => "stopped",
Self::Failed => "failed",
}
}
}
impl FromStr for SessionState {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Starting" => Ok(Self::Starting),
"Running" => Ok(Self::Running),
"Stopped" => Ok(Self::Stopped),
"Failed" => Ok(Self::Failed),
other => Err(format!("unknown SessionState: {other}")),
}
}
}
/// A running container session attached to a project.
#[derive(Debug, Clone)]
pub struct Session {
pub id: String,
pub project_id: String,
pub branch: String,
pub image: String,
pub container_id: Option<String>,
pub state: SessionState,
pub profile: String,
/// Isolated working directory path for this session.
pub work_dir: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub stopped_at: Option<DateTime<Utc>>,
pub error_reason: Option<String>,
pub deleted_at: Option<DateTime<Utc>>,
}
/// Parameters required to create a new session.
#[derive(Debug, Clone)]
pub struct CreateSession {
pub project_id: String,
pub branch: String,
pub image: String,
pub profile: String,
/// Isolated working directory path.
#[allow(dead_code)]
pub work_dir: String,
}
// ---------------------------------------------------------------------------
/// State of a terminal PTY within a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TerminalState {
Starting,
Running,
Stopped,
Failed,
}
impl TerminalState {
fn as_str(&self) -> &'static str {
match self {
Self::Starting => "Starting",
Self::Running => "Running",
Self::Stopped => "Stopped",
Self::Failed => "Failed",
}
}
/// Lowercase state string used in REST API responses.
pub fn as_api_str(&self) -> &'static str {
match self {
Self::Starting => "starting",
Self::Running => "running",
Self::Stopped => "stopped",
Self::Failed => "failed",
}
}
}
impl FromStr for TerminalState {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Starting" => Ok(Self::Starting),
"Running" => Ok(Self::Running),
"Stopped" => Ok(Self::Stopped),
"Failed" => Ok(Self::Failed),
other => Err(format!("unknown TerminalState: {other}")),
}
}
}
/// A terminal PTY instance belonging to a session.
///
/// Session : Terminal = 1 : N. Each terminal represents an independent
/// PTY process within the same container/environment.
#[derive(Debug, Clone)]
pub struct Terminal {
pub id: String,
pub session_id: String,
pub profile: String,
pub state: TerminalState,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
/// Parameters required to create a new terminal.
#[derive(Debug, Clone)]
pub struct CreateTerminal {
pub session_id: String,
pub profile: String,
}
// ---------------------------------------------------------------------------
// Raw row types (sqlx FromRow)
// ---------------------------------------------------------------------------
#[derive(sqlx::FromRow)]
struct ProjectRow {
id: String,
name: String,
git_url: String,
local_path: String,
default_image: Option<String>,
state: String,
clone_error: Option<String>,
created_at: String,
updated_at: String,
deleted_at: Option<String>,
}
impl TryFrom<ProjectRow> for Project {
type Error = sqlx::Error;
fn try_from(row: ProjectRow) -> Result<Self, Self::Error> {
Ok(Self {
id: row.id,
name: row.name,
git_url: row.git_url,
local_path: row.local_path,
default_image: row.default_image,
state: row
.state
.parse()
.map_err(|e: String| sqlx::Error::Decode(e.into()))?,
clone_error: row.clone_error,
created_at: parse_dt(&row.created_at)?,
updated_at: parse_dt(&row.updated_at)?,
deleted_at: row.deleted_at.as_deref().map(parse_dt).transpose()?,
})
}
}
#[derive(sqlx::FromRow)]
struct SessionRow {
id: String,
project_id: String,
branch: String,
image: String,
container_id: Option<String>,
state: String,
profile: String,
work_dir: String,
created_at: String,
updated_at: String,
stopped_at: Option<String>,
error_reason: Option<String>,
deleted_at: Option<String>,
}
impl TryFrom<SessionRow> for Session {
type Error = sqlx::Error;
fn try_from(row: SessionRow) -> Result<Self, Self::Error> {
Ok(Self {
id: row.id,
project_id: row.project_id,
branch: row.branch,
image: row.image,
container_id: row.container_id,
state: row
.state
.parse()
.map_err(|e: String| sqlx::Error::Decode(e.into()))?,
profile: row.profile,
work_dir: row.work_dir,
created_at: parse_dt(&row.created_at)?,
updated_at: parse_dt(&row.updated_at)?,
stopped_at: row.stopped_at.as_deref().map(parse_dt).transpose()?,
error_reason: row.error_reason,
deleted_at: row.deleted_at.as_deref().map(parse_dt).transpose()?,
})
}
}
#[derive(sqlx::FromRow)]
struct TerminalRow {
id: String,
session_id: String,
profile: String,
state: String,
created_at: String,
updated_at: String,
}
impl TryFrom<TerminalRow> for Terminal {
type Error = sqlx::Error;
fn try_from(row: TerminalRow) -> Result<Self, Self::Error> {
Ok(Self {
id: row.id,
session_id: row.session_id,
profile: row.profile,
state: row
.state
.parse()
.map_err(|e: String| sqlx::Error::Decode(e.into()))?,
created_at: parse_dt(&row.created_at)?,
updated_at: parse_dt(&row.updated_at)?,
})
}
}
fn parse_dt(s: &str) -> Result<DateTime<Utc>, sqlx::Error> {
DateTime::parse_from_rfc3339(s)
.map(|dt| dt.with_timezone(&Utc))
.map_err(|e| sqlx::Error::Decode(format!("invalid datetime '{s}': {e}").into()))
}
fn now_str() -> String {
Utc::now().to_rfc3339()
}
// ---------------------------------------------------------------------------
// Delete guard error
// ---------------------------------------------------------------------------
/// Error returned by [`Store::soft_delete_session_unless_last`].
#[derive(Debug)]
pub enum SoftDeleteError {
/// The operation was blocked because the session is the last one for its
/// project — deleting it would violate the project-session invariant.
LastSession,
/// A database-level error occurred.
Database(sqlx::Error),
}
// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------
/// Async SQLite store backed by a connection pool.
///
/// Create with [`Store::new`]; the pool is shared cheaply via `Clone`.
#[derive(Clone, Debug)]
pub struct Store {
pool: SqlitePool,
}
impl Store {
/// Open (or create) the SQLite database at `db_url`, enable WAL mode and
/// foreign-key enforcement, then run pending migrations.
///
/// `db_url` can be `"sqlite::memory:"` for tests or a file path such as
/// `"sqlite:relay.db"`.
/// Create a `Store` from an existing pool (useful for testing).
/// The caller is responsible for running migrations if needed.
#[cfg(test)]
pub(crate) async fn from_pool_with_migrations(pool: SqlitePool) -> Result<Self, sqlx::Error> {
sqlx::migrate!("./migrations").run(&pool).await?;
Ok(Self { pool })
}
/// Create an in-memory `Store` for unit tests.
///
/// Uses a single-connection pool so that all operations share the same
/// in-memory database (`:memory:` creates a fresh DB per connection).
/// Runs all migrations automatically.
#[cfg(test)]
pub async fn for_tests() -> Self {
let opts = SqliteConnectOptions::from_str("sqlite::memory:")
.expect("valid url")
.create_if_missing(true)
.foreign_keys(true);
let pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(opts)
.await
.expect("in-memory pool");
Self::from_pool_with_migrations(pool)
.await
.expect("migrations")
}
pub async fn new(db_url: &str) -> Result<Self, sqlx::Error> {
let opts = SqliteConnectOptions::from_str(db_url)?
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal)
.synchronous(SqliteSynchronous::Normal)
.foreign_keys(true);
let pool = SqlitePoolOptions::new()
.max_connections(16)
.connect_with(opts)
.await?;
sqlx::migrate!("./migrations").run(&pool).await?;
Ok(Self { pool })
}
/// Gracefully close the connection pool.
///
/// Waits for all checked-out connections to be returned, then shuts down
/// the pool. Safe to call multiple times (subsequent calls are no-ops).
pub async fn close(&self) {
self.pool.close().await;
}
// -----------------------------------------------------------------------
// Projects
// -----------------------------------------------------------------------
/// Insert a new project with `Cloning` state.
pub async fn create_project(&self, req: CreateProject) -> Result<Project, sqlx::Error> {
let id = Uuid::new_v4().to_string();
let now = now_str();
sqlx::query(
"INSERT INTO projects (id, name, git_url, local_path, state, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 'Cloning', ?5, ?5)",
)
.bind(&id)
.bind(&req.name)
.bind(&req.git_url)
.bind(&req.local_path)
.bind(&now)
.execute(&self.pool)
.await?;
// Re-read to return the full row (avoids duplicating mapping logic).
self.get_project(&id)
.await?
.ok_or_else(|| sqlx::Error::RowNotFound)
}
/// Fetch a project by id, including soft-deleted rows.
pub async fn get_project(&self, id: &str) -> Result<Option<Project>, sqlx::Error> {
let row = sqlx::query_as::<_, ProjectRow>(
"SELECT id, name, git_url, local_path, default_image, state, clone_error,
created_at, updated_at, deleted_at
FROM projects WHERE id = ?1",
)
.bind(id)
.fetch_optional(&self.pool)
.await?;
row.map(Project::try_from).transpose()
}
/// List all non-deleted projects.
pub async fn list_projects(&self) -> Result<Vec<Project>, sqlx::Error> {
let rows = sqlx::query_as::<_, ProjectRow>(
"SELECT id, name, git_url, local_path, default_image, state, clone_error,
created_at, updated_at, deleted_at
FROM projects WHERE deleted_at IS NULL
ORDER BY created_at",
)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(Project::try_from).collect()
}
/// Update the project's state with optimistic concurrency.
///
/// `updated_at_check` must equal the caller's last-known `updated_at`
/// value. Returns `true` if the row was updated, `false` if not found or
/// the optimistic check failed (stale read).
pub async fn update_project_state(
&self,
id: &str,
state: ProjectState,
clone_error: Option<&str>,
updated_at_check: &str,
) -> Result<bool, sqlx::Error> {
let now = now_str();
let rows_affected = sqlx::query(
"UPDATE projects
SET state = ?1, clone_error = ?2, updated_at = ?3
WHERE id = ?4 AND updated_at = ?5 AND deleted_at IS NULL",
)
.bind(state.as_str())
.bind(clone_error)
.bind(&now)
.bind(id)
.bind(updated_at_check)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Update the `local_path` column for a project (used after id is known).
pub async fn update_project_local_path(
&self,
id: &str,
local_path: &str,
) -> Result<bool, sqlx::Error> {
let rows_affected =
sqlx::query("UPDATE projects SET local_path = ?1 WHERE id = ?2 AND deleted_at IS NULL")
.bind(local_path)
.bind(id)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Update the `default_image` column for a project.
pub async fn update_project_default_image(
&self,
id: &str,
default_image: Option<&str>,
) -> Result<bool, sqlx::Error> {
let now = now_str();
let rows_affected = sqlx::query(
"UPDATE projects SET default_image = ?1, updated_at = ?2
WHERE id = ?3 AND deleted_at IS NULL",
)
.bind(default_image)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Soft-delete a project. Returns `true` if the row was marked deleted.
pub async fn soft_delete_project(&self, id: &str) -> Result<bool, sqlx::Error> {
let now = now_str();
let rows_affected = sqlx::query(
"UPDATE projects SET deleted_at = ?1
WHERE id = ?2 AND deleted_at IS NULL",
)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
// -----------------------------------------------------------------------
// Sessions
// -----------------------------------------------------------------------
/// Insert a new session with `Starting` state.
pub async fn create_session(&self, req: CreateSession) -> Result<Session, sqlx::Error> {
let id = Uuid::new_v4().to_string();
let now = now_str();
sqlx::query(
"INSERT INTO sessions (id, project_id, branch, image, state, profile, work_dir, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 'Starting', ?5, ?6, ?7, ?7)",
)
.bind(&id)
.bind(&req.project_id)
.bind(&req.branch)
.bind(&req.image)
.bind(&req.profile)
.bind(&req.work_dir)
.bind(&now)
.execute(&self.pool)
.await?;
self.get_session(&id)
.await?
.ok_or_else(|| sqlx::Error::RowNotFound)
}
/// Fetch a session by id, including soft-deleted rows.
pub async fn get_session(&self, id: &str) -> Result<Option<Session>, sqlx::Error> {
let row = sqlx::query_as::<_, SessionRow>(
"SELECT id, project_id, branch, image, container_id, state, profile, work_dir,
created_at, updated_at, stopped_at, error_reason, deleted_at
FROM sessions WHERE id = ?1",
)
.bind(id)
.fetch_optional(&self.pool)
.await?;
row.map(Session::try_from).transpose()
}
/// List non-deleted sessions for a project.
pub async fn list_sessions_for_project(
&self,
project_id: &str,
) -> Result<Vec<Session>, sqlx::Error> {
let rows = sqlx::query_as::<_, SessionRow>(
"SELECT id, project_id, branch, image, container_id, state, profile, work_dir,
created_at, updated_at, stopped_at, error_reason, deleted_at
FROM sessions
WHERE project_id = ?1 AND deleted_at IS NULL
ORDER BY created_at",
)
.bind(project_id)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(Session::try_from).collect()
}
/// List all non-deleted sessions (global, paginated by limit/offset).
pub async fn list_all_sessions(
&self,
limit: usize,
offset: usize,
) -> Result<Vec<Session>, sqlx::Error> {
let limit = i64::try_from(limit).unwrap_or(i64::MAX);
let offset = i64::try_from(offset).unwrap_or(i64::MAX);
let rows = sqlx::query_as::<_, SessionRow>(
"SELECT id, project_id, branch, image, container_id, state, profile, work_dir,
created_at, updated_at, stopped_at, error_reason, deleted_at
FROM sessions
WHERE deleted_at IS NULL
ORDER BY created_at
LIMIT ?1 OFFSET ?2",
)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(Session::try_from).collect()
}
/// Update the session's state with optimistic concurrency.
///
/// Returns `true` if the row was updated, `false` if the optimistic check
/// failed or the session was not found / already deleted.
pub async fn update_session_state(
&self,
id: &str,
state: SessionState,
container_id: Option<&str>,
error_reason: Option<&str>,
updated_at_check: &str,
) -> Result<bool, sqlx::Error> {
let now = now_str();
let stopped_at =
matches!(state, SessionState::Stopped | SessionState::Failed).then(|| now.clone());
let rows_affected = sqlx::query(
"UPDATE sessions
SET state = ?1, container_id = COALESCE(?2, container_id),
error_reason = ?3, stopped_at = COALESCE(?4, stopped_at), updated_at = ?5
WHERE id = ?6 AND updated_at = ?7 AND deleted_at IS NULL",
)
.bind(state.as_str())
.bind(container_id)
.bind(error_reason)
.bind(stopped_at)
.bind(&now)
.bind(id)
.bind(updated_at_check)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// List all non-deleted sessions that are in `Starting` or `Running` state.
///
/// Used by the reconciliation pass at server startup to find sessions whose
/// containers may have disappeared while the runner was down.
pub async fn list_active_sessions(&self) -> Result<Vec<Session>, sqlx::Error> {
let rows = sqlx::query_as::<_, SessionRow>(
"SELECT id, project_id, branch, image, container_id, state, profile, work_dir,
created_at, updated_at, stopped_at, error_reason, deleted_at
FROM sessions
WHERE deleted_at IS NULL AND state IN ('Starting', 'Running')
ORDER BY created_at",
)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(Session::try_from).collect()
}
/// Force-set a session's state to `Stopped` without an optimistic-concurrency
/// check. Used only by the reconciliation pass where stale-read retry is not
/// meaningful (the container is already gone).
pub async fn force_stop_session(
&self,
id: &str,
error_reason: &str,
) -> Result<bool, sqlx::Error> {
let now = now_str();
let rows_affected = sqlx::query(
"UPDATE sessions
SET state = 'Stopped', error_reason = ?1, stopped_at = ?2, updated_at = ?2
WHERE id = ?3 AND deleted_at IS NULL AND state IN ('Starting', 'Running')",
)
.bind(error_reason)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Count all non-deleted sessions for the given project (any state).
///
/// Used to enforce the invariant that a project must always have at least
/// one session — the last session cannot be deleted.
pub async fn count_all_sessions_for_project(
&self,
project_id: &str,
) -> Result<usize, sqlx::Error> {
let row: (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM sessions
WHERE project_id = ?1 AND deleted_at IS NULL",
)
.bind(project_id)
.fetch_one(&self.pool)
.await?;
Ok(row.0 as usize)
}
/// Soft-delete a session. Returns `true` if the row was marked deleted.
pub async fn soft_delete_session(&self, id: &str) -> Result<bool, sqlx::Error> {
let now = now_str();
let rows_affected = sqlx::query(
"UPDATE sessions SET deleted_at = ?1
WHERE id = ?2 AND deleted_at IS NULL",
)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Atomically soft-delete a session only when it is NOT the last
/// non-deleted session for its project.
///
/// Returns:
/// - `Ok(true)` — session was deleted
/// - `Ok(false)` — session not found or already deleted
/// - `Err(LastSession)` — session is the last for the project; deletion blocked
pub async fn soft_delete_session_unless_last(&self, id: &str) -> Result<bool, SoftDeleteError> {
let now = now_str();
// A single UPDATE with a correlated subquery ensures atomicity under
// SQLite's WAL serialisation without a separate transaction.
// The WHERE clause only proceeds if the session is not the last one.
let rows_affected = sqlx::query(
"UPDATE sessions SET deleted_at = ?1
WHERE id = ?2
AND deleted_at IS NULL
AND (
SELECT COUNT(*) FROM sessions s2
WHERE s2.project_id = (SELECT project_id FROM sessions WHERE id = ?2)
AND s2.deleted_at IS NULL
) > 1",
)
.bind(&now)
.bind(id)
.execute(&self.pool)
.await
.map_err(SoftDeleteError::Database)?
.rows_affected();
if rows_affected > 0 {
return Ok(true);
}
// Determine why: does the session exist at all?
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM sessions WHERE id = ?1 AND deleted_at IS NULL)",
)
.bind(id)
.fetch_one(&self.pool)
.await
.map_err(SoftDeleteError::Database)?;
if exists {
// Session exists but wasn't deleted — must be the last one.
Err(SoftDeleteError::LastSession)
} else {
Ok(false)
}
}
/// Count non-deleted sessions in `Starting` or `Running` state for
/// the given project.
///
/// Used by the per-project session semaphore to enforce `max_sessions`.
#[allow(dead_code)]
pub async fn count_active_sessions_for_project(
&self,
project_id: &str,
) -> Result<usize, sqlx::Error> {
let row: (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM sessions
WHERE project_id = ?1
AND deleted_at IS NULL
AND state IN ('Starting', 'Running')",
)
.bind(project_id)
.fetch_one(&self.pool)
.await?;
Ok(row.0 as usize)
}
// -----------------------------------------------------------------------
// Terminals
// -----------------------------------------------------------------------
/// Insert a new terminal with `Starting` state.
pub async fn create_terminal(&self, req: CreateTerminal) -> Result<Terminal, sqlx::Error> {
let id = Uuid::new_v4().to_string();
let now = now_str();
sqlx::query(
"INSERT INTO terminals (id, session_id, profile, state, created_at, updated_at)
VALUES (?1, ?2, ?3, 'Starting', ?4, ?4)",
)
.bind(&id)
.bind(&req.session_id)
.bind(&req.profile)
.bind(&now)
.execute(&self.pool)
.await?;
self.get_terminal(&id)
.await?
.ok_or_else(|| sqlx::Error::RowNotFound)
}
/// Fetch a terminal by id.
pub async fn get_terminal(&self, id: &str) -> Result<Option<Terminal>, sqlx::Error> {
let row = sqlx::query_as::<_, TerminalRow>(
"SELECT id, session_id, profile, state, created_at, updated_at
FROM terminals WHERE id = ?1",
)
.bind(id)
.fetch_optional(&self.pool)
.await?;
row.map(Terminal::try_from).transpose()
}
/// List all terminals for a given session.
pub async fn list_terminals_for_session(
&self,
session_id: &str,
) -> Result<Vec<Terminal>, sqlx::Error> {
let rows = sqlx::query_as::<_, TerminalRow>(
"SELECT id, session_id, profile, state, created_at, updated_at
FROM terminals
WHERE session_id = ?1
ORDER BY created_at",
)
.bind(session_id)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(Terminal::try_from).collect()
}
/// Update a terminal's state with optimistic concurrency.
///
/// Returns `true` if the row was updated, `false` if the optimistic check
/// failed or the terminal was not found.
pub async fn update_terminal_state(
&self,
id: &str,
state: TerminalState,
updated_at_check: &str,
) -> Result<bool, sqlx::Error> {
let now = now_str();
let rows_affected = sqlx::query(
"UPDATE terminals
SET state = ?1, updated_at = ?2
WHERE id = ?3 AND updated_at = ?4",
)
.bind(state.as_str())
.bind(&now)
.bind(id)
.bind(updated_at_check)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Delete a terminal by id. Returns `true` if a row was removed.
pub async fn delete_terminal(&self, id: &str) -> Result<bool, sqlx::Error> {
let rows_affected = sqlx::query("DELETE FROM terminals WHERE id = ?1")
.bind(id)
.execute(&self.pool)
.await?
.rows_affected();
Ok(rows_affected > 0)
}
/// Get the first terminal for a session (ordered by creation time).
#[allow(dead_code)]
///
/// Used by gRPC `AttachSession` for backward compatibility — routes to
/// the default terminal without the client knowing about Terminal entities.
pub async fn get_first_terminal_for_session(
&self,
session_id: &str,
) -> Result<Option<Terminal>, sqlx::Error> {
let row = sqlx::query_as::<_, TerminalRow>(
"SELECT id, session_id, profile, state, created_at, updated_at
FROM terminals
WHERE session_id = ?1
ORDER BY created_at ASC
LIMIT 1",
)
.bind(session_id)
.fetch_optional(&self.pool)
.await?;
row.map(Terminal::try_from).transpose()
}
// ---------------------------------------------------------------------------
}
// Unit tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
async fn test_store() -> Store {
Store::for_tests().await
}
#[tokio::test]
async fn wal_mode_is_enabled() {
// WAL is not supported for in-memory SQLite; use a real temp file.
let tmp = tempfile::NamedTempFile::new().expect("tempfile");
let db_url = format!("sqlite:{}", tmp.path().display());
let store = Store::new(&db_url).await.expect("file store");
let row: (String,) = sqlx::query_as("PRAGMA journal_mode")
.fetch_one(&store.pool)
.await
.expect("PRAGMA query failed");
assert_eq!(row.0, "wal", "expected WAL journal mode");
}
#[tokio::test]
async fn create_and_get_project() {
let store = test_store().await;
let project = store
.create_project(CreateProject {
name: "test".into(),