Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 101 additions & 4 deletions pkgs/id/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1068,6 +1068,55 @@ pub fn start_server_config(path: &Path) -> Result<StartedServerConfig> {
})
}

/// The directory journal the server config provisioning persists
/// its accounts in (#5119 slice 3): `directory.jsonl` beside the
/// groups log, the same layout a world directory uses.
#[cfg(feature = "world")]
fn server_config_directory_path(groups_log: &Path) -> PathBuf {
groups_log.with_file_name("directory.jsonl")
Comment on lines +1075 to +1076

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist configured accounts into the live world's directory

When serving a durable world with --server-config and the default groups-log path, this writes configured accounts to ./directory.jsonl, but ServeWorlds::open_world loads .id-worlds/<name>/directory.jsonl through world_store::open_world (world_store.rs:540–545). The provisioned directory is never passed into that live world. Consequently, startup reports successful account provisioning, yet those accounts remain absent from the live directory and directory_view.rs:68–71 treats their keys as anonymous. Resolve provisioning against the directory actually used by the serving world, or explicitly wire the provisioned directory into its state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in PR #8413: slice 3 persisted configured accounts beside the groups log, but the live world loads .id-worlds//directory.jsonl. cmd_serve now seeds the default (startup) world directory from the loaded config via the extracted Provisioned::apply_users, idempotently; regression test seed_world_directory_provisions_configured_accounts covers it (serve suite 47/47, server_config suite 57/57 locally).

}

/// Load the operator server config at `path` and run startup
/// provisioning into the live serving state (#5119 slice 3): the
/// provisioned accounts go into the journaled directory beside the
/// groups log and the preformed group events into the groups log
/// itself — the same state live serving folds and replays — so a
/// restart loads them back, provisioning skips them, and the report
/// names no new creations.
///
/// # Errors
///
/// Fails on the same startup contract as [`start_server_config`],
/// and when the persisted directory or groups log cannot be opened
/// or written.
#[cfg(feature = "world")]
pub fn start_server_config_persisted(
path: &Path,
groups_log: &Path,
) -> Result<StartedServerConfig> {
let config = crate::server_config::ServerConfig::load(path)
.map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?;
let directory = crate::directory::Directory::open(&server_config_directory_path(groups_log))?;
let mut log = crate::groups::log::GroupLog::open(groups_log)?;
let already = log.events().len();
let mut provisioned =
crate::server_config::Provisioned::from_parts(directory, log.events().to_vec());
let report = provisioned
.apply(&config)
.map_err(|error| anyhow::anyhow!("server config {}: {error}", path.display()))?;
// Seed only the events this start added: the rest are the
// from_parts state itself, and re-checking them on every
// restart would rescan the whole log history.
for event in &provisioned.events()[already..] {
log.record_preformed(event)?;
}
Ok(StartedServerConfig {
config,
provisioned,
report,
})
}

