Skip to content
Open
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
8 changes: 8 additions & 0 deletions changelog.d/396.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
- Worker launches no longer hold the installation-wide licence lock across the launcher
call, and take no lock when the licence sets no worker limit, so one slow launcher no
longer serialises every launch or makes other replicas answer `409 license limit is busy`
(#396). The in-process wait for the lock now counts toward the same 10-second deadline.
Under a limit, re-activating an agent reads its status under the lock, a duplicate
request with the same idempotency key at the exact execution limit gets the first
request's execution instead of `402`, and a first OIDC login that links a pre-provisioned
user no longer needs a free seat. See [Licensing](docs/guide/licensing.md).
28 changes: 27 additions & 1 deletion crates/orbit-api/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,14 @@ async fn resolve_oidc(state: &AppState, token: Option<&str>) -> Result<AuthConte
}
// The only API path that provisions new users. Count all orgs and hold the
// lock until the insert so concurrent first logins cannot exceed the seats.
let _seat_limit = state.seat_limit_guard().await?;
// A login that links a pre-provisioned user (same email, decided under the
// lock) adds no seat, so it is not refused at the limit (#396).
let seat_limit = state.license_limit_lock("seats").await?;
if seat_limit.is_some()
&& !links_existing_user(state, &identity.subject, identity.email.as_deref()).await?
{
state.enforce_seat_limit().await?;
}
let link_by_email =
may_link_by_email(identity.email_verified, oidc.require_verified_email);
match state
Expand Down Expand Up @@ -244,6 +251,25 @@ async fn resolve_oidc(state: &AppState, token: Option<&str>) -> Result<AuthConte
})
}

/// Whether an OIDC first login would bind an existing user row instead of inserting
/// one. Mirrors the email normalisation in `Store::upsert_oidc_user`; any existing row
/// with that email (linkable or refused) means no new seat is consumed.
async fn links_existing_user(
state: &AppState,
subject: &str,
email: Option<&str>,
) -> Result<bool, ApiError> {
let email = email
.filter(|value| !value.trim().is_empty())
.unwrap_or(subject)
.to_lowercase();
Ok(state
.store
.get_user_by_email(state.default_org_id, &email)
.await?
.is_some())
}

