Python sqlite3 租约与 fencing token:阻止过期工作者写回旧结果

10-19 4阅读

后台进程拿到一项任务后,可能因为调试断点、长时间计算或进程暂停而错过续租。另一个进程看到租约到期,接手并写入新结果;最初的进程随后恢复,仍然记得自己曾经获得过所有权。如果它只按任务名称提交结果,就会把新结果覆盖掉。租约过期解决了接手资格,却没有自动撤销旧进程手里的写入能力。

本文用 Python 标准库 sqlite3 实现一套仅面向本机 SQLite 数据库的租约协议:每次成功获取都产生递增的 fencing token,续租和释放必须携带原令牌,真正修改业务数据时也必须在数据库语句中检查当前令牌与有效期。重点是过期后的旧持有者隔离,不是任务配额、通用队列或普通版本号更新。

Python sqlite3 租约与 fencing token:阻止过期工作者写回旧结果
概念示意:沙漏表示有限租期,递增令牌区分先后两轮所有权;真正的检查发生在 SQLite 写入条件中。

九段代码分别是完整脚本,可以各自保存后执行 python -X dev -W error example.py,不需要先运行前一段。环境要求为 Python 3.12 及以上、运行时 SQLite 3.35.0 及以上;后者是 RETURNING 的最低版本。演示只用内存库或自动清理的本地临时文件,时间都是人为推进的整数,不调用真实时钟,也不依赖 sleep。

连接显式使用 autocommit=True,复合操作再用 SQL 的 BEGIN IMMEDIATE、COMMIT 和 ROLLBACK 划出事务边界。这里不能把 Python 连接对象的 commit() 当作显式 SQL COMMIT 的替身:在该模式下前者不提交手动打开的事务。所有连接都由 closing 关闭,参数均以占位符绑定。相关行为可核对 Python sqlite3 事务控制文档。

一、先约定有效区间,精确处理相等边界

把租约有效区间定义为从成功获取开始,到 expires 之前结束。也就是 now < expires 才有效,now >= expires 已过期。两条规则必须互补:如果续租使用大于等于,而接管也使用小于等于,同一时刻就会同时被解释成可以续租与可以接管。若两边都排除等号,又会人为留出无人能够继续的空档。

lease 表保留资源名称、持有者、代次令牌和到期整数。空闲状态用 owner 为 NULL 表示,到期值归零;token 即使空闲也保留。数据库约束防止误写负数或非整数,但这些约束不会代替业务权限检查。下面故意把时间放在到期前一格、恰好到期和到期后一格,验证有效与可接管状态总是相反。这里的整数单位由业务自行约定,示例中的一格不等同于现实的一秒。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    con.execute("UPDATE lease SET owner='A', token=7, expires=110")
    for now in (109, 110, 111):
        active, reclaimable = con.execute("""
            SELECT owner IS NOT NULL AND expires > ?,
                   owner IS NULL OR expires <= ?
            FROM lease WHERE resource='report'
        """, (now, now)).fetchone()
        assert bool(active) != bool(reclaimable)
        print(now, bool(active), bool(reclaimable))

运行输出:

109 True False
110 False True
111 False True

这一步先确定协议语义,之后获取、续租、释放和业务写入都遵守同一条边界。数据库不会主动在到期点清空 owner;一行仍显示 A,并不代表 A 此刻仍有效。读取持有者用于展示时,也必须同时解释 expires。

二、原子获取:先提交,再交付令牌

获取资格由一条条件 UPDATE 判断:资源空闲或已过期时,同时换 owner、增加 token、设置新截止值。判断和修改没有分离的读取窗口,也不需要先查询再在 Python 中决定更新。示例把它放入显式写事务,是为了清楚展示令牌只能在提交成功后交给调用者。BEGIN IMMEDIATE 会尝试立即进入写事务;另一个写者占用数据库时可能返回 SQLITE_BUSY,详见 SQLite 事务说明。

