Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(runtime): add tenant runtime module

Steven Enamakel896d21feae0e
diff --git a/crates/openhuman-core/src/core/runtime/tenant.rs b/crates/openhuman-core/src/core/runtime/tenant.rs
new file mode 100644
index 0000000000..3fb7259385
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/tenant.rs
@@ -0,0 +1,209 @@
+//! Who a piece of work runs for, and how per-tenant tables key on it.
+//!
+//! A [`Tenant`] is the pair the ambient [`CoreContext`] carries:
+//!
+//! - `profile` — the SaaS user profile. It is the isolation boundary: storage
+//! scopes, the `/events` filter, the cost ledger and every in-process table
+//! that is keyed by a caller-chosen id (thread ids, session ids) key on it.
+//! - `agent` — the agent inside that profile (`CoreContext::session_agent`).
+//! `None` is the default orchestrator, as on the desktop.
+//!
+//! [`current_tenant`] resolves it. In SaaS only the task's own scope counts
+//! ([`CoreContext::scoped`]): work that lost its scope gets [`NoTenant`] and
+//! must fail closed, never fall back to the operator's default context. A
+//! single-user process keeps reading [`CoreContext::current`], so nothing
+//! changes there.
+//!
+//! [`tenant_key`] and [`session_key`] are the two encodings. Both are
+//! injective, and both leave today's desktop keys untouched: with no profile
+//! and no agent a tenant key is the bare id.
+
+use std::sync::Arc;
+
+use super::CoreContext;
+
+/// The tenant (profile) and the agent inside it that work runs for.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
+pub struct Tenant {
+ /// The SaaS profile; `None` on the desktop and for embedded agents.
+ pub profile: Option<String>,
+ /// The agent inside the profile; `None` for the default orchestrator.
+ pub agent: Option<String>,
+}
+
+impl Tenant {
+ /// The tenant `ctx` serves.
+ pub fn of(ctx: &CoreContext) -> Self {
+ Self {
+ profile: ctx.profile().map(str::to_owned),
+ agent: ctx.session_agent().map(str::to_owned),
+ }
+ }
+
+ /// This tenant without its agent: for tables that isolate profiles from
+ /// each other but are shared by the agents of one profile (and so, on the
+ /// desktop, keep their bare-id keys for embedded agents too).
+ pub fn profile_only(&self) -> Self {
+ Self {
+ profile: self.profile.clone(),
+ agent: None,
+ }
+ }
+}
+
+/// SaaS work that runs with no task scope: it has no tenant and must not act.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NoTenant;
+
+impl std::fmt::Display for NoTenant {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("no tenant scope in SaaS mode; refusing to act as the operator")
+ }
+}
+
+impl std::error::Error for NoTenant {}
+
+/// The context the tenant is read from: the task's own scope in SaaS, the
+/// ambient context (falling back to the process default) otherwise.
+pub fn context_in(saas: bool) -> Option<Arc<CoreContext>> {
+ if saas {
+ CoreContext::scoped()
+ } else {
+ CoreContext::current()
+ }
+}
+
+/// The tenant of the calling task.
+///
+/// # Errors
+///
+/// [`NoTenant`] in SaaS when the task carries no scope.
+pub fn current_tenant() -> Result<Tenant, NoTenant> {
+ let saas = super::is_saas();
+ tenant_in(saas, context_in(saas).as_deref())
+}
+
+/// [`current_tenant`] as a pure function of the mode and the resolved context.
+///
+/// # Errors
+///
+/// [`NoTenant`] when `saas` and there is no context.
+pub fn tenant_in(saas: bool, ctx: Option<&CoreContext>) -> Result<Tenant, NoTenant> {
+ match ctx {
+ Some(ctx) => Ok(Tenant::of(ctx)),
+ None if saas => Err(NoTenant),
+ None => Ok(Tenant::default()),
+ }
+}
+
+/// [`current_tenant`], or for a SaaS task with no scope a tenant no other
+/// work can share: a fresh, random profile. For infallible key builders whose
+/// tables are already per-context (an unscoped SaaS task gets throwaway state
+/// slots, see [`current_slot`](super::current_slot)), so the key can only miss.
+pub fn current_tenant_or_isolated(site: &str) -> Tenant {
+ current_tenant().unwrap_or_else(|NoTenant| {
+ log::warn!("[tenant] {site}: no tenant scope in SaaS; using an isolated key");
+ Tenant {
+ profile: Some(format!("\u{0}unscoped:{}", uuid::Uuid::new_v4().simple())),
+ agent: None,
+ }
+ })
+}
+
+/// Profile prefix byte of a [`tenant_key`].
+const PROFILE_MARK: char = '\u{1e}';
+/// Agent prefix byte of a [`tenant_key`] (and of the web-chat keys before it).
+const AGENT_MARK: char = '\u{1f}';
+
+/// Injective encoding of `(tenant, id)` for in-process tables keyed by a
+/// caller-chosen id.
+///
+/// - no profile, no agent: the bare `id` (today's desktop key), except that an
+/// id starting with a mark byte gets `\x1f` prepended so it can never look
+/// like a scoped key;
+/// - an agent: `\x1f<agent byte length>:<agent><id>` (today's embedded-agent
+/// web-chat key);
+/// - a profile: `\x1e<profile byte length>:<profile>` followed by the key of
+/// `(agent, id)` as above.
+pub fn tenant_key(tenant: &Tenant, id: &str) -> String {
+ let inner = agent_key(tenant.agent.as_deref(), id);
+ match &tenant.profile {
+ Some(profile) => format!("{PROFILE_MARK}{}:{profile}{inner}", profile.len()),
+ None => inner,
+ }
+}
+
+fn agent_key(agent: Option<&str>, id: &str) -> String {
+ match agent {
+ Some(agent) => format!("{AGENT_MARK}{}:{agent}{id}", agent.len()),
+ None if id.starts_with([PROFILE_MARK, AGENT_MARK]) => format!("{AGENT_MARK}{id}"),
+ None => id.to_string(),
+ }
+}
+
+/// The tenant and id a [`tenant_key`] was built from.
+pub fn split_key(key: &str) -> Option<(Tenant, &str)> {
+ let (profile, rest) = match key.strip_prefix(PROFILE_MARK) {
+ Some(rest) => {
+ let (profile, rest) = take_counted(rest)?;
+ (Some(profile.to_owned()), rest)
+ }
+ None => (None, key),
+ };
+ let (agent, id) = match rest.strip_prefix(AGENT_MARK) {
+ Some(escaped) if escaped.starts_with([PROFILE_MARK, AGENT_MARK]) => (None, escaped),
+ Some(scoped) => {
+ let (agent, id) = take_counted(scoped)?;
+ (Some(agent.to_owned()), id)
+ }
+ // A bare id never starts with a profile mark: that would be ambiguous.
+ None if rest.starts_with(PROFILE_MARK) => return None,
+ None => (None, rest),
+ };
+ Some((Tenant { profile, agent }, id))
+}
+
+/// The id a [`tenant_key`] was built from, ignoring its tenant.
+pub fn id_of_key(key: &str) -> Option<&str> {
+ split_key(key).map(|(_, id)| id)
+}
+
+/// `<len>:<value><rest>` -> `(value, rest)`.
+fn take_counted(raw: &str) -> Option<(&str, &str)> {
+ let (len, tail) = raw.split_once(':')?;
+ if len.is_empty() || !len.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ let len: usize = len.parse().ok()?;
+ Some((tail.get(..len)?, tail.get(len..)?))
+}
+
+/// The agent id a host session store keeps this tenant's conversations under.
+///
+/// Without a profile it is the agent, or
+/// [`DEFAULT_AGENT`](crate::agent::session_store::DEFAULT_AGENT) — today's
+/// keys. With one it is `<profile>~<agent|default>`, the profile
+/// percent-escaped (`%` and `~`) so the first `~` always ends it. An agent
+/// named `default` is the default agent.
+pub fn session_key(tenant: &Tenant) -> String {
+ let agent = tenant
+ .agent
+ .as_deref()
+ .unwrap_or(crate::agent::session_store::DEFAULT_AGENT);
+ match &tenant.profile {
+ Some(profile) => format!("{}~{agent}", escape_profile(profile)),
+ None => agent.to_string(),
+ }
+}
+
+fn escape_profile(profile: &str) -> String {
+ profile.replace('%', "%25").replace('~', "%7E")
+}
+
+#[cfg(test)]
+#[path = "tenant_tests.rs"]
+mod tests;
+
+#[cfg(test)]
+#[path = "tenant_proptest_tests.rs"]
+mod proptest_tests;