Skip to content

Commit 386726d

Browse files
committed
feat(rust): cutover project.list (second projection entity)
PR #21 (Caminho B): prove the AppContext→Store→projection pattern generalizes beyond sessions, with a new entity (projects). - GET /project (project.list, group `project`) → array<Project>, served natively from the shared `project` projection table via a new ProjectStore. The icon_* columns fold into one `icon` object; sandboxes/commands are JSON columns. Returns all projects; directory/workspace scoping is a documented follow-up. Gated by OPENCODE_RUST_ROUTES=project; 400 reuses BadRequestError. - opencode-db: ProjectStore trait + SqlxProjectStore + MemoryProjectStore + ProjectRecord + PROJECT_DDL; Database::project_store(). - opencode-proto: Project (+ ProjectIcon/ProjectCommands/ProjectTime). - opencode-effect: AppContext now takes an AppServices bundle (Default = in-memory stores), so adding a store no longer churns every call site; added projects() accessor. - xtask: enforces /project. Verified: build/clippy -D warnings/fmt/test (db 24, server 28) and openapi-diff all green. No new external crates. https://claude.ai/code/session_017Lo2jkGdTgRvsPG6tcwEqz
1 parent 104aa89 commit 386726d

8 files changed

Lines changed: 529 additions & 30 deletions

File tree