第一次获取产生令牌一。竞争者在一百零九时获取不到;到一百一十恰好过期,竞争者获得令牌二。没有命中条件时返回 None,而不是返回数据库里现有的令牌。最大整数保护则保证递增操作不会越过 SQLite 的整数范围。此处只演示协议,输入值是受控常量;第九段会把时间与租期验证加入统一入口。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

ACQUIRE = """
UPDATE lease SET owner=:owner, token=token+1, expires=:deadline
WHERE resource='report' AND (owner IS NULL OR expires<=:now)
  AND token<9223372036854775807
RETURNING token, expires
"""

def acquire(con, owner, now, ttl):
    con.execute("BEGIN IMMEDIATE")
    try:
        rows = con.execute(ACQUIRE, {
            "owner": owner, "now": now, "deadline": now + ttl
        }).fetchall()
        con.execute("COMMIT")
        return rows[0] if rows else None
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    first = acquire(con, "A", 100, 10)
    busy = acquire(con, "B", 109, 10)
    takeover = acquire(con, "B", 110, 10)
    assert (first, busy, takeover) == ((1, 110), None, (2, 120))
    print(first, busy, takeover)

运行输出:

(1, 110) None (2, 120)

RETURNING 返回的是本语句修改后的值,不表示外层事务已经提交。代码先 fetchall 取完结果,再执行 COMMIT,最后返回。若提交失败,异常路径会回滚,调用者不能把临时读到的数字当成有效凭证。

三、原子续租:只能延长仍然有效的同一轮所有权

续租必须同时匹配资源、owner、token 和未过期条件。单独检查 owner 不够,因为一个进程名称可以被重复使用;单独检查 token 而不检查有效期,也会让尚未被别人接管的过期租约重新复活。过期者如果还想工作,应重新参与获取,拿到一个更大的令牌后再开始。

这里选择只延长、不缩短的策略,用 max(expires, now + ttl) 保留已有的更长有效期。该选择是本例的业务约定,并非 SQLite 内置的租约规则。续租保持 token 不变,因为它仍然属于同一轮所有权。输出中第一次续租把截止值延至一百一十四,下一次较短的续租请求不会缩短它,最后在相等边界被拒绝。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

def renew(con, owner, token, now, ttl):
    rows = con.execute("""
        UPDATE lease SET expires=max(expires, :deadline)
        WHERE resource='report' AND owner=:owner AND token=:token
          AND expires>:now
        RETURNING token, expires
    """, {"owner": owner, "token": token,
          "now": now, "deadline": now + ttl}).fetchall()
    return rows[0] if rows else None

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    con.execute("UPDATE lease SET owner='A', token=1, expires=110")
    assert renew(con, "B", 1, 108, 10) is None
    assert renew(con, "A", 99, 108, 10) is None
    print("renew:", renew(con, "A", 1, 109, 5))
    print("keep:", renew(con, "A", 1, 110, 1))
    print("at expiry:", renew(con, "A", 1, 114, 5))
    assert con.execute("SELECT token, expires FROM lease").fetchone() == (1, 114)

运行输出:

renew: (1, 114)
keep: (1, 114)
at expiry: None

实际工作者应在租期结束前预留足够余量尝试续租。一次续租失败不意味着它可以继续用上次成功的身份提交;所有结果仍需经过写入关口检查。不能靠后台心跳线程的局部成功标记跳过数据库验证。

四、原子释放:清空持有者,留下代次历史

释放不是 DELETE。删除租约行,再为同一资源插入从零开始的记录,会让旧令牌和未来令牌发生重用,破坏代次之间的区分。安全的释放只清空 owner 和 expires,保留 token;下一次获取继续加一。资源名称也应代表稳定的逻辑资源,不能在旧工作者可能回来时偷偷改成一个全新计数器。