fn team_role_rank(role: &str) -> u8 {
match role {
"lead" => 3,
Expand Down
17 changes: 10 additions & 7 deletions crates/orbit-api/src/handlers/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,17 +359,20 @@ pub async fn activate_agent(
let agent = require_agent_manage(&state, &auth, agent_id).await?;
// Draft and paused agents already count as non-archived. Restoring an archived one
// adds a seat to the installation-wide agent count, so it needs the same guard as
// creating a new agent.
let _agent_limit = if agent.status == AgentStatus::Archived.as_str() {
state.agent_limit_guard().await?
} else {
None
};
// creating a new agent. The status is read under the lock: an agent archived
// concurrently after `require_agent_manage` must still be counted (#396).
let agent_limit = state.license_limit_lock("agents").await?;
if agent_limit.is_some() {
let current = state.store.get_agent(auth.org_id, agent.id).await?;
if current.status == AgentStatus::Archived.as_str() {
state.enforce_agent_limit().await?;
}
}
state
.store
.set_agent_status(auth.org_id, agent_id, AgentStatus::Active)
.await?;
drop(_agent_limit);
drop(agent_limit);
audit::record(
&state,
&auth,
Expand Down
6 changes: 4 additions & 2 deletions crates/orbit-api/src/handlers/worker_launches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,8 +455,9 @@ pub(crate) async fn launch_profile_internal(
}
}
// Count running workers installation-wide. Held through the launch insert so two
// concurrent launches (manual, team run or dispatcher) cannot exceed the seat count.
let _worker_limit = state.worker_limit_guard().await?;
// concurrent launches (manual, team run or dispatcher) cannot exceed the worker limit,
// and released before the launcher call: the pending row already counts (#396).
let worker_limit = state.worker_limit_guard().await?;
let issued =
crate::handlers::worker_profiles::issue_profile_token(state, auth.org_id, &profile, false)
.await?;
Expand Down Expand Up @@ -499,6 +500,7 @@ pub(crate) async fn launch_profile_internal(
return Err(error.into());
}
};
drop(worker_limit);
let worker_id = launch_worker_id(launch.id);
let mut timeout_seconds = None;
if let Some(execution_id) = single_execution_id {
Expand Down
100 changes: 70 additions & 30 deletions crates/orbit-api/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,25 +96,42 @@ impl AppState {
self.license.status()
}

/// Guard + installation-wide seat count. Keep the returned guard alive until the user
/// row is written so concurrent provisions cannot race past the seat limit.
pub async fn seat_limit_guard(&self) -> Result<LicenseLimitGuard<'_>, crate::error::ApiError> {
let guard = self.store.license_limit_guard("seats").await?;
self.enforce_limit("seats", self.store.count_active_users_installation().await?)?;
Ok(guard)
/// Take the installation-wide lock for one license limit, or `None` without touching
/// the database when the license sets no such limit. Callers that decide under the
/// lock whether a slot is needed (re-reading state first) count with the matching
/// `enforce_*` helper; the `*_limit_guard` methods do both.
pub async fn license_limit_lock(
&self,
limit: &str,
) -> Result<Option<LicenseLimitGuard<'_>>, crate::error::ApiError> {
if self.license_status().limit(limit).is_none() {
return Ok(None);
}
Ok(Some(self.store.license_limit_guard(limit).await?))
}

/// Count active users installation-wide and refuse when the seat limit is reached.
/// Call while holding `license_limit_lock("seats")`.
pub async fn enforce_seat_limit(&self) -> Result<(), crate::error::ApiError> {
self.enforce_limit("seats", self.store.count_active_users_installation().await?)
}

/// Guard + installation-wide agent count. Hold until the agent row is written. Returns
/// `None` without touching the database when the license has no agent limit.
pub async fn agent_limit_guard(
&self,
) -> Result<Option<LicenseLimitGuard<'_>>, crate::error::ApiError> {
if self.license_status().limit("agents").is_none() {
return Ok(None);
let guard = self.license_limit_lock("agents").await?;
if guard.is_some() {
self.enforce_agent_limit().await?;
}
let guard = self.store.license_limit_guard("agents").await?;
self.enforce_limit("agents", self.store.count_agents_installation().await?)?;
Ok(Some(guard))
Ok(guard)
}

/// Count agents installation-wide and refuse when the agent limit is reached. Call
/// while holding `license_limit_lock("agents")`.
pub async fn enforce_agent_limit(&self) -> Result<(), crate::error::ApiError> {
self.enforce_limit("agents", self.store.count_agents_installation().await?)
}

/// Guard + installation-wide rolling 24h execution count. Hold until the execution
Expand All @@ -126,47 +143,70 @@ impl AppState {
return Ok(ExecutionLimit::Unrestricted);
}
let guard = self.store.license_limit_guard("executions_per_day").await?;
self.enforce_execution_limit().await?;
Ok(ExecutionLimit::Enforced(guard))
}

async fn enforce_execution_limit(&self) -> Result<(), crate::error::ApiError> {
let since = Utc::now() - chrono::Duration::hours(24);
let count = self
.store
.count_all_executions_since_installation(since)
.await?;
self.enforce_limit("executions_per_day", count)?;
Ok(ExecutionLimit::Enforced(guard))
self.enforce_limit("executions_per_day", count)
}

/// The single insertion point for licensed executions. Every manual run, rerun, team
/// step, scheduled trigger and runtime tick goes through here so none can skip the
/// `executions_per_day` guard. An idempotent replay returns the existing execution
/// without consuming a slot or taking the lock.
/// without consuming a slot. The key is looked up again under the lock, so a concurrent
/// duplicate at the exact limit gets the execution the first request created instead
/// of a license error.
pub async fn create_execution_with_limit(
&self,
new: NewExecution<'_>,
) -> Result<ExecutionRecord, crate::error::ApiError> {
if let Some(key) = new.idempotency_key {
if let Some(existing) = self
.store
.get_execution_by_idempotency_key(new.org_id, key)
.await?
{
if let Some(existing) = self.execution_for_key(&new).await? {
return Ok(existing);
}
let _limit = self.license_limit_lock("executions_per_day").await?;
if _limit.is_some() {
if let Some(existing) = self.execution_for_key(&new).await? {
return Ok(existing);
}
self.enforce_execution_limit().await?;
}
let _limit = self.execution_limit_guard().await?;
Ok(self.store.create_execution(new).await?)
}

/// Guard + installation-wide running-worker count. Hold until the launch is inserted.
async fn execution_for_key(
&self,
new: &NewExecution<'_>,
) -> Result<Option<ExecutionRecord>, crate::error::ApiError> {
let Some(key) = new.idempotency_key else {
return Ok(None);
};
Ok(self
.store
.get_execution_by_idempotency_key(new.org_id, key)
.await?)
}

/// Guard + installation-wide running-worker count. Hold until the launch row is
/// inserted (a pending launch already counts) and drop it before calling the launcher.
/// Returns `None` without touching the database when the license has no worker limit.
pub async fn worker_limit_guard(
&self,
) -> Result<LicenseLimitGuard<'_>, crate::error::ApiError> {
let guard = self.store.license_limit_guard("workers").await?;
self.enforce_limit(
"workers",
self.store
.count_active_worker_launches_installation()
.await?,
)?;
) -> Result<Option<LicenseLimitGuard<'_>>, crate::error::ApiError> {
let guard = self.license_limit_lock("workers").await?;
if guard.is_some() {
self.enforce_limit(
"workers",
self.store
.count_active_worker_launches_installation()
.await?,
)?;
}
Ok(guard)
}

Expand Down
Loading