Side B fixes a real concurrency bug where a non-reentrant RwLock read guard was held across nested locking calls, which could deadlock the RPC handler, and adds a regression test plus test-harness reliability fixes (timeouts, avoiding pipe-buffer deadlocks) that improve project robustness. Side A also fixes a legitimate bug (duplicate `#entity-section` ids breaking multi-item morph targets) and reduces duplication in vote card rendering, but it's more localized UI plumbing versus B's server-correctness and test-infra fix.
constitution · epochs · watch · epoch 3
c_c6beb77e8e71 (tommy-mor) vs c_9608dc0d38ab (tommy-mor)
download prompt · raw event · cmp_dd4b32a18ff206
council reasoning
B fixes a real Tokio RwLock deadlock by scoping reduced-state read guards in RoomCreate/RoomGrant so locks drop before nested awaits, and backs it with a room-create integration test plus test harness fixes (log-file pipes, HTTP timeouts). A mainly refactors entity morph targets from fixed #entity-section IDs to data-entity-section selectors and reuses entity_section in the vote UI—valuable DRY/cleanup, but not a correctness fix of B’s weight.
Side B fixes a substantive concurrency bug by ensuring `tokio::sync::RwLock` read guards are dropped before later `read().await`/`write().await` calls, preventing self-deadlocks in `RoomCreate` and `RoomGrant`, and adds an integration test covering room creation. Side A is a useful UI refactor that replaces a hard-coded `#entity-section` target with per-item selectors and reuses `entity_section` rendering in the vote view, but it is primarily structural and less critical than eliminating a deadlock in core RPC handling.
sides
A — c_c6beb77e8e71 (tommy-mor)
message
[8dab9b80] nice
diff preview
diff --git a/server/src/fetch/html.rs b/server/src/fetch/html.rs
index 3e0309ff1c2ac1b17923922d2340ba6710e0f9d1..dadf050515f0473943dad97df5d318032c8cb385 100644
--- a/server/src/fetch/html.rs
+++ b/server/src/fetch/html.rs
@@ -10,13 +10,18 @@ use crate::{
ui_action::UI_RPC_FIELD,
};
-fn entity_panel(node: &NodeState) -> Markup {
+/// CSS selector for Idiomorph / SSE updates of one entity block.
+pub fn entity_section_selector(item: &ItemId) -> String {
+ format!(r#"[data-entity-section="{}"]"#, item.as_str())
+}
+
+pub fn entity_panel(node: &NodeState) -> Markup {
if let Some(markup) = crate::render::reddit::entity_markup(node) {
return markup;
}
html! {
@if let Some(data) = &node.data {
- div id="entity-panel" class="entity-card" {
+ div class="entity-card" {
h2 { (data.title) }
@if let Some(author) = &data.author {
p class="muted small" { "by " (author) }
@@ -76,11 +81,11 @@ pub fn fetch_entity_panel(item: &ItemId, has_data: bool, fetching: bool) -> Mark
}
}
-/// Entity card + fetch control (target `#entity-section` for Idiomorph / SSE).
+/// Entity card + fetch control (morph target [`entity_section_selector`]).
pub fn entity_section(item: &ItemId, node: &NodeState, fetching: bool) -> Markup {
let has_data = node.data.is_some();
html! {
- section id="entity-section" class="demo-panel" {
+ section class="entity-section demo-panel" data-entity-section=(item.as_str()) {
(entity_panel(node))
(fetch_entity_panel(item, has_data, fetching))
}
diff --git a/server/src/fetch/mod.rs b/server/src/fetch/mod.rs
index 35f968c21c69ca557bab7951413e3cfbbccfebfd..f5759a34a1afe4069805441cefde6474a6403550 100644
--- a/server/src/fetch/mod.rs
+++ b/server/src/fetch/mod.rs
@@ -77,8 +77,9 @@ pub fn fetch_entity_stream(
let tree = state.tree.read().await;
let empty = NodeState::default();
let node = tree.get(&id).unwrap_or(&empty);
+ let sel = html::entity_section_selector(&id);
JsBuilder::new()
- .morph_selector("#entity-section", html::entity_section(&id, node, true))
+ .morph_selector(&sel, html::entity_section(&id, node, true))
.build()
};
yield Ok(js_event(fetching_js));
@@ -100,12 +101,13 @@ pub fn fetch_entity_stream(
FetchJobResult::Imported(_)
| FetchJobResult::NotFound
| FetchJobResult::SkippedCached
- | FetchJobResult::SkippedDuplicate => {
+ | FetchJobResult::SkippedDuplicate => {
let tree = state.tree.read().await;
let empty = NodeState::default();
let node = tree.get(&id).unwrap_or(&empty);
+ let sel = html::entity_section_selector(&id);
let mut b = JsBuilder::new()
- .morph_selector("#entity-section", html::entity_section(&id, node, false));
+ .morph_selector(&sel, html::entity_section(&id, node, false));
if kind == FetchKind::Children {
b = b.morph_selector("#ranking-panel", ranking_panel(&id, node, &tree));
}
@@ -115,8 +117,9 @@ pub fn fetch_entity_stream(
let tree = state.tree.read().await;
let empty = NodeState::default();
let node = tree.get(&id).unwrap_or(&empty);
+ let sel = html::entity_section_selector(&id);
let js = JsBuilder::new()
- .morph_selector("#entity-section", html::entity_section(&id, node, false))
+ .morph_selector(&sel, html::entity_section(&id, node, false))
.raw(&error_js(&format!("Reddit rate limit — retry in {reset_secs}s.")))
.build();
yield Ok(js_event(js));
@@ -125,8 +128,9 @@ pub fn fetch_entity_stream(
let tree = state.tree.read().await;
let empty = NodeState::default();
let node = tree.get(&id).unwrap_or(&empty);
+ let sel = html::entity_section_selector(&id);
let js = JsBuilder::new()
- .morph_selector("#entity-section", html::entity_section(&id, node, false))
+ .morph_selector(&sel, html::entity_section(&id, node, false))
.raw(&error_js(&format!("Fetch failed: {msg}")))
.build();
yield Ok(js_event(js));
diff --git a/server/src/html/vote.rs b/server/src/html/vote.rs
index 89ed621ad861214e147add2062224fc4137ff8ad..48752f4d78d4762d1badc44e8df008bf5a45bab4 100644
--- a/server/src/html/vote.rs
+++ b/server/src/html/vote.rs
@@ -8,6 +8,7 @@ use maud::{html, Markup};
use serde::Deserialize;
use crate::{
+ fetch::html::entity_section,
form_template::template_json_compact,
html::JsBuilder,
pair::{children_of, resolve_pair, suggest_next_pair_in_pool},
@@ -169,37 +170,13 @@ pub(crate) fn vote_recorded_morph(
}
fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) -> Markup {
- let href = item_href(item);
- let title = child_title(tree, item);
+ let node = tree.get(item).cloned().unwrap_or_else(|| NodeState {
+ id: item.clone(),
+ ..Default::default()
+ });
html! {
div class=(format!("vote-compare-side {side_class}")) {
- a class=(format!("vote-compare-item {side_class}")) href=(href) {
- @if let Some(row) = crate::render::reddit::child_row_markup(tree, item, &href) {
- (row)
- } @else {
- strong { (title) }
- }
- }
- @if let Some(node) = tree.get(item) {
- @if crate::render::reddit::is_reddit_post(item) {
- @if let Some(data) = &node.data {
- @if let Some(src) = data.image_url.as_ref().or(data.thumb_url.as_ref()) {
- figure class="vote-compare-figure" {
- img class="vote-compare-image" src=(src) alt="" loading="lazy";
- }
- }
- @if let Some(author) = &data.author {
- p class="muted small" { "by " (author) }
- }
- }
- } @else if let Some(data) = &node.data {
- @if let Some(body) = &data.body_html {
- div class="vote-compare-item-body" {
- (maud::PreEscaped(body))
- }
- }
- }
- }
+ (entity_section(item, &node, false))
}
}
}
@@ -270,9 +247,6 @@ pub async fn vote_page(
(vote_compare_item_card(&tree, &right, "vote-compare-right"))
}
(vote_back_nav(&parent))
- div id="vote-edge-history-region" {
- (edge_history)
- }
form id="vote-compare-form" method="POST" action="/ui" {
input type="hidden" name=(UI_RPC_FIELD) value=(rpc_json);
input type="hidden" name="ratio_left" id="vote-ratio-left" value="50";
@@ -285,6 +259,9 @@ pub async fn vote_page(
}
(vote_compare_actions(&parent, next_pair.as_ref()))
}
+ div id="vote-edge-history-region" {
+ (edge_history)
+ }
}
};
diff --git a/server/src/render/reddit.rs b/server/src/render/reddit.rs
index 4a18de93cf57d8395ded3caa373a708f39b3f43f..c4f98fc760c32ce1b41a91bd41e97908bd198937 100644
--- a/server/src/render/reddit.rs
+++ b/server/src/render/reddit.rs
@@ -11,7 +11,7 @@ pub fn is_reddit_post(id: &ItemId) -> bool {
id.as_str().starts_with("reddit.com/") && id.as_str().contains("/comments/")
}
-/// Post detail card (`#entity-panel`).
+/// Post detail card (inside [`crate::fetch::html::entity_panel`]).
pub fn entity_markup(node: &NodeState) -> Option<Markup> {
if !is_reddit_post(&node.id) {
return None;
@@ -41,7 +41,7 @@ pub fn child_row_markup(tree: &GlobalTree, id: &ItemId, href: &str) -> Option<Ma
fn post_entity_card(data: &EntityData) -> Markup {
let image = data.image_url.as_ref().or(data.thumb_url.as_ref());
html! {
- div id="entity-panel" class="entity-card reddit-post" {
+ div class="entity-card reddit-post" {
h2 { (data.title) }
@if let Some(author) = &data.author {
p class="muted small" { "by " (author) }
diff --git a/server/static/sorter.css b/server/static/sorter.css
index b95718ce463b200a5667d3014dac2119836a0bef..9379c5f41dedbd41fd8951099a118de1da2a62f4 100644
--- a/server/static/sorter.css
+++ b/server/static/sorter.css
@@ -254,38 +254,11 @@ h1 {
}
.vote-compare-side {
- background: var(--panel);
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 1rem;
min-height: 120px;
}
-.vote-compare-item {
- color: var(--accent);
- text-decoration: none;
- display: block;
-}
-
-.vote-compare-item:hover {
- text-decoration: underline;
-}
-
-.vote-compare-figure {
- margin: 0.75rem 0 0;
-}
-
-.vote-compare-image {
- display: block;
- max-width: 100%;
- height: auto;
- border-radius: 6px;
- border: 1px solid var(--border);
-}
-
-.vote-compare-item-body {
- margin-top: 0.75rem;
- font-size: 0.9rem;
+.vote-compare-side .entity-section {
+ margin: 0;
}
.vote-compare-nav {
B — c_9608dc0d38ab (tommy-mor)
message
[9ecc4e2e] nice
diff preview
diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs
index 5675dcd2e28062acbe3c037b94b77c33adf32474..a18241f3ed7b4a248748fcefc799f9801ca62461 100644
--- a/server/src/api/rpc.rs
+++ b/server/src/api/rpc.rs
@@ -936,7 +936,15 @@ pub async fn handle_rpc_batch(
line_ok(RpcResult::ForumThreads(rpc_list_forum_threads(&reduced, &room)))
}
RpcCommand::RoomCreate { slug, visibility } => {
- match verify_bearer_principal(&headers, &*state.reduced.read().await) {
+ // Scope the first read so its guard drops before any nested `read().await` / `write().await`.
+ // A guard from `match verify(..., &*state.reduced.read().await)` would otherwise live for the
+ // whole `match` and deadlock here (tokio::sync::RwLock is not reentrant).
+ let principal = {
+ let reduced = state.reduced.read().await;
+ verify_bearer_principal(&headers, &*reduced)
+ };
+ match principal {
+ Err((_, m)) => line_err(m, None),
Ok(principal) => {
let slug = slug.trim().to_lowercase();
if slug.is_empty() || slug.len() > 64 {
@@ -994,7 +1002,6 @@ pub async fn handle_rpc_batch(
}
}
}
- Err((_, m)) => line_err(m, None),
}
}
RpcCommand::RoomGrant {
@@ -1002,17 +1009,28 @@ pub async fn handle_rpc_batch(
username,
capability,
} => {
- match verify_bearer_principal(&headers, &*state.reduced.read().await) {
+ let principal = {
+ let reduced = state.reduced.read().await;
+ verify_bearer_principal(&headers, &*reduced)
+ };
+ match principal {
Err((_, m)) => line_err(m, None),
Ok(principal) => {
- let reduced = state.reduced.read().await;
- if !reduced.user_has_cap(&room, &principal, ThreadCapability::Manage) {
+ let can_manage = {
+ let reduced = state.reduced.read().await;
+ reduced.user_has_cap(&room, &principal, ThreadCapability::Manage)
+ };
+ if !can_manage {
line_err("requires Manage capability", None)
} else {
match parse_username(&username) {
Err(msg) => line_err("invalid username", Some(msg)),
Ok(target) => {
- if !reduced.users_by_provider.values().any(|u| u == &target) {
+ let user_exists = {
+ let reduced = state.reduced.read().await;
+ reduced.users_by_provider.values().any(|u| u == &target)
+ };
+ if !user_exists {
line_err(format!("user @{target} not found"), None)
} else {
match parse_capability(&capability) {
diff --git a/server/tests/integration.rs b/server/tests/integration.rs
index 9162bd5bee84035e3908bfb9c8e201b7878ca339..b930120da09fe7d307f0411b84fb639fb8bd0b15 100644
--- a/server/tests/integration.rs
+++ b/server/tests/integration.rs
@@ -95,6 +95,23 @@ async fn test_healthz() {
assert_eq!(response.text().await.unwrap(), "ok");
}
+#[tokio::test]
+async fn test_room_create_private_rpc() {
+ let (addr, _tmp, _log, _handle) = create_test_server().await;
+ let client = reqwest::Client::new();
+ let batch = serde_json::json!([{
+ "RoomCreate": { "slug": "secret-project", "visibility": "private" }
+ }]);
+ let body = rpc_batch(&client, addr, Some(&test_bearer()), batch).await;
+ let line = &body["results"][0];
+ assert_eq!(line["ok"], true, "room create: {:?}", line);
+ let room_id = line["result"]["RoomCreated"]["room_id"].as_str().unwrap();
+ assert!(
+ room_id.contains("/secret-project"),
+ "expected room_id to contain slug, got {room_id}"
+ );
+}
+
#[tokio::test]
async fn test_index_page() {
// HTML routes are offline during the auth-v3 refactor.
diff --git a/test/auth.bb b/test/auth.bb
index 611e04f1806ef81d678a91f499597fe55f691dd7..a67cc1de763434176d2f68e419dd37a8cd328395 100644
--- a/test/auth.bb
+++ b/test/auth.bb
@@ -176,7 +176,7 @@
(assert! (= 200 (:status poll)) "pending-session poll returns 200")
(let [poll-json (json/parse-string (:body poll) true)]
(assert! (:complete poll-json) "pending session complete=true")
- (assert! (= "@bbuser" (:user poll-json)) "poll returns @bbuser")
+ (assert! (= "bbuser" (:user poll-json)) "poll returns stored username bbuser")
(assert! (clojure.string/starts-with? (:token poll-json) "slug_") "poll returns bearer token")
(println "\nwhoami…")
@@ -184,7 +184,7 @@
:headers {"Authorization" (str "Bearer " (:token poll-json))})]
(assert! (= 200 (:status who)) "whoami returns 200")
(let [who-json (json/parse-string (:body who) true)]
- (assert! (= "@bbuser" (:user who-json)) "whoami user is @bbuser"))))))
+ (assert! (= "bbuser" (:user who-json)) "whoami user is bbuser (stored form)"))))))
(println "\nCLI: identity start → OAuth → identity poll → whoami…")
(let [cli-home (str tmp-dir "/cli-home")
@@ -208,7 +208,7 @@
(str "identity poll exits 0 (stderr: " (:err poll-proc) ")"))
(let [poll-cli (json/parse-string (:out poll-proc) true)]
(assert! (= "complete" (:phase poll-cli)) "identity poll --json phase")
- (assert! (= "@cliuser" (:user poll-cli)) "CLI poll user")
+ (assert! (= "cliuser" (:user poll-cli)) "CLI poll user (stored form)")
(assert! (clojure.string/starts-with? (:token poll-cli) "slug_") "CLI poll token")
(let [token-path (str cli-home "/.config/slugsocial/token")]
(assert! (fs/exists? token-path) "token written under isolated HOME")
@@ -219,7 +219,7 @@
(assert! (zero? (:exit who-proc))
(str "whoami exits 0 (stderr: " (:err who-proc) ")"))
(let [who-cli (json/parse-string (:out who-proc) true)]
- (assert! (= "@cliuser" (:user who-cli)) "CLI whoami uses saved token"))))))))
+ (assert! (= "cliuser" (:user who-cli)) "CLI whoami uses saved token"))))))))
(finally
(when-some [s @!server] (common/kill-server s))
diff --git a/test/common.bb b/test/common.bb
index ebb16c615a8b40e8830b5d5765d1e935a45538d0..4ed450377cdbb020f5ff164a812dfbbfc23c0f47 100644
--- a/test/common.bb
+++ b/test/common.bb
@@ -78,9 +78,20 @@
(defn start-server
"Start the slugsocial-server binary with the given env map.
- Returns the babashka.process map."
- [server-bin env-map]
- (p/process [server-bin] {:out :inherit :err :inherit :env env-map}))
+ Returns the babashka.process map.
+
+ When `log-file` (string path) is provided, stdout and stderr are appended there
+ instead of inheriting the parent descriptors. Inheriting shared pipes while the
+ parent blocks on HTTP I/O can fill the pipe buffer and deadlock the server on log writes."
+ ([server-bin env-map]
+ (start-server server-bin env-map nil))
+ ([server-bin env-map log-file]
+ (p/process [server-bin]
+ (if log-file
+ ;; Two string paths (same file): babashka.process can deref the process cleanly.
+ ;; :err :out + ProcessBuilder$Redirect breaks stream copying in deref/kill-server.
+ {:env env-map :out log-file :err log-file}
+ {:out :inherit :err :inherit :env env-map}))))
(defn kill-server
"Forcibly kill a server process (babashka.process map) and wait for it to exit."
diff --git a/test/grants.bb b/test/grants.bb
index 7066c1f2a57f39a362052f8524206dccf37bb7b1..793ba216f2de76a77eb20a76d08403db07ff411b 100644
--- a/test/grants.bb
+++ b/test/grants.bb
@@ -35,13 +35,14 @@
(defn- http-client []
(-> (java.net.http.HttpClient/newBuilder)
(.followRedirects java.net.http.HttpClient$Redirect/ALWAYS)
+ (.connectTimeout (java.time.Duration/ofSeconds 15))
(.build)))
(defn- http-get [url & {:keys [headers]}]
(let [b (java.net.http.HttpRequest/newBuilder (java.net.URI/create url))]
(doseq [[k v] (or headers {})]
(.header b k v))
- (let [req (-> b (.GET) (.build))
+ (let [req (-> b (.timeout (java.time.Duration/ofSeconds 60)) (.GET) (.build))
resp (.send (http-client) req (java.net.http.HttpResponse$BodyHandlers/ofString))]
{:status (.statusCode resp) :body (.body resp)})))
@@ -52,6 +53,7 @@
(doseq [[k v] (or headers {})]
(.header b k v))
(let [req (-> b
+ (.timeout (java.time.Duration/ofSeconds 60))
(.POST (java.net.http.HttpRequest$BodyPublishers/ofString body))
(.build))
resp (.send (http-client) req (java.net.http.HttpResponse$BodyHandlers/ofString))]
@@ -67,6 +69,7 @@
b (java.net.http.HttpRequest/newBuilder (java.net.URI/create url))]
(.header b "Content-Type" "application/x-www-form-urlencoded")
(let [req (-> b
+ (.timeout (java.time.Duration/ofSeconds 60))
(.POST (java.net.http.HttpRequest$BodyPublishers/ofString pairs))
(.build))
resp (.send (http-client) req (java.net.http.HttpResponse$BodyHandlers/ofString))]
Hardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.