本例规定只有尚未过期的当前持有者能够主动释放。过期租约本来就可被接管,无须允许旧工作者执行清理。所有权已转移后,旧持有者的释放请求必须影响零行,不能误删新持有者的身份。打印结果显示,释放后令牌仍是三;B 获取时升为四,A 的延迟清理完全无效。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

def release(con, owner, token, now):
    return con.execute("""
        UPDATE lease SET owner=NULL, expires=0
        WHERE resource='report' AND owner=? AND token=? AND expires>?
    """, (owner, token, now)).rowcount == 1

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    con.execute("UPDATE lease SET owner='A', token=3, expires=110")
    assert not release(con, "B", 3, 104)
    assert release(con, "A", 3, 104)
    print("released:", con.execute("SELECT owner, token FROM lease").fetchone())
    rows = con.execute("""
        UPDATE lease SET owner='B', token=token+1, expires=114
        WHERE resource='report' AND (owner IS NULL OR expires<=104)
          AND token<9223372036854775807
        RETURNING token
    """).fetchall()
    assert rows == [(4,)]
    assert not release(con, "A", 3, 105)
    assert not release(con, "B", 4, 114)
    print("new owner:", con.execute("SELECT owner, token FROM lease").fetchone())

运行输出:

released: (None, 3)
new owner: ('B', 4)

重复释放在这个接口中返回 False,调用方可以将其解释为自己已经不再持有,而不是要求无条件清空状态。不要为了追求释放接口表面上的成功率,把 owner 与 token 条件删掉。

五、真正的 fencing:在业务写入里拒绝旧令牌

租约表只负责记录资格,保护业务数据还需要最后一道门。下面让 document 与 lease 位于同一个数据库,一条 UPDATE 通过 EXISTS 检查当前 owner、token 以及未过期状态,条件满足才写内容。检查与修改在同一语句里完成,竞争者不能插入到它们之间。不要改成先 SELECT 验证、退出事务、再 UPDATE,那样旧资格可能在两步之间失效。

document.last_token 留下最近一次成功写入的代次,额外禁止较小代次覆盖较大代次。这里使用小于等于,允许同一轮租约连续写入多次;若只允许严格小于,同一持有者的第二次正常更新也会失败。决定当前资格的仍然是 lease 的精确匹配:只看 last_token,无法在新持有者尚未写入时挡住旧持有者,也无法拒绝已过期但尚无人接管的写入。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

