单账号多端排他操作权

属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io

确保同一登录用户(Uid)名下的多台设备在同一时刻只有一台持有排他操作权(如答题交卷、单机存档同步、云端控台独占),其余设备可查询当前持有者或主动发起接管踢下线。底层租约存于 CachePlugin 选中的后端。

快速接入#

在 Cargo.toml 开启主包 kxed 的 device-lease 特性(生产多进程部署请一并开启 cache-redis;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["device-lease"] }):

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = [
    "auth",
    "device-lease",
    "cache-redis",
] }

在应用配置文件中将缓存设为共享 Redis(单进程测试可用默认 memory):

TOML
[redis]
url = "redis://127.0.0.1:6379"

[cache]
backend = "redis"

在应用中注册 CachePlugin 与 DeviceLeasePlugin,并在业务 Procedure 中按当前身份 Uid 申请或接管操作权:

Rust
use kxed::plugins::cache::CachePlugin;
use kxed::plugins::device_lease::{AppCtxDeviceLease, DeviceLeasePlugin};
use kxed::plugins::redis::RedisPlugin;
use kxed::prelude::*;
use std::time::Duration;

#[derive(Debug, Serialize, Deserialize, Validate, ToSchema)]
#[garde(allow_unvalidated)]
pub struct StartRound {
    pub device: String,
}

#[mutation(name = "rounds.start", post = "/api/rounds/start")]
pub async fn start_round(ctx: &AppCtx, input: StartRound) -> Result<String, AppErr> {
    let uid = ctx.require_identity().await?.uid();
    let lease = ctx
        .device_lease()?
        .acquire(&uid, &input.device, Duration::from_secs(60))
        .await?;
    Ok(lease.device().to_owned())
}

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(RedisPlugin::new())
        .plugin(CachePlugin::new())
        .plugin(DeviceLeasePlugin::new())
        .run()
        .await
}

子 crate 独立接入最小示例:

Rust
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::cache::CachePlugin;
use kxed_plugins::device_lease::{AppCtxDeviceLease, DeviceLeasePlugin, Lease};
use std::time::Duration;

fn plugins() -> (CachePlugin, DeviceLeasePlugin) {
    (CachePlugin::new(), DeviceLeasePlugin::new())
}

async fn acquire_round(ctx: &AppCtx, device: &str) -> Result<Lease, AppErr> {
    let uid = ctx.require_identity().await?.uid();
    Ok(ctx.device_lease()?.acquire(&uid, device, Duration::from_secs(60)).await?)
}

核心操作方法#

通过 ctx.device_lease()? 获取 DeviceLease 句柄(device 字符串为应用自定义的设备标识):

方法行为说明
acquire(uid, device, ttl)无人持有时获取租约;本设备已持有时直接续期;其他设备正持有时返回 DeviceLeaseError::Taken { holder }
renew(&lease, ttl)仅当租约仍归本设备持有时延长 ttl,已被抢占或过期则返回 DeviceLeaseError::Lost
takeover(uid, device, ttl)CAS 原子抢占操作权:若旧持有者在线,自动推送 device.lease.taken 通知并断开其连接(WebSocket close code 1008)
holder(uid)查询当前持有操作权的设备标识,无人持有或已过期返回 Ok(None)

错误码与运行期边界#

所有 DeviceLeaseError 变体均可直接用 ? 转为 AppErr:

错误变体HTTP 状态码与错误码触发原因与客户端处理
Taken { holder }409 device_lease_taken其他设备正持有有效租约;前端可提示用户是否调用 takeover 接管
Lost409 device_lease_lost续期时租约已过期或已被其他设备接管;纯 HTTP 客户端在下一次续期/操作时据此退出操作态
Conflict409 device_lease_conflict两台新设备在同一瞬间并发 takeover 触发 CAS 冲突;重读后重试即可
缓存后端错误沿用 CacheError(503/504 等)底层 Redis 超时或不可用

部署与容灾说明:

  • 失联自动释放:持有设备断网或客户端闪退后,最多等待一个 ttl 自然过期,其他设备即可无阻碍 acquire。
  • 多实例共享要求:多实例部署必须将 cache.backend 设为 "redis",使租约与跨节点 WebSocket 踢线(经 Presence SharedConnectionControl)全集群一致生效。租约键前缀为 device-lease:<uid_hex>。