///|
/// 读整个文件,失败返回空。
async fn read_bytes_or_empty(path : String) -> Bytes {
let f = Some(@fs.open(path, mode=ReadOnly)) catch { _ => None }
match f {
None => Bytes::make(0, b'\x00')
Some(file) => {
let data = Some(file.read_all()) catch { _ => None }
file.close()
match data {
None => Bytes::make(0, b'\x00')
Some(r) => r.binary()
}
}
}
}
///|
/// node 文件里就是一个十进制数字。
fn parse_node_id(b : Bytes) -> Int32 {
let mut n = 0
for i = 0; i < b.length(); i = i + 1 {
let c = b[i].to_int()
if c >= 48 && c <= 57 {
n = n * 10 + (c - 48)
} else if n > 0 {
break
}
}
n
}
///|
/// 文件的修改时间(纳秒,自 epoch);读不到返回 -1。
///
/// -1 同时表示「当时文件还不存在」,两种情况的处理一样:现在有就算新的。
#borrow(path)
extern "c" fn mtime_ns_raw(path : Bytes) -> Int64 = "moonbit_mtime_ns"
///|
fn mtime_ns(path : String) -> Int64 {
mtime_ns_raw(@util.cstr(path))
}
///|
/// 文件在 `since_ns` 之后被重写过吗。
///
/// 只看时间不看内容:portal 换了会话也可能给出同一个节点号(节点号是复用的),
/// 那种情况内容一样、时间变了,正是要认的。
fn rewritten_since(path : String, since_ns : Int64) -> Bool {
mtime_ns(path) > since_ns
}
///|
/// 拿 portal 给出来的 pipewire node id。
///
/// 正常情况是 autostart 那个助手(跑在 app-...@autostart.service 里,portal 认得出
/// app id,授权记得住)把 node 写进文件,这里只读文件,不碰它。
/// 只有在没人写文件时才自己拉一个助手 —— 那种身份 portal 认不出来,会弹授权框。
///
/// `force`:缓存不可信,只认「这一轮之后新写出来的 node」。
/// 看门狗重连时走这条路 —— 缓存里那个 id 正是刚死掉的那条流。
///|
/// ② 那一段最多等几轮(每轮 500 毫秒)。
///
/// 三种情形分开,原因是等待的价值完全不同:
/// - `orphaned`:缓存是我们自己拉起、又跟着我们被收掉的助手写的。它已经
/// 不在,没人会去重写文件,一轮都不该等(这就是重启慢 30 秒的根源)。
/// - `helper_alive`:助手在,可能正建会话,值得等满 60 轮(30 秒)。
/// - 都不是:冷启动,autostart 可能在我们之后一两秒才起来。等三秒,
/// 既给它机会,又不至于和它抢着各拉一个(两个助手会互相抢会话)。
pub fn portal_wait_rounds(orphaned : Bool, helper_alive : Bool) -> Int32 {
if orphaned {
0
} else if helper_alive {
60
} else {
6
}
}
///|
pub async fn acquire_portal_node(dir : String, force~ : Bool = false) -> Int32? {
let out = "\{dir}/portal.node"
let paths = @util.runtime_paths()
let tok = match paths.state_dir {
Some(state_dir) => "\{state_dir}/portal.token"
None => ""
}
// ① 已经有人写了就直接用 —— 但必须先确认写它的助手还活着。
//
// 原来是无条件信任:只要文件里有个正数就返回。助手一旦死掉
// (崩溃、被 kill、会话被外部关闭),文件内容不变,于是这里
// 每次都直接返回那个死 id,② 和 ③ 永远不会执行 ——
// 没有任何自愈路径,只能人工删文件或重启服务。
let cached = parse_node_id(read_bytes_or_empty(out))
// 助手活着没有,后面两处都要用,问一次就够
let helper_alive = portal_helper_alive()
// 缓存里的 node 是我们自己拉起的助手写下的,而那个助手跟着服务一起被
// systemd 收掉了(它在服务的 cgroup 里)。这种情况下一味等它重写文件是
// 白等 —— 那个进程已经不存在,没人会去写。判据就是「有缓存但助手没了」。
let orphaned = cached > 0 && !helper_alive
if !force && cached > 0 {
if helper_alive {
return Some(cached)
}
// 助手没了,缓存作废:删掉再走下面的重新拉起流程
eprintln("portal: 助手进程不在了,作废缓存的 node=\{cached}")
remove_file(out)
}
// force 时记下现在这个文件长什么样,只认之后的变化。
//
// 为什么不干脆把文件删掉重来:删的瞬间助手可能正好写进新 node,
// 那就被我们删掉了,而它以为已经写完,不会再写第二次 —— 于是等到超时。
// 不删文件,改成「记住旧值/旧时间,等它变成别的」就没有这个窗口。
let stamp = if force { mtime_ns(out) } else { -1L }
// ② 等 autostart 助手写它(它开机比服务稍晚,重连时也会重写)
//
// 什么时候值得等:
// - 有助手活着(它可能正在建会话,下一秒就写出来)
// - 冷启动、还没有 node 文件(autostart 可能在我们之后一两秒才起来)
//
// 什么时候不值得等:`orphaned` —— 缓存是跟着我们一起死掉的助手写的,
// 现在没人在跑,等满 30 秒也等不到。原来这里不分青红皂白等满 60 轮,
// 于是每次 `systemctl restart` 都要空转 30 秒才去拉新助手(实测
// 30.8 秒才切回 pipewire,其中 30 秒全耗在这一段)。
let grace_rounds = portal_wait_rounds(orphaned, helper_alive)
for k = 0; k < grace_rounds; k = k + 1 {
@async.sleep(500)
let id = parse_node_id(read_bytes_or_empty(out))
if id > 0 && (!force || id != cached || rewritten_since(out, stamp)) {
return Some(id)
}
}
// ③ 没有可用的 node。
//
// 先看是不是已经有助手在跑(比如 autostart 拉起的 loop,它只是还没
// 拿到 node 而已)。已经在跑就只等它,绝不能再拉一个 ——
// 一个进程同时只能持有一条 screencast 会话,两个助手会互相抢,
// 两边都拿不到 node,还各自弹一次授权框。
if portal_helper_alive() {
eprintln("portal: 已有助手在跑,等它拿 node")
for k = 0; k < 180; k = k + 1 {
@async.sleep(500)
let id = parse_node_id(read_bytes_or_empty(out))
if id > 0 && (!force || id != cached || rewritten_since(out, stamp)) {
return Some(id)
}
}
eprintln("portal: 助手在跑但一直没写出 node")
return None
}
// 真的没人管:自己拉一个
match paths.state_dir {
Some(state_dir) => {
let _ = Some(@fs.mkdir(state_dir, permission=0o700, recursive=true)) catch {
_ => None
}
}
None => ()
}
let bin = match @env.get_env_var("HOME") {
Some(h) => "\{h}/.local/bin/screen-kacha-portal"
None => "screen-kacha-portal"
}
let spawned = Some(@process.spawn_orphan(bin, ["--out", out, "--token", tok])) catch {
_ => None
}
match spawned {
None => {
eprintln("拉起 portal 助手失败")
return None
}
Some(_) => ()
}
for k = 0; k < 180; k = k + 1 {
@async.sleep(500)
let id = parse_node_id(read_bytes_or_empty(out))
if id > 0 {
return Some(id)
}
}
None
}
///|
/// 写 portal.node 的那个助手进程还在不在。
///
/// 这里有个坑:`pgrep -x screen-kacha-portal` **永远匹配不到**。
/// Linux 的进程名(comm)上限是 15 个字符,`screen-kacha-portal` 有 18 个,
/// 内核会把它截成 `screen-kacha-po`,pgrep 还会明确警告
/// 「模式要搜索的进程名的长度超过 15 个字符」。
/// 所以只能用 `-f` 匹配完整命令行。
///
/// `-f` 不会杀自己(这里是 pgrep 不是 pkill),模式里带路径前缀
/// 也避免了误伤命令行里恰好含这串的别的进程。
async fn portal_helper_alive() -> Bool {
let (code, out) = @process.collect_stdout("/usr/bin/pgrep", [
"-f", "/screen-kacha-portal --out",
]) catch {
_ => return false
}
if code != 0 {
return false
}
let text = out.text() catch { _ => return false }
text.trim() != ""
}
///|
async fn remove_file(path : String) -> Unit {
let _ = @process.run("/usr/bin/rm", ["-f", path]) catch { _ => 1 }
}