def write_document(con, owner, token, now, body):
    rows = con.execute("""
        UPDATE document SET body=:body, last_token=:token
        WHERE name='report' AND last_token<=:token
          AND EXISTS(
              SELECT 1 FROM lease
              WHERE resource=document.name AND owner=:owner
                AND token=:token AND expires>:now
          )
        RETURNING body, last_token
    """, {"owner": owner, "token": token, "now": now, "body": body}).fetchall()
    return bool(rows)

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    CREATE TABLE document(name TEXT PRIMARY KEY, body TEXT, last_token INTEGER);
    INSERT INTO document VALUES('report', 'initial', 0);
    """)
    con.execute("UPDATE lease SET owner='A', token=1, expires=110")
    assert write_document(con, "A", 1, 109, "from A")
    assert not write_document(con, "A", 1, 110, "expired A")
    con.execute("""
        UPDATE lease SET owner='B', token=token+1, expires=120
        WHERE resource='report' AND expires<=110
          AND token<9223372036854775807
    """)
    assert not write_document(con, "A", 1, 111, "late A")
    assert write_document(con, "B", 2, 111, "from B")
    assert write_document(con, "B", 2, 112, "B second write")
    assert not write_document(con, "A", 1, 112, "overwrite B")
    print(con.execute("SELECT body, last_token FROM document").fetchone())

运行输出:

('B second write', 2)

测试先拒绝 A 在相等边界的写入,再模拟 B 接管,最后允许 B 连续写两次并挡住 A 的延迟覆盖。这不是消息去重协议:同一令牌的重复业务请求依然可能执行多次,需要恰好一次效果的业务还要增加自己的请求标识。此处保护范围仅限这些受检的数据库写入。

六、同名工作者重启:用令牌识别两次生命周期

开发环境常把 owner 写成固定进程名,进程重启后仍叫 worker-1。即使生产中使用随机会话标识,也不应把唯一名称当成代次检查的替代品。考虑同名工作者的一轮租约过期后,又成功获取下一轮;旧回调仍可能带着上一次的上下文到达。名称相同,凭证的代次却不同,这正是容易被忽视的重复身份问题。

本段把令牌从八推进到九,却保留相同 owner。旧令牌八发出的释放和续租都影响零行,数据库仍保留第九轮的一百二十截止值。这样的测试比单纯换成 A 与 B 更严格:它验证真正起作用的是代次检查,而不是碰巧不同的字符串。业务回调需要保存获取时返回的令牌,不要在提交前重新查询最新令牌冒充当前持有者。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    # 同一个 owner 名称先后属于两轮租约。
    con.execute("UPDATE lease SET owner='worker-1', token=8, expires=110")
    old_token = 8
    rows = con.execute("""
        UPDATE lease SET token=token+1, expires=120
        WHERE resource='report' AND expires<=110
          AND token<9223372036854775807
        RETURNING token
    """).fetchall()
    assert rows == [(9,)]
    old_release = con.execute("""
        UPDATE lease SET owner=NULL, expires=0
        WHERE resource='report' AND owner=? AND token=? AND expires>?
    """, ("worker-1", old_token, 111)).rowcount
    old_renew = con.execute("""
        UPDATE lease SET expires=200
        WHERE resource='report' AND owner=? AND token=? AND expires>?
    """, ("worker-1", old_token, 111)).rowcount
    assert old_release == old_renew == 0
    print("old actions:", old_release, old_renew)
    print(con.execute("SELECT owner, token, expires FROM lease").fetchone())

运行输出:

old actions: 0 0
('worker-1', 9, 120)

fencing token 不是密码,也不是对恶意数据库写者的授权机制。能够绕过应用直接修改 lease 或冒用当前凭证的代码仍然能破坏协议。这里防的是遵守协议的旧工作者、迟到回调与重试。

七、两个本地连接:区分数据库忙与租约被占用

一项业务资源被别人持有,与整个数据库暂时不能开始写事务,是两种不同结果。前者由条件更新返回空结果,后者是 SQLite 的锁竞争异常。示例打开同一本地临时文件的两个连接,故意让 A 持有写事务,再让 B 尝试进入。timeout=0 让锁竞争立即返回,不靠线程调度、真实等待或概率测试制造结果。

A 提交后,B 可以重新开始写事务,但业务租约仍未过期,因此这次获取返回空结果。SQLite 的单写者模型只序列化数据库写事务,不等于业务租约一直占着数据库锁。应把昂贵计算放在事务外,每次获取、续租和提交结果使用短事务。关于不同连接之间的可见性与写入串行化,可查阅 SQLite 隔离说明。

import sqlite3
from contextlib import ExitStack, closing
from pathlib import Path
from tempfile import TemporaryDirectory

assert sqlite3.sqlite_version_info >= (3, 35, 0)
with TemporaryDirectory() as folder, ExitStack() as stack:
    path = Path(folder) / "lease.db"
    a = stack.enter_context(closing(sqlite3.connect(path, autocommit=True, timeout=0)))
    b = stack.enter_context(closing(sqlite3.connect(path, autocommit=True, timeout=0)))
    a.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    a.execute("BEGIN IMMEDIATE")
    try:
        b.execute("BEGIN IMMEDIATE")
    except sqlite3.OperationalError as exc:
        assert exc.sqlite_errorcode == sqlite3.SQLITE_BUSY
        print("second writer: SQLITE_BUSY")
    else:
        raise AssertionError("The competing writer unexpectedly entered")
    a.execute("""
        UPDATE lease SET owner='A', token=token+1, expires=110
        WHERE resource='report' AND (owner IS NULL OR expires<=100)
          AND token<9223372036854775807
    """)
    a.execute("COMMIT")
    b.execute("BEGIN IMMEDIATE")
    try:
        rows = b.execute("""
            UPDATE lease SET owner='B', token=token+1, expires=119
            WHERE resource='report' AND (owner IS NULL OR expires<=109)
              AND token<9223372036854775807
            RETURNING token
        """).fetchall()
        b.execute("COMMIT")
    except BaseException:
        if b.in_transaction:
            b.execute("ROLLBACK")
        raise
    assert rows == []
    print("after retry: lease unavailable")

运行输出:

second writer: SQLITE_BUSY
after retry: lease unavailable

生产重试应有上限、退避和取消条件;进入事务后重新读取统一时间来源,不能把等待锁之前取到的旧时间一直沿用。示例不把所有 OperationalError 都吞掉,只确认预期的 SQLITE_BUSY。磁盘错误、损坏或语法错误需要作为真实故障处理。

八、回滚与整数上限:令牌不能提前泄漏,也不能回绕

单调递增说的是同一资源已经提交的成功授予序列。事务里临时算出一,再整体回滚,下一次成功获取仍可能得到一。这并不违反已提交历史的单调性,前提是上一个临时令牌从未交给工作者、从未用于事务外的动作。不能在 COMMIT 之前发消息、启动任务或写外部文件,然后希望回滚把这些副作用一起撤销。

示例先取得临时令牌并回滚,再重新获取并提交,证明只有后者可以发布。随后人为把计数器推到有符号六十四位整数上限,获取被拒绝。SQLite 算术在整数溢出时可能转为浮点运算,不能期待它自动给你安全的新代次;相关行为见 SQLite 表达式文档。上限应触发明确告警和人工迁移,不应归零继续运行。

import sqlite3
from contextlib import closing

assert sqlite3.sqlite_version_info >= (3, 35, 0)

with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    """)
    claim = """
        UPDATE lease SET owner='A', token=token+1, expires=110
        WHERE resource='report' AND (owner IS NULL OR expires<=100)
          AND token<9223372036854775807
        RETURNING token
    """
    con.execute("BEGIN IMMEDIATE")
    provisional = con.execute(claim).fetchall()
    assert provisional == [(1,)]
    con.execute("ROLLBACK")
    assert con.execute("SELECT token FROM lease").fetchone() == (0,)
    con.execute("BEGIN IMMEDIATE")
    committed = con.execute(claim).fetchall()
    con.execute("COMMIT")
    assert committed == [(1,)]
    print("published after commit:", committed[0][0])
    con.execute("UPDATE lease SET owner=NULL, expires=0, token=?",
                (2**63 - 1,))
    assert con.execute(claim).fetchall() == []
    print("at token limit: acquisition rejected")