‎RUST_MIGRATION.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ cargo-dist · cargo-deny. **Out of scope:** tree-sitter (TUI-only).
7979
- ✅ **First session read-route cutover** (PR #18): `GET /api/session/{sessionID}` (`v2.session.get`, group `session`) → `SessionV2Info`, served natively by reading the shared **`session` projection table** via a `SessionStore` wired through `AppContext`. **Finding:** the V2 read routes read projection tables (the projector folds events into them on the *write* path), not the event log per request — so a faithful Rust read is a `SELECT`, not an event fold. `session.status` is **not** cuttable yet (it reads per-process in-memory runner state, which lives in TS until Phase 4). Contract enforced by `openapi-diff` (now collapses `anyOf[X,X]` and drops the `{type:null}` member utoipa adds for `Option<$ref>`); seam-gated (`OPENCODE_RUST_ROUTES=session`, off by default). A separate test exercises `event_store.read()` against externally (TS-)written event rows.
8080
- ✅ **Session list cutover** (PR #19): `GET /api/session` (`v2.session.list`, group `session`) → `SessionsResponse` (`{ data: SessionV2Info[], cursor }`), same `SessionStore` with `limit`/`order`/`search`/`project`/`workspace`/`directory` filters. Contract-enforced (`/api/session`); the 400 union (`anyOf[InvalidCursorError, InvalidRequestError]`) reuses the dedup-collapsing normalizer.
8181
- ✅ **Keyset cursor pagination** (PR #20): `v2.session.list` now returns real `previous`/`next` cursors and follows an inbound `cursor`. Faithful TS keyset semantics (`session.ts`): anchor `(time_created, id)`, order-flip + result-reverse for `previous`, default limit 50; an undecodable cursor → 400 `InvalidCursorError`. The cursor token is a Rust-native `base64url(JSON)` (opaque per the contract; not byte-interchangeable with TS cursors across a mid-pagination rollback — documented). Added the `base64` crate.
82+
- ✅ **Second entity read cutover** (PR #21): `GET /project` (`project.list`, group `project`) → `array<Project>`, served natively from the shared **`project` projection table** via a new `ProjectStore` — proving the `AppContext → Store → projection` pattern generalizes beyond sessions (`icon_*` columns fold into `icon`; `sandboxes`/`commands` are JSON). `directory`/`workspace` scoping is a documented follow-up (returns all projects). `AppContext` now takes an **`AppServices`** bundle (`Default` = in-memory) so adding a store doesn't churn call sites. Contract-enforced (`/project`, 400 reuses `BadRequestError`).
8283
- ⬜ Channels (`watch`/`async-broadcast`), SSE `/event`
8384
- ⬜ Cutover: `agent`, `project`, `project-copy`, `credential`, `model`, `provider`, then `event`
8485

‎crates/opencode-bin/src/main.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::sync::Arc;
1010

1111
use clap::Parser;
1212
use opencode_db::Database;
13-
use opencode_effect::{init_tracing, AppContext};
13+
use opencode_effect::{init_tracing, AppContext, AppServices};
1414
use opencode_server::{proxy::Upstream, RouteTable, ServerState};
1515

1616
#[derive(Parser, Debug)]
@@ -103,7 +103,11 @@ async fn build_app_context(db_path: &Path) -> anyhow::Result<AppContext> {
103103
);
104104
}
105105

106-
Ok(AppContext::new(db.event_store(), db.session_store()))
106+
Ok(AppContext::new(AppServices {
107+
event_store: db.event_store(),
108+
sessions: db.session_store(),
109+
projects: db.project_store(),
110+
}))
107111
}
108112

109113
#[tokio::main]

‎crates/opencode-db/src/lib.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//! migration-apply is deferred to Phase 6.
99
1010
pub mod migration;
11+
pub mod project;
1112
pub mod session;
1213

1314
use std::path::Path;
@@ -23,6 +24,7 @@ use sqlx::SqlitePool;
2324
pub use opencode_events::{EventInput, StoredEvent};
2425

2526
pub use migration::{MigrationReport, EXPECTED_MIGRATIONS};
27+
pub use project::{MemoryProjectStore, ProjectRecord, ProjectStore, SqlxProjectStore, PROJECT_DDL};
2628
pub use session::{
2729
ListAnchor, ListDirection, MemorySessionStore, SessionContextEpoch, SessionContextEpochRepo,
2830
SessionInput, SessionInputRepo, SessionListQuery, SessionRecord, SessionStore,
@@ -232,6 +234,11 @@ impl Database {
232234
Arc::new(SqlxSessionStore::new(self.pool.clone()))
233235
}
234236

237+
/// A [`ProjectStore`] (read model over the `project` projection table), backed by the shared pool.
238+
pub fn project_store(&self) -> Arc<dyn ProjectStore> {
239+
Arc::new(SqlxProjectStore::new(self.pool.clone()))
240+
}
241+
235242
/// The `session_input` repository, backed by the shared pool.
236243
pub fn session_input(&self) -> SessionInputRepo {
237244
SessionInputRepo::new(self.pool.clone())

‎crates/opencode-db/src/project.rs‎

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
//! Read store over the `project` **projection table** — the second entity (after sessions) to prove
2+
//! the `AppContext → Store → projection table` pattern generalizes. Mirrors the TS `project` schema
3+
//! (`packages/core/src/project/sql.ts`): the `icon_*` columns fold into one `icon` object and the
4+
//! `sandboxes`/`commands` columns are JSON. TS owns the schema; reads here are a plain `SELECT`.
5+
6+
use std::sync::Mutex;
7+
8+
use async_trait::async_trait;
9+
use serde_json::Value;
10+
use sqlx::sqlite::SqliteRow;
11+
use sqlx::{Row, SqlitePool};
12+
13+
use crate::DbError;
14+
15+
/// `project` projection-table DDL (the columns this store reads). For tests / a future Rust-applies
16+
/// path; TS owns the real (possibly wider) table.
17+
pub const PROJECT_DDL: &str = "\
18+
CREATE TABLE IF NOT EXISTS project (\
19+
id text PRIMARY KEY,\
20+
worktree text NOT NULL,\
21+
vcs text,\
22+
name text,\
23+
icon_url text,\
24+
icon_url_override text,\
25+
icon_color text,\
26+
time_created integer NOT NULL,\
27+
time_updated integer NOT NULL,\
28+
time_initialized integer,\
29+
sandboxes text NOT NULL DEFAULT '[]',\
30+
commands text\
31+
);";
32+
33+
/// A row of the `project` projection table.
34+
#[derive(Debug, Clone, PartialEq)]
35+
pub struct ProjectRecord {
36+
/// Project id.
37+
pub id: String,
38+
/// Absolute worktree path.
39+
pub worktree: String,
40+
/// Version-control system (e.g. `"git"`), if known.
41+
pub vcs: Option<String>,
42+
/// Display name, if set.
43+
pub name: Option<String>,
44+
/// Icon URL, if set.
45+
pub icon_url: Option<String>,
46+
/// Icon URL override, if set.
47+
pub icon_url_override: Option<String>,
48+
/// Icon color, if set.
49+
pub icon_color: Option<String>,
50+
/// Creation time (ms).
51+
pub time_created: i64,
52+
/// Last-updated time (ms).
53+
pub time_updated: i64,
54+
/// Initialization time (ms), if initialized.
55+
pub time_initialized: Option<i64>,
56+
/// Sandbox worktree paths (JSON array column).
57+
pub sandboxes: Vec<String>,
58+
/// Project commands JSON (`{ start? }`), if set.
59+
pub commands: Option<Value>,
60+
}
61+
62+
const PROJECT_COLS: &str = "id, worktree, vcs, name, icon_url, icon_url_override, icon_color, \
63+
time_created, time_updated, time_initialized, sandboxes, commands";
64+
65+
fn record_from_row(row: &SqliteRow) -> Result<ProjectRecord, DbError> {
66+
let sandboxes: String = row.try_get("sandboxes")?;
67+
let sandboxes: Vec<String> = serde_json::from_str(&sandboxes)?;
68+
let commands: Option<String> = row.try_get("commands")?;
69+
let commands = commands.map(|s| serde_json::from_str(&s)).transpose()?;
70+
Ok(ProjectRecord {
71+
id: row.try_get("id")?,
72+
worktree: row.try_get("worktree")?,
73+
vcs: row.try_get("vcs")?,
74+
name: row.try_get("name")?,
75+
icon_url: row.try_get("icon_url")?,
76+
icon_url_override: row.try_get("icon_url_override")?,
77+
icon_color: row.try_get("icon_color")?,
78+
time_created: row.try_get("time_created")?,
79+
time_updated: row.try_get("time_updated")?,
80+
time_initialized: row.try_get("time_initialized")?,
81+
sandboxes,
82+
commands,
83+
})
84+
}
85+
86+
/// Read-only store over the `project` projection table.
87+
#[async_trait]
88+
pub trait ProjectStore: Send + Sync {
89+
/// List all projects, most-recently-created first.
90+
async fn list(&self) -> Result<Vec<ProjectRecord>, DbError>;
91+
}
92+
93+
/// SQLite-backed [`ProjectStore`] over the shared pool.
94+
pub struct SqlxProjectStore {
95+
pool: SqlitePool,
96+
}
97+
98+
impl SqlxProjectStore {
99+
/// Wrap the shared pool.
100+
pub fn new(pool: SqlitePool) -> Self {
101+
Self { pool }
102+
}
103+
}
104+
105+
#[async_trait]
106+
impl ProjectStore for SqlxProjectStore {
107+
async fn list(&self) -> Result<Vec<ProjectRecord>, DbError> {
108+
let rows = sqlx::query(&format!(
109+
"SELECT {PROJECT_COLS} FROM project ORDER BY time_created DESC, id"
110+
))
111+
.fetch_all(&self.pool)
112+
.await?;
113+
rows.iter().map(record_from_row).collect()
114+
}
115+
}
116+
117+
/// In-memory [`ProjectStore`] — test double / the backing for `AppServices::default()`.
118+
#[derive(Default)]
119+
pub struct MemoryProjectStore {
120+
rows: Mutex<Vec<ProjectRecord>>,
121+
}
122+
123+
impl MemoryProjectStore {
124+
/// Create an empty store.
125+
pub fn new() -> Self {
126+
Self::default()
127+
}
128+
129+
/// Insert a project record.
130+
pub fn insert(&self, record: ProjectRecord) {
131+
self.rows
132+
.lock()
133+
.expect("project store mutex poisoned")
134+
.push(record);
135+
}
136+
}
137+
138+
#[async_trait]
139+
impl ProjectStore for MemoryProjectStore {
140+
async fn list(&self) -> Result<Vec<ProjectRecord>, DbError> {
141+
let mut rows = self
142+
.rows
143+
.lock()
144+
.expect("project store mutex poisoned")
145+
.clone();
146+
// Most-recent first, id as a stable tiebreaker (matches the SQL ordering).
147+
rows.sort_by(|a, b| (b.time_created, b.id.as_str()).cmp(&(a.time_created, a.id.as_str())));
148+
Ok(rows)
149+
}
150+
}
151+
152+
#[cfg(test)]
153+
mod tests {
154+
use super::*;
155+
use crate::Database;
156+
use serde_json::json;
157+
158+
#[tokio::test]
159+
async fn sqlx_project_store_reads_ts_written_rows() {
160+
let dir = tempfile::tempdir().unwrap();
161+
let db = Database::connect(dir.path().join("projects.db"))
162+
.await
163+
.unwrap();
164+
sqlx::query(PROJECT_DDL).execute(db.pool()).await.unwrap();
165+
// Two projects (newest by time_created should sort first).
166+
sqlx::query(
167+
"INSERT INTO project (id, worktree, vcs, name, icon_url, time_created, time_updated, \
168+
time_initialized, sandboxes, commands) \
169+
VALUES ('prj_a', '/a', 'git', 'Alpha', 'http://i', 100, 100, 150, \
170+
'[\"/a/sb\"]', '{\"start\":\"bun dev\"}')",
171+
)
172+
.execute(db.pool())
173+
.await
174+
.unwrap();
175+
sqlx::query(
176+
"INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) \
177+
VALUES ('prj_b', '/b', 300, 300, '[]')",
178+
)
179+
.execute(db.pool())
180+
.await
181+
.unwrap();
182+
183+
let store = SqlxProjectStore::new(db.pool().clone());
184+
let projects = store.list().await.unwrap();
185+
assert_eq!(projects.len(), 2);
186+
// Newest first.
187+
assert_eq!(projects[0].id, "prj_b");
188+
assert_eq!(projects[1].id, "prj_a");
189+
let a = &projects[1];
190+
assert_eq!(a.worktree, "/a");
191+
assert_eq!(a.vcs.as_deref(), Some("git"));
192+
assert_eq!(a.icon_url.as_deref(), Some("http://i"));
193+
assert_eq!(a.time_initialized, Some(150));
194+
assert_eq!(a.sandboxes, vec!["/a/sb".to_string()]);
195+
assert_eq!(a.commands, Some(json!({ "start": "bun dev" })));
196+
// prj_b: minimal row.
197+
assert_eq!(projects[0].sandboxes, Vec::<String>::new());
198+
assert_eq!(projects[0].commands, None);
199+
assert_eq!(projects[0].vcs, None);
200+
}
201+
202+
#[tokio::test]
203+
async fn memory_project_store_lists_newest_first() {
204+
let store = MemoryProjectStore::new();
205+
let rec = |id: &str, created: i64| ProjectRecord {
206+
id: id.into(),
207+
worktree: "/w".into(),
208+
vcs: None,
209+
name: None,
210+
icon_url: None,
211+
icon_url_override: None,
212+
icon_color: None,
213+
time_created: created,
214+
time_updated: created,
215+
time_initialized: None,
216+
sandboxes: vec![],
217+
commands: None,
218+
};
219+
store.insert(rec("prj_old", 100));
220+
store.insert(rec("prj_new", 200));
221+
let ids: Vec<String> = store
222+
.list()
223+
.await
224+
.unwrap()
225+
.into_iter()
226+
.map(|p| p.id)
227+
.collect();
228+
assert_eq!(ids, ["prj_new", "prj_old"]);
229+
}
230+
}

‎crates/opencode-effect/src/lib.rs‎

Lines changed: 37 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
99
use std::sync::Arc;
1010

11-
use opencode_db::{EventStore, SessionStore};
11+
use opencode_db::{EventStore, ProjectStore, SessionStore};
1212

1313
/// Binary-edge error taxonomy. Libraries return their own `thiserror` enums; these are mapped to
1414
/// HTTP responses (and to the `opencode_proto::ErrorEnvelope` `_tag` shape) at the server edge.
@@ -50,39 +50,49 @@ impl AppError {
5050
}
5151
}
5252

53-
/// Shared application context — cheap to clone (`Arc`), threaded through axum via `State`.
53+
/// The services wired into an [`AppContext`] (the Rust analog of an Effect `Layer`-provided context).
5454
///
55-
/// This is the Rust analog of an Effect `Layer`-provided context: services are held as
56-
/// `Arc<dyn Trait>` and wired once at the composition root (`build_app_context()` in `opencode-bin`).
57-
/// More services (`Database` repos, `LlmClient`, `Config`, …) are added here as routes are cut over.
55+
/// `Default` provides in-memory stores (tests / ephemeral runs); the composition root
56+
/// (`build_app_context()` in `opencode-bin`) overrides the fields it has real backings for via
57+
/// struct-update syntax — `AppServices { event_store: db.event_store(), ..Default::default() }` — so
58+
/// adding a new store doesn't churn every call site.
5859
#[derive(Clone)]
59-
pub struct AppContext {
60-
inner: Arc<AppContextInner>,
60+
pub struct AppServices {
61+
/// Append-only event store.
62+
pub event_store: Arc<dyn EventStore>,
63+
/// `session` projection read store.
64+
pub sessions: Arc<dyn SessionStore>,
65+
/// `project` projection read store.
66+
pub projects: Arc<dyn ProjectStore>,
67+
}
68+
69+
impl Default for AppServices {
70+
fn default() -> Self {
71+
Self {
72+
event_store: Arc::new(opencode_db::MemoryEventStore::new()),
73+
sessions: Arc::new(opencode_db::MemorySessionStore::new()),
74+
projects: Arc::new(opencode_db::MemoryProjectStore::new()),
75+
}
76+
}
6177
}
6278

63-
struct AppContextInner {
64-
event_store: Arc<dyn EventStore>,
65-
sessions: Arc<dyn SessionStore>,
79+
/// Shared application context — cheap to clone (`Arc`), threaded through axum via `State`.
80+
#[derive(Clone)]
81+
pub struct AppContext {
82+
inner: Arc<AppServices>,
6683
}
6784

6885
impl AppContext {
69-
/// Construct a context wired with the given stores. Production wiring (single shared SQLite pool,
70-
/// migration verification) happens in `build_app_context()`.
71-
pub fn new(event_store: Arc<dyn EventStore>, sessions: Arc<dyn SessionStore>) -> Self {
86+
/// Construct a context from a wired [`AppServices`].
87+
pub fn new(services: AppServices) -> Self {
7288
Self {
73-
inner: Arc::new(AppContextInner {
74-
event_store,
75-
sessions,
76-
}),
89+
inner: Arc::new(services),
7790
}
7891
}
7992

80-
/// A context backed by in-memory stores — for tests and ephemeral runs.
93+
/// A context backed entirely by in-memory stores — for tests and ephemeral runs.
8194
pub fn in_memory() -> Self {
82-
Self::new(
83-
Arc::new(opencode_db::MemoryEventStore::new()),
84-
Arc::new(opencode_db::MemorySessionStore::new()),
85-
)
95+
Self::new(AppServices::default())
8696
}
8797

8898
/// The wired event store.
@@ -94,6 +104,11 @@ impl AppContext {
94104
pub fn sessions(&self) -> &Arc<dyn SessionStore> {
95105
&self.inner.sessions
96106
}
107+
108+
/// The wired project (projection) store.
109+
pub fn projects(&self) -> &Arc<dyn ProjectStore> {
110+
&self.inner.projects
111+
}
97112
}
98113

99114
/// Initialize global tracing. Idempotent and safe to call once at startup.

0 commit comments

Comments
 (0)