clean up
Some checks failed
lint / lint (push) Failing after 5m1s
test / unit (push) Successful in 16m56s
test / integration (push) Failing after 19m2s
lint / lint (pull_request) Failing after 5m4s
test / unit (pull_request) Successful in 16m27s
test / integration (pull_request) Failing after 17m29s
Some checks failed
lint / lint (push) Failing after 5m1s
test / unit (push) Successful in 16m56s
test / integration (push) Failing after 19m2s
lint / lint (pull_request) Failing after 5m4s
test / unit (pull_request) Successful in 16m27s
test / integration (pull_request) Failing after 17m29s
This commit is contained in:
6
Cargo.lock
generated
6
Cargo.lock
generated
@@ -427,9 +427,11 @@ dependencies = [
|
||||
"bcrypt",
|
||||
"chrono",
|
||||
"domain",
|
||||
"hex",
|
||||
"jsonwebtoken",
|
||||
"rand 0.8.6",
|
||||
"serde",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"uuid",
|
||||
@@ -1056,7 +1058,9 @@ dependencies = [
|
||||
"async-trait",
|
||||
"chrono",
|
||||
"futures",
|
||||
"hex",
|
||||
"serde",
|
||||
"sha2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"url",
|
||||
@@ -2525,11 +2529,9 @@ dependencies = [
|
||||
"axum",
|
||||
"chrono",
|
||||
"domain",
|
||||
"hex",
|
||||
"http-body-util",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,402 +0,0 @@
|
||||
# Federated Hashtag Indexing Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** When a federated Note arrives via the ActivityPub inbox, extract its hashtags from the AP `tag` array and attach them to the stored thought so they appear in tag feeds.
|
||||
|
||||
**Architecture:** `accept_note` is changed to return `ThoughtId` (instead of `()`) by doing a SELECT after the INSERT. The `ThoughtsObjectHandler` gains a `TagRepository` dependency; after `accept_note` succeeds, it walks the Note's `tag` array, finds entries with `type == "Hashtag"`, strips and lowercases the `name`, and calls `tag_repo.find_or_create` + `tag_repo.attach_to_thought`. Bootstrap wires the new dependency.
|
||||
|
||||
**Tech Stack:** Rust, sqlx (Postgres), async-trait, `serde_json::Value` (AP tag array), `domain::ports::TagRepository`
|
||||
|
||||
---
|
||||
|
||||
## Key Facts
|
||||
|
||||
- `ActivityPubRepository::accept_note` is defined in `crates/adapters/activitypub-base/src/ap_ports.rs` line 65 — currently returns `Result<(), DomainError>`
|
||||
- `PgActivityPubRepository::accept_note` is in `crates/adapters/postgres/src/activitypub.rs` line 213 — does `INSERT ... ON CONFLICT(ap_id) DO NOTHING` and maps result to `()`
|
||||
- `ThoughtsObjectHandler` is in `crates/adapters/activitypub/src/handler.rs` — has `repo: Arc<dyn ActivityPubRepository>` and calls `accept_note` at line 141
|
||||
- `note.tag` is `Vec<serde_json::Value>` (see `crates/adapters/activitypub/src/note.rs` line 28)
|
||||
- `TagRepository::find_or_create(&str) -> Result<Tag, DomainError>` and `attach_to_thought(&ThoughtId, i32) -> Result<(), DomainError>` are in `crates/domain/src/ports.rs` lines 158–163
|
||||
- `ThoughtId` is already imported in `postgres/src/activitypub.rs` (line 13)
|
||||
- Bootstrap wires `ThoughtsObjectHandler::new(...)` at `crates/bootstrap/src/factory.rs` line 76
|
||||
- Baseline: `cargo test` passes 149 tests
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `crates/adapters/activitypub-base/src/ap_ports.rs` | `accept_note` return: `() → ThoughtId` |
|
||||
| `crates/adapters/postgres/src/activitypub.rs` | Return `ThoughtId` from `accept_note` — INSERT then SELECT |
|
||||
| `crates/adapters/activitypub/src/handler.rs` | Add `tag_repo` field; extract hashtags + attach after `accept_note` |
|
||||
| `crates/bootstrap/src/factory.rs` | Pass `PgTagRepository` to `ThoughtsObjectHandler::new` |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Change `accept_note` trait signature to return `ThoughtId`
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/adapters/activitypub-base/src/ap_ports.rs:65-75`
|
||||
|
||||
- [ ] **Step 1: Add `ThoughtId` import**
|
||||
|
||||
At the top of `crates/adapters/activitypub-base/src/ap_ports.rs`, `ThoughtId` must be in scope. Check existing imports. If not present, add:
|
||||
|
||||
```rust
|
||||
use domain::value_objects::ThoughtId;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Change the return type**
|
||||
|
||||
Find `accept_note` (line 65). Change `-> Result<(), DomainError>` to `-> Result<ThoughtId, DomainError>`:
|
||||
|
||||
```rust
|
||||
/// Persist an incoming remote Note. Idempotent on ap_id.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn accept_note(
|
||||
&self,
|
||||
ap_id: &str,
|
||||
author_id: &UserId,
|
||||
content: &str,
|
||||
published: chrono::DateTime<chrono::Utc>,
|
||||
sensitive: bool,
|
||||
content_warning: Option<String>,
|
||||
visibility: &str,
|
||||
in_reply_to: Option<&str>,
|
||||
) -> Result<ThoughtId, DomainError>;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify it compiles (expect errors in impl)**
|
||||
|
||||
```bash
|
||||
cargo build -p activitypub-base 2>&1 | tail -5
|
||||
```
|
||||
|
||||
Expected: the `activitypub-base` crate itself compiles. Errors in `postgres` and `activitypub` crates are expected — fixed in next tasks.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/adapters/activitypub-base/src/ap_ports.rs
|
||||
git commit -m "refactor(ap-ports): accept_note returns ThoughtId instead of ()"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Update `PgActivityPubRepository::accept_note` to return `ThoughtId`
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/adapters/postgres/src/activitypub.rs:213-256`
|
||||
|
||||
- [ ] **Step 1: Write a failing test for the new return type**
|
||||
|
||||
In `crates/adapters/postgres/src/activitypub.rs`, find the `#[cfg(test)]` block (around line 330). Add:
|
||||
|
||||
```rust
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn accept_note_returns_thought_id(pool: sqlx::PgPool) {
|
||||
let repo = PgActivityPubRepository::new(pool.clone());
|
||||
// Create a remote actor first
|
||||
let actor_user_id = repo
|
||||
.intern_remote_actor("https://remote.example/users/alice")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let thought_id = repo
|
||||
.accept_note(
|
||||
"https://remote.example/notes/1",
|
||||
&actor_user_id,
|
||||
"Hello #rust world",
|
||||
chrono::Utc::now(),
|
||||
false,
|
||||
None,
|
||||
"public",
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Verify the returned ThoughtId is a real UUID in the DB
|
||||
let row: (uuid::Uuid,) = sqlx::query_as("SELECT id FROM thoughts WHERE ap_id=$1")
|
||||
.bind("https://remote.example/notes/1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(thought_id.as_uuid(), row.0);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to confirm it fails**
|
||||
|
||||
```bash
|
||||
cargo test -p postgres accept_note_returns_thought_id 2>&1 | tail -10
|
||||
```
|
||||
|
||||
Expected: compile error — `accept_note` still returns `()`.
|
||||
|
||||
- [ ] **Step 3: Update the implementation**
|
||||
|
||||
Replace the `accept_note` body (lines 213–256). The change: after the INSERT, SELECT the `id` by `ap_id` and wrap it in `ThoughtId`.
|
||||
|
||||
```rust
|
||||
async fn accept_note(
|
||||
&self,
|
||||
ap_id: &str,
|
||||
author_id: &UserId,
|
||||
content: &str,
|
||||
published: DateTime<Utc>,
|
||||
sensitive: bool,
|
||||
content_warning: Option<String>,
|
||||
visibility: &str,
|
||||
in_reply_to: Option<&str>,
|
||||
) -> Result<ThoughtId, DomainError> {
|
||||
let capped: String = content.chars().take(MAX_REMOTE_CONTENT_CHARS).collect();
|
||||
let (in_reply_to_id, in_reply_to_url) = match in_reply_to {
|
||||
Some(url) => {
|
||||
let local_uuid = url::Url::parse(url).ok().and_then(|u| {
|
||||
u.path()
|
||||
.strip_prefix(THOUGHTS_PATH_PREFIX)
|
||||
.and_then(|s| s.split('/').next())
|
||||
.and_then(|s| uuid::Uuid::parse_str(s).ok())
|
||||
});
|
||||
(local_uuid, Some(url.to_string()))
|
||||
}
|
||||
None => (None, None),
|
||||
};
|
||||
sqlx::query(
|
||||
"INSERT INTO thoughts(id,user_id,content,ap_id,visibility,sensitive,local,content_warning,created_at,in_reply_to_id,in_reply_to_url)
|
||||
VALUES($1,$2,$3,$4,$8,$5,false,$6,$7,$9,$10) ON CONFLICT(ap_id) DO NOTHING",
|
||||
)
|
||||
.bind(uuid::Uuid::new_v4())
|
||||
.bind(author_id.as_uuid())
|
||||
.bind(&capped)
|
||||
.bind(ap_id)
|
||||
.bind(sensitive)
|
||||
.bind(content_warning)
|
||||
.bind(published)
|
||||
.bind(visibility)
|
||||
.bind(in_reply_to_id)
|
||||
.bind(&in_reply_to_url)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.into_domain()?;
|
||||
|
||||
// SELECT the id regardless of whether the INSERT was a no-op (idempotent).
|
||||
let row: (uuid::Uuid,) =
|
||||
sqlx::query_as("SELECT id FROM thoughts WHERE ap_id=$1")
|
||||
.bind(ap_id)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.into_domain()?;
|
||||
Ok(ThoughtId::from_uuid(row.0))
|
||||
}
|
||||
```
|
||||
|
||||
`ThoughtId::from_uuid(Uuid) -> ThoughtId` is generated by the `uuid_id!` macro in `crates/domain/src/value_objects.rs` — the call above is correct.
|
||||
|
||||
- [ ] **Step 4: Run the test**
|
||||
|
||||
```bash
|
||||
cargo test -p postgres accept_note_returns_thought_id 2>&1 | tail -5
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Run all backend tests**
|
||||
|
||||
```bash
|
||||
cargo test 2>&1 | tail -5
|
||||
```
|
||||
|
||||
Expected: 149+ tests pass (the new test is extra).
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/adapters/postgres/src/activitypub.rs
|
||||
git commit -m "fix(postgres): accept_note returns ThoughtId via SELECT after INSERT"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Add hashtag indexing to `ThoughtsObjectHandler`
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/adapters/activitypub/src/handler.rs`
|
||||
|
||||
- [ ] **Step 1: Add `TagRepository` import and field**
|
||||
|
||||
At the top of `handler.rs`, add:
|
||||
```rust
|
||||
use domain::ports::TagRepository;
|
||||
```
|
||||
|
||||
Add `tag_repo` to the struct and constructor:
|
||||
|
||||
```rust
|
||||
pub struct ThoughtsObjectHandler {
|
||||
repo: Arc<dyn ActivityPubRepository>,
|
||||
urls: ThoughtsUrls,
|
||||
event_publisher: Option<Arc<dyn EventPublisher>>,
|
||||
tag_repo: Arc<dyn TagRepository>,
|
||||
}
|
||||
|
||||
impl ThoughtsObjectHandler {
|
||||
pub fn new(
|
||||
repo: Arc<dyn ActivityPubRepository>,
|
||||
base_url: &str,
|
||||
event_publisher: Option<Arc<dyn EventPublisher>>,
|
||||
tag_repo: Arc<dyn TagRepository>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repo,
|
||||
urls: ThoughtsUrls::new(base_url),
|
||||
event_publisher,
|
||||
tag_repo,
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Use the returned `ThoughtId` and attach hashtags**
|
||||
|
||||
In the `handle_note` (or equivalent) method, find where `accept_note` is called (around line 141). Change:
|
||||
|
||||
```rust
|
||||
// Before:
|
||||
self.repo
|
||||
.accept_note(
|
||||
ap_id.as_str(),
|
||||
&author_id,
|
||||
¬e.content,
|
||||
note.published,
|
||||
note.sensitive,
|
||||
note.summary,
|
||||
visibility,
|
||||
note.in_reply_to.as_ref().map(|u| u.as_str()),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
```
|
||||
|
||||
To:
|
||||
|
||||
```rust
|
||||
// After:
|
||||
let thought_id = self.repo
|
||||
.accept_note(
|
||||
ap_id.as_str(),
|
||||
&author_id,
|
||||
¬e.content,
|
||||
note.published,
|
||||
note.sensitive,
|
||||
note.summary,
|
||||
visibility,
|
||||
note.in_reply_to.as_ref().map(|u| u.as_str()),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
|
||||
// Extract hashtags from the AP tag array and index them.
|
||||
let hashtag_names: Vec<String> = note
|
||||
.tag
|
||||
.iter()
|
||||
.filter(|t| t.get("type").and_then(|v| v.as_str()) == Some("Hashtag"))
|
||||
.filter_map(|t| t.get("name").and_then(|v| v.as_str()))
|
||||
.map(|name| name.trim_start_matches('#').to_lowercase())
|
||||
.filter(|name| !name.is_empty())
|
||||
.collect();
|
||||
|
||||
for name in hashtag_names {
|
||||
if let Ok(tag) = self.tag_repo.find_or_create(&name).await {
|
||||
let _ = self.tag_repo.attach_to_thought(&thought_id, tag.id).await;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Build to catch errors**
|
||||
|
||||
```bash
|
||||
cargo build -p activitypub 2>&1 | tail -10
|
||||
```
|
||||
|
||||
Expected: compiles. If `TagRepository` or `ThoughtId` imports are wrong, fix them now.
|
||||
|
||||
- [ ] **Step 4: Run all tests**
|
||||
|
||||
```bash
|
||||
cargo test 2>&1 | tail -5
|
||||
```
|
||||
|
||||
Expected: all pass.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/adapters/activitypub/src/handler.rs
|
||||
git commit -m "feat(activitypub): index hashtags from incoming federated notes"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Update bootstrap to inject `TagRepository`
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/bootstrap/src/factory.rs:76-80`
|
||||
|
||||
- [ ] **Step 1: Find the `ThoughtsObjectHandler::new(...)` call**
|
||||
|
||||
Around line 76:
|
||||
```rust
|
||||
Arc::new(ThoughtsObjectHandler::new(
|
||||
Arc::new(PgActivityPubRepository::new(pool.clone())),
|
||||
&cfg.base_url,
|
||||
Some(event_publisher.clone()),
|
||||
))
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add the `tag_repo` argument**
|
||||
|
||||
```rust
|
||||
Arc::new(ThoughtsObjectHandler::new(
|
||||
Arc::new(PgActivityPubRepository::new(pool.clone())),
|
||||
&cfg.base_url,
|
||||
Some(event_publisher.clone()),
|
||||
Arc::new(postgres::tag::PgTagRepository::new(pool.clone())),
|
||||
))
|
||||
```
|
||||
|
||||
`PgTagRepository` is already imported/used in the same file (line 99 constructs one for `AppState`). No new import needed.
|
||||
|
||||
- [ ] **Step 3: Build the full workspace**
|
||||
|
||||
```bash
|
||||
cargo build 2>&1 | tail -5
|
||||
```
|
||||
|
||||
Expected: clean build, no errors.
|
||||
|
||||
- [ ] **Step 4: Run all tests**
|
||||
|
||||
```bash
|
||||
cargo test 2>&1 | tail -5
|
||||
```
|
||||
|
||||
Expected: 150+ tests pass.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/bootstrap/src/factory.rs
|
||||
git commit -m "feat(bootstrap): inject TagRepository into ThoughtsObjectHandler"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Final Verification
|
||||
|
||||
- [ ] `cargo test` passes all tests
|
||||
- [ ] `grep -n "tag_repo" crates/adapters/activitypub/src/handler.rs` shows both the field and the usage after `accept_note`
|
||||
- [ ] `grep -n "ThoughtId" crates/adapters/activitypub-base/src/ap_ports.rs` shows the return type on `accept_note`
|
||||
- [ ] `grep -n "PgTagRepository" crates/bootstrap/src/factory.rs` shows two usages (existing AppState one + new handler one)
|
||||
@@ -1,579 +0,0 @@
|
||||
# Suspense Boundaries & Streaming Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Stream the feed page immediately while sidebar widgets load independently, and fix the N+1 top-friends profile fetch by having the backend return full user objects in one query.
|
||||
|
||||
**Architecture:** The `TopFriendRepository::list_for_user` already JOINs users — the backend just discards the user data and returns only usernames. We fix the handler to return `Vec<UserResponse>`. Frontend: `TopFriends` becomes self-contained (fetches its own data via cookies, no props from page), wrapped in `<Suspense>`. `app/page.tsx` drops all sidebar awaits, reducing critical-path work to two parallel calls.
|
||||
|
||||
**Tech Stack:** Rust/Axum (backend), Next.js 15 App Router, React 19 Suspense, Tailwind CSS, shadcn/ui
|
||||
|
||||
---
|
||||
|
||||
## Key Facts
|
||||
|
||||
- `TopFriendRepository::list_for_user` already returns `Vec<(TopFriend, User)>` — the JOIN with the users table is done. The handler just discards the `User` data.
|
||||
- `to_user_response(u: &User) -> UserResponse` lives in `crates/presentation/src/handlers/auth.rs` as `pub fn` — import it where needed.
|
||||
- Auth token in frontend server components: `(await cookies()).get("auth_token")?.value ?? null` via `next/headers`.
|
||||
- Baseline test suite: `cargo test` (148 tests) in the backend; `npx tsc --noEmit` in `thoughts-frontend/`.
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `crates/api-types/src/responses.rs` | Add `TopFriendsResponse { top_friends: Vec<UserResponse> }` |
|
||||
| `crates/presentation/src/handlers/social.rs` | Return `TopFriendsResponse` instead of `{ topFriends: usernames }` |
|
||||
| `thoughts-frontend/lib/api.ts` | Update `getTopFriends` schema to `z.array(UserSchema)` |
|
||||
| `thoughts-frontend/components/loading-skeleton.tsx` | Add `TagsSkeleton`, `CountSkeleton` |
|
||||
| `thoughts-frontend/components/top-friends.tsx` | Self-contained: fetches own data, no `usernames` prop |
|
||||
| `thoughts-frontend/app/page.tsx` | Strip `getFriends`/`getTopFriends`/`shouldDisplayTopFriends`; add Suspense |
|
||||
| `thoughts-frontend/app/loading.tsx` | New — feed page skeleton |
|
||||
| `thoughts-frontend/app/tags/[tagName]/loading.tsx` | New |
|
||||
| `thoughts-frontend/app/search/loading.tsx` | New |
|
||||
| `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx` | New |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add `TopFriendsResponse` to api-types
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/api-types/src/responses.rs`
|
||||
|
||||
- [ ] **Step 1: Add the response struct**
|
||||
|
||||
In `crates/api-types/src/responses.rs`, after the `NotificationResponse` block, add:
|
||||
|
||||
```rust
|
||||
#[derive(Serialize, utoipa::ToSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TopFriendsResponse {
|
||||
pub top_friends: Vec<UserResponse>,
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify it compiles**
|
||||
|
||||
```bash
|
||||
cargo build -p api-types
|
||||
```
|
||||
|
||||
Expected: Compiles with no errors.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/api-types/src/responses.rs
|
||||
git commit -m "feat(api-types): TopFriendsResponse with Vec<UserResponse>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Update `get_top_friends_handler` to return full user objects
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/presentation/src/handlers/social.rs`
|
||||
|
||||
- [ ] **Step 1: Read the current handler**
|
||||
|
||||
Current code (around line 159–167 in `social.rs`):
|
||||
|
||||
```rust
|
||||
pub async fn get_top_friends_handler(
|
||||
Deps(d): Deps<SocialDeps>,
|
||||
Path(username): Path<String>,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let user = get_user_by_username(&*d.users, &username).await?;
|
||||
let friends = get_top_friends(&*d.top_friends, &user.id).await?;
|
||||
let usernames: Vec<&str> = friends.iter().map(|(_, u)| u.username.as_str()).collect();
|
||||
Ok(Json(serde_json::json!({ "topFriends": usernames })))
|
||||
}
|
||||
```
|
||||
|
||||
`friends` is already `Vec<(TopFriend, User)>` — the user data is there.
|
||||
|
||||
- [ ] **Step 2: Add import and update the handler**
|
||||
|
||||
Add to the imports at the top of `social.rs`:
|
||||
```rust
|
||||
use api_types::responses::TopFriendsResponse;
|
||||
use crate::handlers::auth::to_user_response;
|
||||
```
|
||||
|
||||
Replace the handler body:
|
||||
|
||||
```rust
|
||||
#[utoipa::path(get, path = "/users/{username}/top-friends",
|
||||
params(("username" = String, Path, description = "Username")),
|
||||
responses((status = 200, description = "Top friends list", body = TopFriendsResponse)))]
|
||||
pub async fn get_top_friends_handler(
|
||||
Deps(d): Deps<SocialDeps>,
|
||||
Path(username): Path<String>,
|
||||
) -> Result<Json<TopFriendsResponse>, ApiError> {
|
||||
let user = get_user_by_username(&*d.users, &username).await?;
|
||||
let friends = get_top_friends(&*d.top_friends, &user.id).await?;
|
||||
let top_friends = friends.iter().map(|(_, u)| to_user_response(u)).collect();
|
||||
Ok(Json(TopFriendsResponse { top_friends }))
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run backend tests**
|
||||
|
||||
```bash
|
||||
cargo test
|
||||
```
|
||||
|
||||
Expected: 148 tests pass (same as before — no test exercises the response shape directly).
|
||||
|
||||
- [ ] **Step 4: Smoke-test the endpoint manually (optional)**
|
||||
|
||||
```bash
|
||||
curl -s -H "Authorization: Bearer <your_token>" http://localhost:3001/users/me/top-friends | python3 -m json.tool
|
||||
```
|
||||
|
||||
Expected: `{ "topFriends": [ { "id": "...", "username": "...", "avatarUrl": "...", ... } ] }`
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/presentation/src/handlers/social.rs
|
||||
git commit -m "fix(api): top-friends endpoint returns full UserResponse — eliminates frontend N+1"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Update frontend `getTopFriends` Zod schema
|
||||
|
||||
**Files:**
|
||||
- Modify: `thoughts-frontend/lib/api.ts`
|
||||
|
||||
- [ ] **Step 1: Find and update `getTopFriends`**
|
||||
|
||||
In `lib/api.ts`, find `getTopFriends` (around line 232). Current:
|
||||
|
||||
```ts
|
||||
export const getTopFriends = (username: string, token: string | null) =>
|
||||
apiFetch(
|
||||
`/users/${username}/top-friends`,
|
||||
{ next: { tags: [`profile:${username}`] } },
|
||||
z.object({ topFriends: z.array(z.string()) }),
|
||||
token
|
||||
);
|
||||
```
|
||||
|
||||
Replace with:
|
||||
|
||||
```ts
|
||||
export const getTopFriends = (username: string, token: string | null) =>
|
||||
apiFetch(
|
||||
`/users/${username}/top-friends`,
|
||||
{ next: { tags: [`profile:${username}`] } },
|
||||
z.object({ topFriends: z.array(UserSchema) }),
|
||||
token
|
||||
);
|
||||
```
|
||||
|
||||
`UserSchema` is already defined in the same file — no new import needed.
|
||||
|
||||
- [ ] **Step 2: Type-check**
|
||||
|
||||
```bash
|
||||
cd thoughts-frontend && npx tsc --noEmit
|
||||
```
|
||||
|
||||
Expected: 0 errors. (TypeScript will flag call sites that use `getTopFriends` and expect `string[]` — these are fixed in Task 4.)
|
||||
|
||||
If errors: note them, they'll be resolved in Task 4.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add thoughts-frontend/lib/api.ts
|
||||
git commit -m "fix(frontend): getTopFriends schema returns UserSchema[] not string[]"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Add `TagsSkeleton` and `CountSkeleton` to loading-skeleton.tsx
|
||||
|
||||
**Files:**
|
||||
- Modify: `thoughts-frontend/components/loading-skeleton.tsx`
|
||||
|
||||
- [ ] **Step 1: Add the two new exports**
|
||||
|
||||
In `thoughts-frontend/components/loading-skeleton.tsx`, append after the existing exports:
|
||||
|
||||
```tsx
|
||||
export function TagsSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-4 space-y-2">
|
||||
<Skeleton className="h-4 w-24 mb-3" />
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<Skeleton key={i} className="h-6 w-full rounded-full" />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export function CountSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-4 pb-4">
|
||||
<Skeleton className="h-6 w-32" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`Card`, `CardContent`, and `Skeleton` are already imported in the file.
|
||||
|
||||
- [ ] **Step 2: Type-check**
|
||||
|
||||
```bash
|
||||
cd thoughts-frontend && npx tsc --noEmit
|
||||
```
|
||||
|
||||
Expected: 0 errors.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add thoughts-frontend/components/loading-skeleton.tsx
|
||||
git commit -m "feat(frontend): TagsSkeleton and CountSkeleton for sidebar Suspense fallbacks"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Rewrite `TopFriends` to be self-contained
|
||||
|
||||
**Files:**
|
||||
- Modify: `thoughts-frontend/components/top-friends.tsx`
|
||||
|
||||
- [ ] **Step 1: Replace the component**
|
||||
|
||||
Replace the entire file with:
|
||||
|
||||
```tsx
|
||||
import Link from "next/link";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { UserAvatar } from "./user-avatar";
|
||||
import { getTopFriends } from "@/lib/api";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
interface TopFriendsProps {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export async function TopFriends({ username }: TopFriendsProps) {
|
||||
const token = (await cookies()).get("auth_token")?.value ?? null;
|
||||
const data = await getTopFriends(username, token).catch(() => ({ topFriends: [] }));
|
||||
const friends = data.topFriends;
|
||||
|
||||
if (friends.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Card id="top-friends" className="p-4">
|
||||
<CardHeader id="top-friends__header" className="p-0 pb-2">
|
||||
<CardTitle id="top-friends__title" className="text-lg text-shadow-md">
|
||||
Top Friends
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent id="top-friends__content" className="p-0">
|
||||
{friends.map((friend) => (
|
||||
<Link
|
||||
id={`top-friends__link-${friend.id}`}
|
||||
href={`/users/${friend.username}`}
|
||||
key={friend.id}
|
||||
className="flex items-center gap-3 py-2 px-2 -mx-2 rounded-lg hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
<UserAvatar src={friend.avatarUrl} alt={friend.username} />
|
||||
<span
|
||||
id={`top-friends__name-${friend.id}`}
|
||||
className="text-xs truncate w-full font-medium text-shadow-sm"
|
||||
>
|
||||
{friend.displayName || friend.username}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Changes from old component:
|
||||
- Props: was `{ mode, usernames: string[] }`, now `{ username: string }` — fetches its own data
|
||||
- No more N+1 `getUserProfile` calls — renders `data.topFriends` (already `User[]`) directly
|
||||
- `mode` prop removed — always shows "Top Friends" title (the "friends fallback" mode is dropped)
|
||||
- Returns `null` if no top friends (sidebar just hides the widget)
|
||||
|
||||
- [ ] **Step 2: Type-check**
|
||||
|
||||
```bash
|
||||
cd thoughts-frontend && npx tsc --noEmit
|
||||
```
|
||||
|
||||
Expected: Errors at `app/page.tsx` call sites (still pass old props) — will be fixed in Task 6.
|
||||
|
||||
- [ ] **Step 3: Commit (even with type errors from call sites)**
|
||||
|
||||
```bash
|
||||
git add thoughts-frontend/components/top-friends.tsx
|
||||
git commit -m "refactor(frontend): TopFriends self-contained — fetches own data, no N+1"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Update `app/page.tsx` — strip blocking awaits + add Suspense
|
||||
|
||||
**Files:**
|
||||
- Modify: `thoughts-frontend/app/page.tsx`
|
||||
|
||||
- [ ] **Step 1: Update imports**
|
||||
|
||||
Replace the current import block at the top of `app/page.tsx`:
|
||||
|
||||
```ts
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import { getFeed, getMe, Me } from "@/lib/api";
|
||||
import { ThoughtForm } from "@/components/thought-form";
|
||||
import { EmptyState } from "@/components/empty-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Link from "next/link";
|
||||
import { PopularTags } from "@/components/popular-tags";
|
||||
import { ThoughtThread } from "@/components/thought-thread";
|
||||
import { buildThoughtThreads } from "@/lib/utils";
|
||||
import { TopFriends } from "@/components/top-friends";
|
||||
import { UsersCount } from "@/components/users-count";
|
||||
import { PaginationNav } from "@/components/pagination-nav";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
import { ProfileSkeleton, TagsSkeleton, CountSkeleton } from "@/components/loading-skeleton";
|
||||
```
|
||||
|
||||
(Removed: `getFriends`, `getTopFriends`, `User`)
|
||||
|
||||
- [ ] **Step 2: Replace `FeedPage` function**
|
||||
|
||||
```tsx
|
||||
async function FeedPage({
|
||||
token,
|
||||
searchParams,
|
||||
}: {
|
||||
token: string;
|
||||
searchParams: { page?: string };
|
||||
}) {
|
||||
const page = parseInt(searchParams.page ?? "1", 10);
|
||||
|
||||
const [feedData, me] = await Promise.all([
|
||||
getFeed(token, page).catch(() => null),
|
||||
getMe(token).catch(() => null) as Promise<Me | null>,
|
||||
]);
|
||||
|
||||
if (!feedData || !me) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
const { items: allThoughts, totalPages } = feedData!;
|
||||
const thoughtThreads = buildThoughtThreads(allThoughts);
|
||||
|
||||
const sidebar = (
|
||||
<>
|
||||
<Suspense fallback={<ProfileSkeleton />}>
|
||||
<TopFriends username={me.username} />
|
||||
</Suspense>
|
||||
<Suspense fallback={<TagsSkeleton />}>
|
||||
<PopularTags />
|
||||
</Suspense>
|
||||
<Suspense fallback={<CountSkeleton />}>
|
||||
<UsersCount />
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto max-w-6xl p-4 sm:p-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
|
||||
<aside className="hidden lg:block lg:col-span-1">
|
||||
<div className="sticky top-20 space-y-6 glass-effect glossy-effect bottom rounded-md p-4">
|
||||
<h2 className="text-lg font-semibold">Filters & Sorting</h2>
|
||||
<p className="text-sm text-muted-foreground">Coming soon...</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="col-span-1 lg:col-span-2 space-y-6">
|
||||
<header className="mb-6">
|
||||
<h1 className="text-3xl font-bold text-shadow-sm">Your Feed</h1>
|
||||
</header>
|
||||
<ThoughtForm />
|
||||
|
||||
<div className="block lg:hidden space-y-6">
|
||||
{sidebar}
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{thoughtThreads.map((thought) => (
|
||||
<ThoughtThread
|
||||
key={thought.id}
|
||||
thought={thought}
|
||||
currentUser={me}
|
||||
/>
|
||||
))}
|
||||
{thoughtThreads.length === 0 && (
|
||||
<EmptyState message="Your feed is empty. Follow some users to see their thoughts!" />
|
||||
)}
|
||||
</div>
|
||||
<PaginationNav
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
buildHref={(p) => `/?page=${p}`}
|
||||
/>
|
||||
</main>
|
||||
|
||||
<aside className="hidden lg:block lg:col-span-1">
|
||||
<div className="sticky top-20 space-y-6">
|
||||
{sidebar}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Type-check**
|
||||
|
||||
```bash
|
||||
cd thoughts-frontend && npx tsc --noEmit
|
||||
```
|
||||
|
||||
Expected: 0 errors.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add thoughts-frontend/app/page.tsx
|
||||
git commit -m "perf(frontend): stream sidebar via Suspense — feed renders immediately, sidebar loads async"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Add `loading.tsx` files for pages missing them
|
||||
|
||||
**Files:**
|
||||
- Create: `thoughts-frontend/app/loading.tsx`
|
||||
- Create: `thoughts-frontend/app/tags/[tagName]/loading.tsx`
|
||||
- Create: `thoughts-frontend/app/search/loading.tsx`
|
||||
- Create: `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx`
|
||||
|
||||
- [ ] **Step 1: Create `thoughts-frontend/app/loading.tsx`**
|
||||
|
||||
This matches the feed page layout (3-column grid with feed column visible):
|
||||
|
||||
```tsx
|
||||
import { ThoughtSkeleton } from "@/components/loading-skeleton";
|
||||
|
||||
export default function FeedLoading() {
|
||||
return (
|
||||
<div className="container mx-auto max-w-6xl p-4 sm:p-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
|
||||
<aside className="hidden lg:block lg:col-span-1" />
|
||||
<main className="col-span-1 lg:col-span-2 space-y-6">
|
||||
<div className="h-10 w-32 bg-muted rounded animate-pulse mb-6" />
|
||||
<div className="space-y-4">
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
</div>
|
||||
</main>
|
||||
<aside className="hidden lg:block lg:col-span-1" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create `thoughts-frontend/app/tags/[tagName]/loading.tsx`**
|
||||
|
||||
```tsx
|
||||
import { ThoughtSkeleton } from "@/components/loading-skeleton";
|
||||
|
||||
export default function TagLoading() {
|
||||
return (
|
||||
<div className="container mx-auto max-w-2xl p-4 sm:p-6 space-y-4">
|
||||
<div className="h-8 w-40 bg-muted rounded animate-pulse" />
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Create `thoughts-frontend/app/search/loading.tsx`**
|
||||
|
||||
```tsx
|
||||
import { ThoughtSkeleton } from "@/components/loading-skeleton";
|
||||
|
||||
export default function SearchLoading() {
|
||||
return (
|
||||
<div className="container mx-auto max-w-2xl p-4 sm:p-6 space-y-4">
|
||||
<div className="h-8 w-48 bg-muted rounded animate-pulse" />
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Create `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx`**
|
||||
|
||||
```tsx
|
||||
import { ThoughtSkeleton } from "@/components/loading-skeleton";
|
||||
|
||||
export default function ThoughtLoading() {
|
||||
return (
|
||||
<div className="container mx-auto max-w-2xl p-4 sm:p-6 space-y-4">
|
||||
<ThoughtSkeleton />
|
||||
<div className="pl-6 border-l-2 border-primary border-dashed space-y-4">
|
||||
<ThoughtSkeleton />
|
||||
<ThoughtSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Type-check**
|
||||
|
||||
```bash
|
||||
cd thoughts-frontend && npx tsc --noEmit
|
||||
```
|
||||
|
||||
Expected: 0 errors.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add thoughts-frontend/app/loading.tsx \
|
||||
thoughts-frontend/app/tags \
|
||||
thoughts-frontend/app/search/loading.tsx \
|
||||
thoughts-frontend/app/thoughts
|
||||
git commit -m "feat(frontend): loading.tsx skeletons for feed, tags, search, and thread pages"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Final Verification
|
||||
|
||||
- [ ] `cargo test` — 148 tests pass
|
||||
- [ ] `cd thoughts-frontend && npx tsc --noEmit` — 0 errors
|
||||
- [ ] `grep -r "usernames" thoughts-frontend/components/top-friends.tsx` — 0 results (old prop gone)
|
||||
- [ ] `grep -r "getFriends\|getTopFriends\|shouldDisplayTopFriends" thoughts-frontend/app/page.tsx` — 0 results
|
||||
- [ ] `grep -r "Suspense" thoughts-frontend/app/page.tsx` — 3+ results (one per sidebar widget)
|
||||
@@ -1,304 +0,0 @@
|
||||
# Frontend Overhaul Design
|
||||
|
||||
**Date:** 2026-05-15
|
||||
**Status:** Approved
|
||||
|
||||
## Problem
|
||||
|
||||
The backend `/feed` endpoint responds in ~10ms, but the frontend renders the page noticeably later. Three root causes:
|
||||
|
||||
1. **Author profile waterfall** — every page that displays thoughts fetches N separate `getUserProfile` calls after the main feed query, sequentially. 4+ pages duplicate this pattern verbatim.
|
||||
2. **Scattered cache invalidation** — 5 isolated `router.refresh()` calls with no shared abstraction. Full page re-render on every mutation regardless of what actually changed.
|
||||
3. **Broken composition** — `authorDetails: Map<string, {...}>` prop-drilled 4+ levels. Three components over 200 lines. Empty/loading states copy-pasted 4+ times each. `PostThoughtForm` and `ReplyForm` are near-identical duplicates.
|
||||
|
||||
## Approach
|
||||
|
||||
**Server Actions + `revalidateTag`** — idiomatic Next.js 15 + React 19 solution.
|
||||
|
||||
- Backend embeds author data in all response types → waterfall eliminated at the source
|
||||
- Fetch cache tagged by data domain → mutations revalidate exactly what changed, not the whole page
|
||||
- Server Actions replace client-side fetch + `router.refresh()` → one invalidation point per mutation
|
||||
- `useOptimistic` (React 19) → instant UI feedback for toggle interactions
|
||||
- Component splits and shared primitives → composition fixed
|
||||
|
||||
No new dependencies added.
|
||||
|
||||
---
|
||||
|
||||
## Section 1: Backend — Embed Author Data Everywhere
|
||||
|
||||
### New type in `crates/api-types/`
|
||||
|
||||
```rust
|
||||
pub struct AuthorResponse {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub display_name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
```
|
||||
|
||||
### Response types updated
|
||||
|
||||
| Response type | Change |
|
||||
|---|---|
|
||||
| `ThoughtResponse` | Add `author: AuthorResponse` |
|
||||
| `NotificationResponse` | Add `actor: AuthorResponse` |
|
||||
| `BoostResponse` / `LikeResponse` | Add `actor: AuthorResponse` if referencing a user |
|
||||
|
||||
### Architecture constraints
|
||||
|
||||
- Business logic stays in application use cases, not handlers.
|
||||
- **Feed/list queries:** `PgFeedRepository` already joins the users table. `row_to_entry` populates author fields from the existing join — no extra queries.
|
||||
- **Individual thought lookups:** Use cases that return a single thought compose `ThoughtRepository + UserReader` to produce a `ThoughtWithAuthor` output struct. The use case already takes both ports.
|
||||
- **Handlers** only map: `ThoughtWithAuthor → ThoughtResponse { author: AuthorResponse }`. No DB access.
|
||||
|
||||
### Frontend impact
|
||||
|
||||
`lib/api.ts` Zod schemas updated to match. The `authorDetails: Map<string, {...}>` pattern, all `getUserProfile` calls inside page components, and all `Promise.all([...getUserProfile])` waterfalls are deleted.
|
||||
|
||||
---
|
||||
|
||||
## Section 2: Frontend — Tagged Fetch Cache
|
||||
|
||||
Replace bare `fetch()` calls with tagged Next.js fetch so `revalidateTag` can target them precisely.
|
||||
|
||||
### `apiFetch` signature addition
|
||||
|
||||
```ts
|
||||
apiFetch(path, token, options?: RequestInit & { next?: NextFetchRequestConfig })
|
||||
```
|
||||
|
||||
The `next` field passes through to `fetch()`. No new dependencies.
|
||||
|
||||
### Tag taxonomy
|
||||
|
||||
| Tag | Invalidated when |
|
||||
|---|---|
|
||||
| `feed` | thought posted, deleted, edited, boosted |
|
||||
| `profile:{username}` | profile edited, follow/unfollow of that user |
|
||||
| `thoughts:{id}` | thought edited, deleted, replied to |
|
||||
| `tags:{name}` | new thought containing that tag |
|
||||
| `notifications` | any interaction received |
|
||||
|
||||
### Usage
|
||||
|
||||
```ts
|
||||
// lib/api.ts
|
||||
const feed = await apiFetch('/feed', token, { next: { tags: ['feed'] } })
|
||||
const profile = await apiFetch(`/users/${username}`, token, {
|
||||
next: { tags: [`profile:${username}`] }
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Section 3: Mutation Layer — Server Actions
|
||||
|
||||
All mutations become Server Actions in `app/actions/`. Each action calls the backend, then revalidates exactly the affected tags.
|
||||
|
||||
### File layout
|
||||
|
||||
```
|
||||
app/actions/
|
||||
thoughts.ts — createThought, deleteThought, editThought
|
||||
social.ts — followUser, unfollowUser, likeThought, boostThought
|
||||
profile.ts — updateProfile
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
```ts
|
||||
// app/actions/thoughts.ts
|
||||
'use server'
|
||||
import { revalidateTag } from 'next/cache'
|
||||
|
||||
export async function createThought(formData: FormData) {
|
||||
const token = await getToken()
|
||||
await apiFetch('/thoughts', token, { method: 'POST', body: parseFormData(formData) })
|
||||
revalidateTag('feed')
|
||||
}
|
||||
|
||||
export async function deleteThought(thoughtId: string, authorUsername: string) {
|
||||
const token = await getToken()
|
||||
await apiFetch(`/thoughts/${thoughtId}`, token, { method: 'DELETE' })
|
||||
revalidateTag('feed')
|
||||
revalidateTag(`thoughts:${thoughtId}`)
|
||||
revalidateTag(`profile:${authorUsername}`)
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// app/actions/social.ts
|
||||
'use server'
|
||||
|
||||
export async function followUser(username: string) {
|
||||
const token = await getToken()
|
||||
await apiFetch(`/users/${username}/follow`, token, { method: 'POST' })
|
||||
revalidateTag(`profile:${username}`)
|
||||
revalidateTag('feed')
|
||||
}
|
||||
|
||||
export async function likeThought(thoughtId: string) {
|
||||
const token = await getToken()
|
||||
await apiFetch(`/thoughts/${thoughtId}/like`, token, { method: 'POST' })
|
||||
revalidateTag(`thoughts:${thoughtId}`)
|
||||
revalidateTag('feed')
|
||||
}
|
||||
```
|
||||
|
||||
### Migration
|
||||
|
||||
Components drop `router.refresh()` and the `useRouter` import entirely. They call the Server Action directly (or pass it as a prop). The `router` dependency disappears from all mutation components.
|
||||
|
||||
---
|
||||
|
||||
## Section 4: Optimistic Updates — `useOptimistic`
|
||||
|
||||
React 19's `useOptimistic` used for toggle interactions where latency is most noticeable: like, boost, follow.
|
||||
|
||||
### Like/boost (in `ThoughtCardActions`)
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
|
||||
export function ThoughtActions({ thought }: { thought: ThoughtResponse }) {
|
||||
const [optimisticLiked, addOptimisticLike] = useOptimistic(thought.liked_by_viewer)
|
||||
const [optimisticLikes, addOptimisticCount] = useOptimistic(thought.likes_count)
|
||||
|
||||
async function handleLike() {
|
||||
addOptimisticLike(!optimisticLiked)
|
||||
addOptimisticCount(optimisticLiked ? optimisticLikes - 1 : optimisticLikes + 1)
|
||||
await likeThought(thought.id)
|
||||
}
|
||||
|
||||
return (
|
||||
<button onClick={handleLike}>
|
||||
{optimisticLiked ? '♥' : '♡'} {optimisticLikes}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Follow button
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
|
||||
export function FollowButton({ username, initialFollowing }: Props) {
|
||||
const [optimisticFollowing, addOptimistic] = useOptimistic(initialFollowing)
|
||||
|
||||
async function handleFollow() {
|
||||
addOptimistic(!optimisticFollowing)
|
||||
await (optimisticFollowing ? unfollowUser(username) : followUser(username))
|
||||
}
|
||||
|
||||
return <button onClick={handleFollow}>{optimisticFollowing ? 'Unfollow' : 'Follow'}</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Scope:** optimistic updates for like, boost, follow only. `createThought` and `deleteThought` do not get optimistic treatment — tagged cache revalidation is fast enough.
|
||||
|
||||
---
|
||||
|
||||
## Section 5: Composition
|
||||
|
||||
### `ThoughtCard` split
|
||||
|
||||
```
|
||||
components/thought-card/
|
||||
index.tsx — assembles sub-components, no logic
|
||||
header.tsx — avatar, username, display name, timestamp
|
||||
body.tsx — content, hashtag links, content warning toggle
|
||||
actions.tsx — like, boost, reply, delete; owns useOptimistic (client component)
|
||||
```
|
||||
|
||||
Author data comes from `ThoughtResponse.author` directly. No `authorDetails` map, no prop drilling.
|
||||
|
||||
### Unified `ThoughtForm`
|
||||
|
||||
Replaces `PostThoughtForm` and `ReplyForm` (near-identical duplicates).
|
||||
|
||||
```tsx
|
||||
// components/thought-form.tsx
|
||||
type Props = {
|
||||
action: (formData: FormData) => Promise<void> // Server Action passed in
|
||||
placeholder?: string
|
||||
replyTo?: string
|
||||
}
|
||||
```
|
||||
|
||||
Call sites:
|
||||
```tsx
|
||||
<ThoughtForm action={createThought} placeholder="What's on your mind?" />
|
||||
<ThoughtForm action={replyToThought.bind(null, thoughtId)} replyTo={author} />
|
||||
```
|
||||
|
||||
`PostThoughtForm` and `ReplyForm` files are deleted.
|
||||
|
||||
### Shared primitives
|
||||
|
||||
```tsx
|
||||
// components/empty-state.tsx
|
||||
export function EmptyState({ message }: { message: string }) { ... }
|
||||
|
||||
// components/loading-skeleton.tsx
|
||||
export function ThoughtSkeleton() { ... }
|
||||
export function ProfileSkeleton() { ... }
|
||||
```
|
||||
|
||||
4 copy-pasted empty state blocks replaced by `<EmptyState message="No thoughts yet." />`. Repeated loading card JSX replaced by `<ThoughtSkeleton />`.
|
||||
|
||||
### `RemoteUserProfile` split
|
||||
|
||||
```
|
||||
components/remote-user-profile/
|
||||
index.tsx — tab state only (client)
|
||||
profile-card.tsx — avatar, bio, stats (server)
|
||||
connections.tsx — followers/following lists with Suspense boundary (client)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Files Changed
|
||||
|
||||
### Backend (`crates/`)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `crates/api-types/src/responses.rs` | Add `AuthorResponse`; embed in `ThoughtResponse`, `NotificationResponse` |
|
||||
| `crates/adapters/postgres/src/feed.rs` | Enrich `row_to_entry` with author columns from existing join |
|
||||
| `crates/application/src/use_cases/thoughts.rs` | Return `ThoughtWithAuthor` from relevant use cases |
|
||||
| `crates/presentation/src/handlers/thoughts.rs` | Map `ThoughtWithAuthor → ThoughtResponse`; remove secondary user fetches |
|
||||
| `crates/presentation/src/handlers/feed.rs` | Same mapping update |
|
||||
| `crates/presentation/src/handlers/notifications.rs` | Embed actor in notification responses |
|
||||
|
||||
### Frontend (`thoughts-frontend/`)
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `lib/api.ts` | Add `next` option to `apiFetch`; update Zod schemas with `AuthorResponse` |
|
||||
| `app/actions/thoughts.ts` | New — Server Actions for thought mutations |
|
||||
| `app/actions/social.ts` | New — Server Actions for social interactions |
|
||||
| `app/actions/profile.ts` | New — Server Actions for profile mutations |
|
||||
| `app/page.tsx` | Remove author fetch waterfall; use tagged fetch |
|
||||
| `app/users/[username]/page.tsx` | Same |
|
||||
| `app/thoughts/[thoughtId]/page.tsx` | Same |
|
||||
| `app/tags/[tagName]/page.tsx` | Same |
|
||||
| `app/search/page.tsx` | Same |
|
||||
| `components/thought-card/` | Split into header/body/actions |
|
||||
| `components/thought-form.tsx` | New unified form |
|
||||
| `components/post-thought-form.tsx` | Deleted |
|
||||
| `components/reply-form.tsx` | Deleted |
|
||||
| `components/empty-state.tsx` | New shared primitive |
|
||||
| `components/loading-skeleton.tsx` | New shared primitive |
|
||||
| `components/follow-button.tsx` | Remove `router.refresh()`; use Server Action + `useOptimistic` |
|
||||
| `components/remote-user-profile/` | Split into profile-card/connections |
|
||||
|
||||
---
|
||||
|
||||
## What This Does Not Cover
|
||||
|
||||
- Streaming / Suspense boundaries between sidebar widgets (future, lower priority once waterfall is gone)
|
||||
- Search result caching (search is user-input-driven; less predictable tag invalidation)
|
||||
- Pagination beyond the current page-based approach
|
||||
@@ -1,84 +0,0 @@
|
||||
# Federated Hashtag Indexing Design
|
||||
|
||||
**Date:** 2026-05-16
|
||||
**Status:** Approved
|
||||
|
||||
## Problem
|
||||
|
||||
When a remote ActivityPub Note arrives via the inbox, `accept_note` stores the thought in the `thoughts` table (`local = false`) but never attaches hashtags. As a result, federated content is invisible to tag feeds — `/tags/rust` only shows local posts even when remote servers have sent tagged notes.
|
||||
|
||||
## Solution
|
||||
|
||||
After persisting the remote thought, extract hashtags from the Note's AP `tag` array and attach them using the existing `TagRepository` infrastructure.
|
||||
|
||||
---
|
||||
|
||||
## Design
|
||||
|
||||
### Hashtag source: AP `tag` array
|
||||
|
||||
AP Notes carry a structured `tag` array:
|
||||
```json
|
||||
[
|
||||
{ "type": "Hashtag", "name": "#rust", "href": "https://mastodon.social/tags/rust" },
|
||||
{ "type": "Mention", "href": "...", "name": "@alice" }
|
||||
]
|
||||
```
|
||||
|
||||
Filter entries where `type == "Hashtag"`, take `name`, strip the leading `#`, lowercase. Do NOT use `domain::hashtag::extract()` on the raw content — remote content is often HTML and the char-walker would produce false positives inside anchor text.
|
||||
|
||||
### `accept_note` return type change
|
||||
|
||||
`ActivityPubRepository::accept_note` currently returns `Result<(), DomainError>`. Change to `Result<ThoughtId, DomainError>` so the handler has the ID needed for `attach_to_thought`.
|
||||
|
||||
### Handler change
|
||||
|
||||
In `crates/adapters/activitypub/src/handler.rs`, after calling `accept_note`:
|
||||
|
||||
```rust
|
||||
let thought_id = ap_repo.accept_note(...).await?;
|
||||
|
||||
// Extract hashtags from AP tag array
|
||||
let hashtag_names: Vec<String> = note["tag"]
|
||||
.as_array()
|
||||
.map(|tags| {
|
||||
tags.iter()
|
||||
.filter(|t| t["type"].as_str() == Some("Hashtag"))
|
||||
.filter_map(|t| t["name"].as_str())
|
||||
.map(|name| name.trim_start_matches('#').to_lowercase())
|
||||
.filter(|name| !name.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
for name in hashtag_names {
|
||||
if let Ok(tag) = tag_repo.find_or_create(&name).await {
|
||||
let _ = tag_repo.attach_to_thought(&thought_id, tag.id).await;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Tag failures are silenced (`let _ = ...`) — a tag attachment failure should not cause the entire note ingestion to fail.
|
||||
|
||||
### Dependency injection
|
||||
|
||||
The AP handler struct gains `tag_repo: Arc<dyn TagRepository>`. Wired in `crates/bootstrap/src/` alongside the existing handler dependencies.
|
||||
|
||||
---
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `crates/domain/src/ports.rs` | `ActivityPubRepository::accept_note` return type: `() → ThoughtId` |
|
||||
| `crates/adapters/postgres/src/activitypub.rs` | Return `ThoughtId` from `accept_note` impl |
|
||||
| `crates/adapters/activitypub/src/handler.rs` | Add `tag_repo` field; extract + attach hashtags after `accept_note` |
|
||||
| `crates/bootstrap/src/factory.rs` | Inject `TagRepository` into AP handler |
|
||||
|
||||
---
|
||||
|
||||
## What This Does Not Cover
|
||||
|
||||
- Backfilling existing remote thoughts already in the DB (only new incoming notes get tagged)
|
||||
- Updating tags when a remote Edit activity arrives for a previously accepted note
|
||||
- Federated search (search still queries local thoughts only; this only fixes tag feeds)
|
||||
@@ -1,173 +0,0 @@
|
||||
# Suspense Boundaries & Streaming Design
|
||||
|
||||
**Date:** 2026-05-16
|
||||
**Status:** Approved
|
||||
|
||||
## Problem
|
||||
|
||||
The home feed page (`app/page.tsx`) blocks rendering until all data is ready:
|
||||
- `getFeed` + `getMe` — critical path, fine
|
||||
- `getFriends` + `getTopFriends` — sidebar data, runs **after** the feed fetch, adds 150–500ms before any HTML ships
|
||||
- `PopularTags`, `TopFriends`, `UsersCount` are async server components that all resolve before the page renders
|
||||
|
||||
Additionally, `TopFriends` has an N+1 problem: it fetches a list of usernames then makes N separate `getUserProfile` calls in parallel (~500ms–2s+ for 5–10 friends).
|
||||
|
||||
No React Suspense boundaries exist anywhere in the app. `ThoughtSkeleton` and `ProfileSkeleton` are available from the previous overhaul.
|
||||
|
||||
## Solution
|
||||
|
||||
1. **Backend:** enrich `/users/{username}/top-friends` to return full `UserResponse` objects — eliminating the N+1
|
||||
2. **Frontend:** move sidebar fetches into the sidebar components themselves, wrap each in `<Suspense>`, strip secondary fetches from `app/page.tsx`
|
||||
|
||||
---
|
||||
|
||||
## Section 1: Backend — Enrich top-friends endpoint
|
||||
|
||||
### Response type change
|
||||
|
||||
```rust
|
||||
// crates/api-types/src/responses.rs
|
||||
pub struct TopFriendsResponse {
|
||||
pub top_friends: Vec<UserResponse>,
|
||||
}
|
||||
```
|
||||
|
||||
Replaces the existing `{ topFriends: string[] }` shape. Same URL: `GET /users/{username}/top-friends`.
|
||||
|
||||
### Use case change
|
||||
|
||||
The existing use case calls `TopFriendRepository::get_top_friends(username)` returning `Vec<UserId>`. Add a `UserRepository::find_many(&[UserId])` call (or a single JOIN query) to resolve the full user objects in one extra query. No N+1.
|
||||
|
||||
### Files changed
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `crates/api-types/src/responses.rs` | Add `TopFriendsResponse { top_friends: Vec<UserResponse> }` |
|
||||
| `crates/domain/src/ports.rs` | Add `find_many(ids: &[UserId])` to `UserRepository` (or equivalent) |
|
||||
| `crates/adapters/postgres/src/user.rs` | Implement `find_many` with `WHERE id = ANY($1)` |
|
||||
| `crates/application/src/use_cases/users.rs` | Update top-friends use case to return `Vec<User>` |
|
||||
| `crates/presentation/src/handlers/users.rs` | Map `Vec<User>` → `TopFriendsResponse` |
|
||||
|
||||
---
|
||||
|
||||
## Section 2: Frontend — Suspense boundaries + self-contained sidebars
|
||||
|
||||
### Strip `app/page.tsx`
|
||||
|
||||
Remove `getFriends`, `getTopFriends`, `shouldDisplayTopFriends`, and the conditional sidebar rendering logic. Page-level critical path becomes:
|
||||
|
||||
```ts
|
||||
const [feedData, me] = await Promise.all([
|
||||
getFeed(token, page).catch(() => null),
|
||||
getMe(token).catch(() => null),
|
||||
])
|
||||
```
|
||||
|
||||
Pass `me.username` and `token` as props to `TopFriends`.
|
||||
|
||||
### Self-contained `TopFriends`
|
||||
|
||||
`TopFriends` receives `username: string` and `token: string` as props and fetches `getTopFriends(username, token)` internally. The response is now `{ topFriends: UserResponse[] }` — render directly, no secondary fetches.
|
||||
|
||||
### Suspense wrapping (both desktop and mobile sidebars)
|
||||
|
||||
```tsx
|
||||
<Suspense fallback={<ProfileSkeleton />}>
|
||||
<TopFriends username={me.username} token={token} />
|
||||
</Suspense>
|
||||
<Suspense fallback={<TagsSkeleton />}>
|
||||
<PopularTags />
|
||||
</Suspense>
|
||||
<Suspense fallback={<CountSkeleton />}>
|
||||
<UsersCount />
|
||||
</Suspense>
|
||||
```
|
||||
|
||||
Each widget streams in independently. Feed renders as soon as `getFeed` resolves.
|
||||
|
||||
### New skeleton variants
|
||||
|
||||
Add to `components/loading-skeleton.tsx`:
|
||||
|
||||
```tsx
|
||||
export function TagsSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-4 space-y-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
{[...Array(5)].map((_, i) => (
|
||||
<Skeleton key={i} className="h-6 w-full rounded-full" />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export function CountSkeleton() {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-4">
|
||||
<Skeleton className="h-6 w-32" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### `loading.tsx` files for pages missing them
|
||||
|
||||
Currently only `/users/[username]/loading.tsx` exists. Add:
|
||||
|
||||
| Page | Skeleton content |
|
||||
|---|---|
|
||||
| `app/loading.tsx` | `ThoughtSkeleton` × 3 |
|
||||
| `app/tags/[tagName]/loading.tsx` | `ThoughtSkeleton` × 3 |
|
||||
| `app/search/loading.tsx` | `ThoughtSkeleton` × 3 |
|
||||
| `app/thoughts/[thoughtId]/loading.tsx` | `ThoughtSkeleton` × 2 |
|
||||
|
||||
### Update `lib/api.ts`
|
||||
|
||||
```ts
|
||||
// Before
|
||||
export const getTopFriends = (username: string, token: string | null) =>
|
||||
apiFetch(..., z.object({ topFriends: z.array(z.string()) }), token)
|
||||
|
||||
// After
|
||||
export const getTopFriends = (username: string, token: string | null) =>
|
||||
apiFetch(..., z.object({ topFriends: z.array(UserSchema) }), token)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Files Changed
|
||||
|
||||
### Backend
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `crates/api-types/src/responses.rs` | `TopFriendsResponse { top_friends: Vec<UserResponse> }` |
|
||||
| `crates/domain/src/ports.rs` | `UserRepository::find_many` |
|
||||
| `crates/adapters/postgres/src/user.rs` | `find_many` impl |
|
||||
| `crates/application/src/use_cases/users.rs` | Return `Vec<User>` from top-friends use case |
|
||||
| `crates/presentation/src/handlers/users.rs` | Map to `TopFriendsResponse` |
|
||||
|
||||
### Frontend
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `thoughts-frontend/lib/api.ts` | Update `getTopFriends` schema |
|
||||
| `thoughts-frontend/app/page.tsx` | Strip sidebar fetches; pass `username`+`token` to TopFriends |
|
||||
| `thoughts-frontend/components/top-friends.tsx` | Self-contained fetch; use `UserResponse[]` |
|
||||
| `thoughts-frontend/components/loading-skeleton.tsx` | Add `TagsSkeleton`, `CountSkeleton` |
|
||||
| `thoughts-frontend/app/loading.tsx` | New — feed skeleton |
|
||||
| `thoughts-frontend/app/tags/[tagName]/loading.tsx` | New |
|
||||
| `thoughts-frontend/app/search/loading.tsx` | New |
|
||||
| `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx` | New |
|
||||
|
||||
---
|
||||
|
||||
## What This Does Not Cover
|
||||
|
||||
- Suspense on the feed content itself (feed is already the critical path — streaming it would show partial thought lists, which is awkward UX)
|
||||
- Left sidebar "Filters & Sorting" placeholder (still empty)
|
||||
- Streaming on other pages beyond loading.tsx coverage
|
||||
Reference in New Issue
Block a user