运行输出:

published after commit: 1
at token limit: acquisition rejected

同样,恢复旧备份或重新初始化数据库也可能把代次历史倒退。恢复流程必须先停止全部工作者、隔离旧上下文,再明确建立新的运行代际。本教程不提供跨备份恢复的全局令牌服务,也不把数据库内的递增数字夸大成永不回退的外部保证。

九、把边界串成一次完整回归

最后一段把四类操作收口为同一个事务入口。受控 Clock 只能向前推进,操作取得写事务后才读时间;租期必须是正整数,并检查截止值不会溢出。特别使用 type(value) is int,是为了不让 Python 的 True 作为整数一混进时间或令牌。接口先验证动作与身份,再执行 SQL,发生错误时只在事务确实仍活动的情况下回滚。

回归顺序覆盖 A 获取、B 提前抢占失败、A 正常写入、到期续租失败、B 恰好接管、A 延迟操作失败、B 释放、同名 B 再获取、旧 B 令牌再次失效。几个非法租期还验证异常路径没有残留事务。代码故意保持单资源以突出语义;扩展多资源时,把资源名称作为绑定参数贯穿每一个条件,不能只给获取操作加过滤。

import sqlite3
from contextlib import closing

MAX_INT = 2**63 - 1
assert sqlite3.sqlite_version_info >= (3, 35, 0)

