Files
huskies/server/src/crdt_state/write/migrations.rs
T
2026-05-12 17:55:12 +00:00

184 lines
6.6 KiB
Rust

//! Name and story-ID migration helpers for pipeline items.
//!
//! Contains one-time startup migrations that backfill the `name` field from
//! story ID slugs and rewrite slug-form story IDs to numeric-only form.
use bft_json_crdt::json_crdt::{CrdtNode, JsonValue};
use super::super::state::{apply_and_persist, get_crdt, rebuild_index};
use crate::slog;
/// Derive a human-readable name from a story ID's slug component.
///
/// Strips the numeric prefix and item-type prefix (story/bug/spike/refactor),
/// replaces underscores with spaces, and capitalises the first letter.
///
/// Examples:
/// - `"729_story_store_story_name"` → `"Store story name"`
/// - `"4_bug_login_crash"` → `"Login crash"`
/// - `"10_spike_arch_review"` → `"Arch review"`
pub fn name_from_story_id(story_id: &str) -> String {
// Strip the leading digits then the first underscore: "729_story_..." → "story_..."
let after_num = story_id.trim_start_matches(|c: char| c.is_ascii_digit());
let after_num = after_num.strip_prefix('_').unwrap_or(after_num);
// Strip the item-type prefix.
let slug = after_num
.strip_prefix("story_")
.or_else(|| after_num.strip_prefix("bug_"))
.or_else(|| after_num.strip_prefix("spike_"))
.or_else(|| after_num.strip_prefix("refactor_"))
.unwrap_or(after_num);
// Replace underscores with spaces.
let spaced = slug.replace('_', " ");
// Capitalise the first character.
let mut chars = spaced.chars();
match chars.next() {
None => String::new(),
Some(first) => {
let mut name = first.to_uppercase().to_string();
name.push_str(chars.as_str());
name
}
}
}
/// Extract the numeric-only ID from a slug-form story ID, if applicable.
///
/// Returns `Some("664")` for `"664_story_my_feature"`, and `None` for IDs
/// that are already numeric-only (`"664"`) or have no valid numeric prefix.
#[allow(clippy::string_slice)] // idx comes from find('_') → always a char boundary
pub(super) fn numeric_id_from_slug(story_id: &str) -> Option<String> {
// Already numeric-only — no migration needed.
if story_id.chars().all(|c: char| c.is_ascii_digit()) {
return None;
}
// Must have a non-empty numeric segment before the first underscore.
let idx = story_id.find('_')?;
let prefix = &story_id[..idx];
if prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_digit()) {
return None;
}
Some(prefix.to_string())
}
/// Migrate existing story IDs from slug form (`664_story_my_feature`) to
/// numeric-only form (`664`) in the in-memory CRDT, persisting a signed op
/// for each updated register so the change survives restarts.
///
/// Returns the list of `(old_id, new_id)` pairs that were actually migrated.
/// Callers should use this list to rename downstream filesystem artifacts
/// (worktree directories, git branches, log directories).
///
/// Items whose `story_id` is already numeric-only are left untouched.
/// Items where the target numeric ID is already in use are skipped to avoid
/// conflicts. Running this migration repeatedly is safe — subsequent calls
/// on already-migrated state are no-ops.
pub fn migrate_story_ids_to_numeric() -> Vec<(String, String)> {
let Some(state_mutex) = get_crdt() else {
return Vec::new();
};
// First pass: collect (index, old_id, new_id) while holding the lock.
let migrations: Vec<(usize, String, String)> = {
let Ok(state) = state_mutex.lock() else {
return Vec::new();
};
let existing_ids: std::collections::HashSet<String> = state.index.keys().cloned().collect();
state
.index
.iter()
.filter_map(|(story_id, &idx)| {
let numeric = numeric_id_from_slug(story_id)?;
// Skip if the target numeric ID is already occupied.
if existing_ids.contains(&numeric) {
return None;
}
Some((idx, story_id.clone(), numeric))
})
.collect()
};
if migrations.is_empty() {
return Vec::new();
}
// Second pass: apply story_id register updates.
let Ok(mut state) = state_mutex.lock() else {
return Vec::new();
};
let mut result = Vec::new();
for (idx, old_id, new_id) in migrations {
apply_and_persist(&mut state, |s| {
s.crdt.doc.items[idx].story_id.set(new_id.clone())
});
result.push((old_id, new_id));
}
// Rebuild the index so all downstream reads use the new numeric IDs.
state.index = rebuild_index(&state.crdt);
let count = result.len();
slog!("[crdt] Migrated {count} story IDs from slug form to numeric");
result
}
/// Backfill the `name` CRDT field for pipeline items that have an empty name.
///
/// Iterates over all items in the in-memory CRDT. For each item whose `name`
/// register is empty, derives a human-readable name from the story ID slug
/// (see [`name_from_story_id`]) and writes it via a signed CRDT op.
///
/// This is a one-time startup migration: items created before the `name` field
/// was consistently populated will gain a name on the next server start.
/// Items that already have a non-empty name are left untouched.
pub fn migrate_names_from_slugs() {
let Some(state_mutex) = get_crdt() else {
return;
};
// First pass: collect (index, derived_name) pairs for items missing a name.
let migrations: Vec<(usize, String)> = {
let Ok(state) = state_mutex.lock() else {
return;
};
state
.index
.iter()
.filter_map(|(story_id, &idx)| {
let item = &state.crdt.doc.items[idx];
// Skip items that already have a name.
let already_named =
matches!(item.name.view(), JsonValue::String(ref s) if !s.is_empty());
if already_named {
return None;
}
let name = name_from_story_id(story_id);
if name.is_empty() {
return None;
}
Some((idx, name))
})
.collect()
};
if migrations.is_empty() {
return;
}
// Second pass: apply all name writes while holding the lock.
let Ok(mut state) = state_mutex.lock() else {
return;
};
let count = migrations.len();
for (idx, name) in migrations {
apply_and_persist(&mut state, |s| s.crdt.doc.items[idx].name.set(name.clone()));
}
slog!("[crdt] Migrated names for {count} items from story ID slugs");
}