fix(app): channel sync keeps a new channel's empty fields out on retry, orders saves, drops stale lookups

- A rate-limited edit of a newly registered channel is retried with the
  same "never clear Discord with an empty field" rule (it was retried as
  an existing channel and cleared the topic).
- Channel edits go one at a time, and Discord's form of the name is
  written back only while the settings still hold the name that was sent,
  so a slow answer to an earlier save never overwrites a later one.
- The chat channel screen drops a Discord name/topic lookup that answers
  after the ID was changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 19:49:47 +09:00
parent 0d9c6ec984
commit d4bd4acfe9
3 changed files with 80 additions and 22 deletions

View File

@@ -72,13 +72,18 @@ pub struct Syncer {
api: Arc<dyn ChannelApi>,
settings_file: PathBuf,
status: Mutex<HashMap<u64, SyncState>>,
/// Channels with a retry already waiting (another save while waiting adds none).
retrying: Mutex<std::collections::HashSet<u64>>,
/// Channels with a retry already waiting (another save while waiting adds none), and whether
/// that channel was new (so the retry still keeps empty fields out).
retrying: Mutex<HashMap<u64, bool>>,
/// One channel edit at a time: a later save waits for an earlier one, so a slow answer to the
/// earlier never lands after the later.
edit_lock: tokio::sync::Mutex<()>,
}
impl Syncer {
pub fn new(api: Arc<dyn ChannelApi>, settings_file: PathBuf) -> Arc<Self> {
Arc::new(Self { api, settings_file, status: Mutex::default(), retrying: Mutex::default() })
Arc::new(Self { api, settings_file, status: Mutex::default(), retrying: Mutex::default(),
edit_lock: tokio::sync::Mutex::new(()) })
}
/// A channel's name and topic on Discord now (the screens fill a newly registered channel with them).
@@ -108,9 +113,10 @@ impl Syncer {
}
async fn sync_one(self: &Arc<Self>, c: &ChatChannelSettings, is_new: bool) -> SyncState {
let _one_at_a_time = self.edit_lock.lock().await;
let current = match self.api.info(c.id).await {
Ok(i) => i,
Err(e) => return self.refused(c.id, e),
Err(e) => return self.refused(c.id, e, is_new),
};
let keep = |v: &str| !(is_new && v.trim().is_empty());
let name = (keep(&c.name) && c.name != current.name).then_some(c.name.as_str());
@@ -121,25 +127,31 @@ impl Syncer {
match self.api.edit(c.id, name, topic).await {
Ok(stored) => {
if keep(&c.name) && stored.name != c.name {
self.write_name(c.id, &stored.name);
self.write_name(c.id, &c.name, &stored.name);
}
crate::info_log!("chat", "channel {} name and topic updated on Discord", c.id);
SyncState::Applied { name: stored.name }
}
Err(e) => self.refused(c.id, e),
Err(e) => self.refused(c.id, e, is_new),
}
}
fn refused(self: &Arc<Self>, id: u64, e: ApiError) -> SyncState {
fn refused(self: &Arc<Self>, id: u64, e: ApiError, is_new: bool) -> SyncState {
match e {
ApiError::RateLimited(wait) => {
crate::info_log!("chat", "channel {id}: Discord asks to wait {}s before the next edit", wait.as_secs());
if self.retrying.lock().unwrap().insert(id) {
let first = {
let mut r = self.retrying.lock().unwrap();
let first = !r.contains_key(&id);
*r.entry(id).or_insert(is_new) |= is_new;
first
};
if first {
let me = self.clone();
tokio::spawn(async move {
tokio::time::sleep(wait).await;
me.retrying.lock().unwrap().remove(&id);
me.retry(id).await;
let is_new = me.retrying.lock().unwrap().remove(&id).unwrap_or(false);
me.retry(id, is_new).await;
});
}
SyncState::Pending { retry_in_sec: wait.as_secs().max(1) }
@@ -152,11 +164,11 @@ impl Syncer {
}
/// Try a pending channel again with what the settings hold now.
async fn retry(self: &Arc<Self>, id: u64) {
async fn retry(self: &Arc<Self>, id: u64, is_new: bool) {
let Ok(settings) = crate::settings::load_settings(&self.settings_file) else { return };
match settings.chat_channels.into_iter().find(|c| c.id == id && c.sync_discord) {
Some(c) => {
let state = self.sync_one(&c, false).await;
let state = self.sync_one(&c, is_new).await;
self.status.lock().unwrap().insert(id, state);
}
None => {
@@ -165,15 +177,21 @@ impl Syncer {
}
}
/// Show Discord's form of the name (spaces become `-`) in the app too.
fn write_name(&self, id: u64, name: &str) {
/// Show Discord's form of the name (spaces become `-`) in the app too, only while the settings
/// still hold the name that was sent (a later save keeps its own).
fn write_name(&self, id: u64, sent: &str, name: &str) {
let Ok(view) = crate::settings_edit::view(&self.settings_file) else { return };
let Some(Value::Array(mut list)) = view.get("chatChannels").cloned() else { return };
let mut changed = false;
for c in &mut list {
if c["id"].as_str() == Some(id.to_string().as_str()) {
if c["id"].as_str() == Some(id.to_string().as_str()) && c["name"].as_str() == Some(sent) {
c["name"] = json!(name);
changed = true;
}
}
if !changed {
return;
}
let mut changes = serde_json::Map::new();
changes.insert("chatChannels".into(), Value::Array(list));
if let Err(e) = crate::settings_edit::apply(&self.settings_file, &changes) {
@@ -249,6 +267,8 @@ mod tests {
forbidden: Vec<u64>,
limited: Mutex<u32>,
edits: Mutex<Vec<(u64, Option<String>, Option<String>)>>,
/// How long each next edit takes (the first save's slow answer).
delays: Mutex<Vec<Duration>>,
}
#[async_trait]
impl ChannelApi for FakeDiscord {
@@ -259,6 +279,10 @@ mod tests {
if self.forbidden.contains(&id) {
return Err(ApiError::Failed("봇에 이 채널의 채널 관리 권한이 없습니다".into()));
}
let delay = { let mut d = self.delays.lock().unwrap(); if d.is_empty() { None } else { Some(d.remove(0)) } };
if let Some(d) = delay {
tokio::time::sleep(d).await;
}
{
let mut l = self.limited.lock().unwrap();
if *l > 0 {
@@ -375,4 +399,33 @@ mod tests {
s.sync(vec![ch(B, "잡담", "아무 말")], &[]).await;
assert!(d.edits.lock().unwrap().is_empty(), "nothing differs from Discord: no edit");
}
#[tokio::test]
async fn a_retried_new_channel_still_never_clears_discord_with_an_empty_field() {
let d = fake(vec![], 1);
let file = settings_with(&[ch(B, "잡담 2", "")]);
let s = Syncer::new(d.clone(), file);
let out = s.sync(vec![ch(B, "잡담 2", "")], &[]).await;
assert!(matches!(out[0].1, SyncState::Pending { .. }), "{out:?}");
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(s.status()[&B], SyncState::Applied { name: "잡담-2".into() });
assert_eq!(d.channels.lock().unwrap()[&B].topic, "아무 말", "the retry kept the empty description out");
}
#[tokio::test]
async fn a_slow_first_save_never_overwrites_a_later_one() {
let d = fake(vec![], 0);
*d.delays.lock().unwrap() = vec![Duration::from_millis(300)];
let file = settings_with(&[ch(A, "일정 표", "")]);
let s = Syncer::new(d.clone(), file.clone());
let s1 = s.clone();
let first = tokio::spawn(async move { s1.sync(vec![ch(A, "일정 표", "")], &[ch(A, "일정", "")]).await });
tokio::time::sleep(Duration::from_millis(50)).await;
// Saved again while Discord still answers the first edit.
std::fs::write(&file, json!({"chatChannels": [{"id": A.to_string(), "name": "회의", "description": ""}]}).to_string()).unwrap();
s.sync(vec![ch(A, "회의", "")], &[ch(A, "일정 표", "")]).await;
first.await.unwrap();
assert_eq!(d.channels.lock().unwrap()[&A].name, "회의", "Discord ends with the later save");
assert_eq!(crate::settings::load_settings(&file).unwrap().chat_channels[0].name, "회의", "and so does the app");
}
}