class Clock:
    def __init__(self, now):
        self.now = now

    def set(self, now):
        if type(now) is not int or not self.now <= now <= MAX_INT:
            raise ValueError("clock must be a nondecreasing integer")
        self.now = now

    def __call__(self):
        return self.now

def step(con, clock, action, owner, token=0, ttl=0, body=""):
    if action not in {"acquire", "renew", "release", "write"}:
        raise ValueError("unknown action")
    if not isinstance(owner, str) or not owner:
        raise ValueError("owner is required")
    if type(token) is not int or not 0 <= token <= MAX_INT:
        raise ValueError("invalid token")
    if action != "acquire" and token == 0:
        raise ValueError("a granted token is required")
    con.execute("BEGIN IMMEDIATE")
    try:
        now = clock()  # 取得写事务之后,再读取受控时钟。
        if type(now) is not int or not 0 <= now <= MAX_INT:
            raise ValueError("invalid clock")
        if action in {"acquire", "renew"}:
            if type(ttl) is not int or not 0 < ttl <= MAX_INT - now:
                raise ValueError("invalid ttl")
        p = {"owner": owner, "token": token, "now": now,
             "deadline": now + ttl, "body": body, "limit": MAX_INT}
        if action == "acquire":
            sql = """
                UPDATE lease SET owner=:owner, token=token+1, expires=:deadline
                WHERE resource='report' AND (owner IS NULL OR expires<=:now)
                  AND token<:limit
                RETURNING token, expires
            """
        elif action == "renew":
            sql = """
                UPDATE lease SET expires=max(expires, :deadline)
                WHERE resource='report' AND owner=:owner AND token=:token
                  AND expires>:now
                RETURNING token, expires
            """
        elif action == "release":
            sql = """
                UPDATE lease SET owner=NULL, expires=0
                WHERE resource='report' AND owner=:owner AND token=:token
                  AND expires>:now
                RETURNING token
            """
        else:
            sql = """
                UPDATE document SET body=:body, last_token=:token
                WHERE name='report' AND last_token<=:token AND EXISTS(
                    SELECT 1 FROM lease WHERE resource=document.name
                    AND owner=:owner AND token=:token AND expires>:now
                )
                RETURNING body, last_token
            """
        rows = con.execute(sql, p).fetchall()
        con.execute("COMMIT")
        return rows[0] if rows else None
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