/// The pull policy the live event-sync gate serves under (#5119): the server
/// config's `[policy] pull_policy` when a config was loaded, else the code
/// default ([`crate::pull_policy::PullPolicy::Open`]), so a `serve` without
Expand Down Expand Up @@ -1193,7 +1242,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> {
#[cfg(feature = "world")]
let started_server_config = match &server_config {
Some(path) => {
let started = start_server_config(path)?;
let started = start_server_config_persisted(path, &groups_log)?;
status!(
"server config: loaded {} (provisioned {} user(s), {} group(s), {} member(s))",
path.display(),
Expand Down Expand Up @@ -1491,9 +1540,13 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> {
// The world protocol instance is shared between its ALPN registration and
// the meta protocol, which exposes its abuse counters (#4918).
#[cfg(feature = "world")]
let world_protocol = world_hub
.as_ref()
.map(|hub| world_protocol_for(hub.clone(), *node_id.as_bytes(), started_server_config.as_ref()));
let world_protocol = world_hub.as_ref().map(|hub| {
world_protocol_for(
hub.clone(),
*node_id.as_bytes(),
started_server_config.as_ref(),
)
});

#[cfg(feature = "world")]
let abuse_handle = world_protocol
Expand Down Expand Up @@ -3515,6 +3568,50 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "world")]
#[test]
fn start_server_config_persisted_survives_a_restart() {
let dir = serve_config_dir("persisted");
let path = dir.join("server.toml");
let groups_log = dir.join("groups.jsonl");
// Real Ed25519 public keys, as in
// start_server_config_applies_provisioning.
let id = |n: u8| {
ed25519_dalek::SigningKey::from_bytes(&[n; 32])
.verifying_key()
.to_bytes()
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>()
};
std::fs::write(
&path,
format!(
"[[users]]\nkey = \"ann\"\nid = \"{}\"\n\n[[users]]\nkey = \"bo\"\nid = \"{}\"\n\n\
[[groups]]\nkey = \"team\"\nname = \"Team\"\ncreator = \"ann\"\n\n\
[[groups.members]]\nuser = \"bo\"\nrole = \"write\"\n",
id(1),
id(2)
),
)
.unwrap();
let started = start_server_config_persisted(&path, &groups_log).unwrap();
assert_eq!(started.report.users_created, 2);
assert_eq!(started.report.groups_created, 1);
assert_eq!(started.report.members_added, 1);
drop(started);
// A restart over the same persisted state loads the accounts
// and group events back and creates nothing: no recreations,
// no new-creation reports (#5119 slice 3 acceptance).
let restarted = start_server_config_persisted(&path, &groups_log).unwrap();
assert_eq!(restarted.report, crate::server_config::Report::default());
assert!(restarted.provisioned.directory().account(&id(1)).is_some());
assert!(restarted.provisioned.directory().account(&id(2)).is_some());
// The create event plus the one member add.
assert_eq!(restarted.provisioned.events().len(), 2);
let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "world")]
#[test]
fn start_server_config_fails_startup_on_a_malformed_file() {
Expand Down
58 changes: 58 additions & 0 deletions pkgs/id/src/groups/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,34 @@ impl GroupLog {
Ok(Recorded { event: id, outcome })
}

/// Records an event that was already formed elsewhere, keeping its
/// ID and its place in its own chain: the seeding path for events a
/// config provisioned (#5119 slice 3). An event whose ID the log
/// already holds is skipped and changes nothing, so seeding the
/// same events on every start is a no-op after the first.
///
/// # Errors
///
/// Fails if the events cannot be folded, or the file cannot be
/// written. Nothing is written when the fold fails.
pub fn record_preformed(&mut self, event: &Event) -> Result<Option<Recorded>> {
if self.events.iter().any(|held| held.id == event.id) {
return Ok(None);
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
let mut next = self.events.clone();
next.push(event.clone());
let outcome = fold(&next)?
.outcome(&event.id)
.cloned()
.context("the fold did not decide the event")?;
self.append(event)?;
self.events = next;
Ok(Some(Recorded {
event: event.id,
outcome,
}))
}

/// The IDs no event names in its `after`. A new event names these, so it comes after all of them.
fn heads(&self) -> Vec<Hash> {
let named: BTreeSet<Hash> = self
Expand Down Expand Up @@ -376,6 +404,36 @@ mod tests {
})
}

#[test]
fn test_record_preformed_seeds_once_and_then_skips() {
let dir = TempDir::new().unwrap();
let path = dir.path().join(FILE_NAME);
// Form the event in a scratch log, as provisioning forms it
// away from the log it will seed.
let scratch = dir.path().join("scratch.jsonl");
let mut formed = GroupLog::open(&scratch).unwrap();
let recorded = formed.record(OWNER, None, create_body()).unwrap();
let event = formed.events()[0].clone();

let mut log = GroupLog::open(&path).unwrap();
let seeded = log.record_preformed(&event).unwrap().unwrap();
assert_eq!(seeded.event, recorded.event);
assert_eq!(seeded.outcome, Outcome::Applied);
// Seeding the same event again changes nothing.
assert!(log.record_preformed(&event).unwrap().is_none());
assert_eq!(log.events().len(), 1);
// And the seeded event is what a reopen reads back.
let reopened = GroupLog::open(&path).unwrap();
assert_eq!(reopened.events(), log.events());
assert!(
reopened
.projection()
.unwrap()
.group(&recorded.event)
.is_some()
);
}

#[test]
fn test_a_recorded_event_is_read_back_and_folds_the_same() {
let dir = TempDir::new().unwrap();
Expand Down
66 changes: 56 additions & 10 deletions pkgs/id/src/server_config/provision.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,20 @@ impl Provisioned {
}
}

/// Starts from state a previous run persisted: the accounts in
/// `directory` and the group `events` already recorded (#5119
/// slice 3). [`Provisioned::apply`] skips what already exists, so
/// a restart over the same persisted state creates nothing and
/// reports nothing.
#[must_use]
pub fn from_parts(directory: Directory, events: Vec<Event>) -> Self {
Self {
directory,
events,
create: CreateRule::Anyone,
}
}

/// The accounts.
#[must_use]
pub const fn directory(&self) -> &Directory {
Expand Down Expand Up @@ -134,7 +148,9 @@ impl Provisioned {
}

/// Creates the accounts and groups the config names, and adds their members. What already
/// exists is skipped, so a second run of the same config changes nothing.
/// exists is skipped, so a second run of the same config changes nothing. A group recorded
/// only in part (an earlier run stopped mid-group) is completed with exactly its missing
/// events, so interrupted provisioning resumes instead of succeeding over a half-made group.
///
/// # Errors
///
Expand All @@ -159,23 +175,30 @@ impl Provisioned {
report.users_created += 1;
}
for group in config.groups() {
if self.events.iter().any(|event| event.id == group.id) {
let batch = group_events(group);
let missing: Vec<Event> = batch
.iter()
.filter(|event| !self.events.iter().any(|held| held.id == event.id))
.cloned()
.collect();
if missing.is_empty() {
continue;
}
if !config
.create_rule()
.allows(&group.creator, &self.projection()?)
let creates = missing.iter().any(|event| event.id == group.id);
if creates
&& !config
.create_rule()
.allows(&group.creator, &self.projection()?)
{
return Err(ProvisionError::NotAllowed {
group: group.key.clone(),
creator: hex_encode(&group.creator),
});
}
let batch = group_events(group);
let mut next = self.events.clone();
next.extend(batch.iter().cloned());
next.extend(missing.iter().cloned());
let projection = fold(&next)?;
for event in &batch {
for event in &missing {
if let Some(Outcome::Refused(refusal)) = projection.outcome(&event.id) {
return Err(ProvisionError::Refused {
group: group.key.clone(),
Expand All @@ -184,8 +207,10 @@ impl Provisioned {
}
}
self.events = next;
report.groups_created += 1;
report.members_added += group.members.len();
if creates {
report.groups_created += 1;
}
report.members_added += missing.iter().filter(|event| event.id != group.id).count();
}
Ok(report)
}
Expand Down Expand Up @@ -568,6 +593,27 @@ mod tests {
}
}

#[test]
fn test_an_interrupted_group_is_completed_by_the_next_apply() {
// The first run recorded the create and stopped before the
// member adds: the next apply adds exactly the missing
// events and reports them, without recreating the group.
let text = config(TEAM);
let (state, result) = apply(&text);
result.unwrap();
let full = state.events().to_vec();
let mut resumed = Provisioned::from_parts(state.directory().clone(), full[..1].to_vec());
let parsed = ServerConfig::parse(&text).unwrap();
let report = resumed.apply(&parsed).unwrap();
assert_eq!(report.users_created, 0);
assert_eq!(report.groups_created, 0);
assert_eq!(report.members_added, 2);
assert_eq!(resumed.events(), full.as_slice());
// And a third run is a no-op again.
let again = resumed.apply(&parsed).unwrap();
assert_eq!(again, Report::default());
}

#[test]
fn test_a_create_recorded_after_the_start_meets_the_create_rule() {
// Only ann may create. A create by anyone else that arrives after the start is refused, as
Expand Down
Loading