with closing(sqlite3.connect(":memory:", autocommit=True, timeout=0)) as con:
    con.executescript("""
    CREATE TABLE lease(
        resource TEXT PRIMARY KEY,
        owner TEXT,
        token INTEGER NOT NULL CHECK(typeof(token)='integer' AND token>=0),
        expires INTEGER NOT NULL CHECK(typeof(expires)='integer' AND expires>=0),
        CHECK(owner IS NULL OR (typeof(owner)='text' AND length(owner)>0)),
        CHECK(owner IS NULL OR token>0),
        CHECK(owner IS NOT NULL OR expires=0)
    );
    INSERT INTO lease VALUES('report', NULL, 0, 0);
    CREATE TABLE document(
        name TEXT PRIMARY KEY, body TEXT NOT NULL,
        last_token INTEGER NOT NULL CHECK(typeof(last_token)='integer' AND last_token>=0)
    );
    INSERT INTO document VALUES('report', 'initial', 0);
    """)
    clock = Clock(100)
    assert step(con, clock, "acquire", "A", ttl=10) == (1, 110)
    clock.set(109)
    assert step(con, clock, "acquire", "B", ttl=10) is None
    assert step(con, clock, "write", "A", 1, body="A result") == ("A result", 1)
    clock.set(110)
    assert step(con, clock, "renew", "A", 1, ttl=10) is None
    assert step(con, clock, "write", "A", 1, body="late A") is None
    assert step(con, clock, "acquire", "B", ttl=10) == (2, 120)
    clock.set(111)
    assert step(con, clock, "release", "A", 1) is None
    assert step(con, clock, "renew", "A", 1, ttl=20) is None
    assert step(con, clock, "write", "B", 2, body="B result") == ("B result", 2)
    assert step(con, clock, "release", "B", 2) == (2,)
    assert step(con, clock, "write", "B", 2, body="released B") is None
    assert step(con, clock, "acquire", "B", ttl=5) == (3, 116)
    assert step(con, clock, "write", "B", 2, body="old B") is None
    assert step(con, clock, "renew", "B", 3, ttl=10) == (3, 121)
    for bad_ttl in (0, -1, True, MAX_INT):
        try:
            step(con, clock, "renew", "B", 3, ttl=bad_ttl)
        except ValueError:
            assert not con.in_transaction
        else:
            raise AssertionError("bad ttl accepted")
    assert con.execute("SELECT body, last_token FROM document").fetchone() == ("B result", 2)
    print("state-machine assertions passed")
    print("lease:", con.execute("SELECT owner, token, expires FROM lease").fetchone())
    print("document:", con.execute("SELECT body, last_token FROM document").fetchone())

运行输出:

state-machine assertions passed
lease: ('B', 3, 121)
document: ('B result', 2)

最终文档仍是 B 第二轮留下的结果,当前租约已经进入第三轮。业务内容的最近写入代次可以落后于当前租约代次,这完全正常:获取租约本身不代表已经产出新内容。正因如此,写入检查必须读取当前租约,而不能只拿业务表中的最后写入令牌推断所有权。

落地边界:本地租约不会自动变成分布式时钟方案

本文假设所有参与者访问同一台机器上的同一份 SQLite 数据库文件,并遵守同一协议。SQLite 官方也建议在多个客户端需要跨网络访问同一数据库时考虑客户端服务器数据库,参见 适用场景说明。不要把示例文件放到网络共享目录,就把本地事务模型当作跨节点协调方案。

整数时钟是测试接口,不是现实时间方案。真实部署必须明确时间单位、来源、回拨处理、机器重启后的时间基准,以及长时间暂停后的恢复策略。持久化的截止值不能直接混用不同启动周期的进程单调时钟。即便所有代码都在同一主机上,时钟选择也需要单独设计;本文没有解决分布式时钟同步、网络分区或跨机租约安全。

这里的有效性判断发生在数据库写操作内采用的时间点。系统可能在检查后暂停,提交也可能晚于名义截止时刻;因此它不承诺现实时间一到点,就能中断正在进行的计算或强制取消已进入的事务。短事务与写事务串行化保证接管不能插入受保护写入的检查和修改之间,而精确到期语义依赖可信的时间采样。对严格墙钟截止要求,应进一步定义线性化点和可接受的暂停模型。

另一个常见误区是先通过数据库校验,再写本地文件、调用支付接口或发送网络请求。SQLite 无法把那些外部副作用纳入这里的原子检查。若外部资源不亲自检查并拒绝旧代次,fencing 只停留在数字层面;若外部资源会检查,也仍需单独设计其提交与失败语义。本例有意把受保护数据留在同一数据库中。

上线前至少保留这些断言:相等边界不能续租和写入;接管必增令牌;释放不得删除历史;同名持有者的旧令牌无效;数据库忙不等于租约拒绝;令牌只有提交后才能传播。租约决定谁可以尝试继续工作,数据库写入条件决定谁的结果最终能够留下。两处都检查,旧进程醒来时才不会凭过去的资格改写现在。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。