Skip to content

System

SeqReadResult

SeqReadResult(rows: RowsT, blocked: tuple[int, int] | None)

Source: hetu/data/backend/base.py:201

Bases: tuple, Generic

Result of BackendClient.seq_read: the rows read and what blocked the read.

提交序号列增量读(seq_read)的结果,可以直接解包:rows, blocked = ...。

  • rows:号大于 after 的行,按号升序,格式按 row_format;
  • blocked:(号, 行 id) 或 None。索引里有、这次却没取到行的第一个 member,它挡住了后面的 行;None 表示没被挡住。取行落到落后的副本、读完索引之后行被删了都会挡住,下一次通常就好了; 同一个 (号, 行 id) 一直挡着,多半是索引残留(索引里有、行没有)。

Attributes

  • rows (RowsT) — No description.

  • blocked (tuple[int, int] | None) — No description.


SessionRepository

SessionRepository(session: Session, comp_cls: type[BaseComponent]) -> None

Source: hetu/data/backend/repo.py:77

从数据库查询数据并放入Session缓存,System的ctx.repo[...]返回的便是此类。

Attributes

Methods

remote_has_unique_conflicts_

remote_has_unique_conflicts_(row: numpy.record, fields: set) -> str | None

Source: hetu/data/backend/repo.py:122

内部方法,在远程数据库中检查Unique索引冲突。

is_unique_conflicts

is_unique_conflicts(row: numpy.record, insert=False) -> tuple[str | None, bool]

Source: hetu/data/backend/repo.py:177

检查一行数据的Unique索引在本地和远程数据库中是否有冲突。

这是可选的提前检查(每个 unique 字段 1 次往返):insert / update 默认不再 调用本方法,等价的判定在 commit() 时由后端原子执行(见 IdentityMap.get_absent_unique_fields)。想在事务体内提前失败、或据此分支时可 显式调用。

Parameters

  • row (np.record) — 待检查的行数据,必须是 c-struct 格式。

  • insert (bool) — 如果为True,表示这是一个插入操作,否则是更新操作,要求之前已获取过旧数据。

Returns

field 为冲突的unique列名,无冲突时为 None。is_race 为 True 表示该冲突 应作为 RaceCondition 处理:远程冲突命中了一个「本事务曾观察其不存在」的列 (基于过期快照的乐观并发失败,重试可解);False 则是确定性冲突,应 UniqueViolation 。

注意优先级:只要有任一 observed-absent 列发生远程冲突就判为竞态,即便另有 非 observed-absent 列也冲突——否则像 upsert 在锚定列与其他unique列同时撞车 时会错误退化为 UniqueViolation,破坏「重试后转为 update」的语义。

get_by_id

get_by_id(row_id: numpy.int64 | int) -> numpy.record | None

Source: hetu/data/backend/repo.py:241

按主键 id 读一行,读到的放入Session缓存,和 get(id=row_id) 完全一样。 命中缓存(含本事务新 insert 的行)时不去数据库查询。

读空会登记"本事务观察到该 id 不存在":同一事务内再读这个 id(get_by_id 或 get(id=))直接返回 None,不再查询数据库。commit 时确认这个 id 仍然不存在:读空之后 被别的事务插入了,或者读空读到的是落后的副本,判为 RaceCondition 重试;本事务 insert 这个 id 撞车时同样判竞态,而不是 UniqueViolation 。

Parameters

  • row_id (Any) — 行的主键 id。

Returns

读空(含本事务删掉的行)返回 None,否则返回 np.record (c-struct) 格式的行。

get

get(
    index_name: str | None = None,
    query_value: numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool | None = None,
    _group: collections.abc.Mapping[str, Any] | None = None,
    **kwargs: numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool,
) -> numpy.record | None

Source: hetu/data/backend/repo.py:366

从数据库获取单行数据,并放入Session缓存。 推荐通过"id"主键查询,这样无须查询索引,如果缓存命中,不会去数据库查询;否则会执行1-2次查询。 主键或 unique 列读空会登记"本事务观察到该值不存在":同一事务内再次 get 同一值直接返回 None(不再查询数据库),commit 时若该值已被并发写入(或读空读到的是落后的副本)则判为 RaceCondition 重试。 结果按本事务眼里的数据:本事务新 insert 的行能查到,删掉的、已改走这个值的行不算匹配。 例外是提交序号列(commit_seq):本事务 insert 的行还没有号(是 0),按这一列查不到它们, 按 id、按别的索引能查到。

非 unique 列同样会在提交时校验:读空而提交前已有匹配的行(被并发插入,或读到了滞后的 副本)判 RaceCondition ,所以"get 为 None 就 insert"的写法是安全的;命中时只保证返回的 这一行没被改过,之后别的事务再插入同值的行不算冲突。

Parameters

  • index_name (Any) — 辅助参数,如果不便使用kwargs参数时使用。

  • query_value (Any) — 辅助参数,如果不便使用kwargs参数时使用。

  • _group (Any) — 辅助参数,复合索引(groupby)的分组值 {分组列: 值},配合 index_name 使用。

  • kwargs (Any) — 查询字段和值,例如 id=1234567890。只能查询一个有索引的字段;复合索引要同时给出 全部分组列,例如 get(name="abc", zone=3)(组内查询)。值按字面比较:字符串开头的 ( / [ 不是区间标记(只有 range 才解释),get(name="[GM]Bob") 查的就是 “[GM]Bob”。

Returns

如果未查询到匹配数据,则返回 None。如果查询到数据,则返回查询到的第一行数据。 返回 np.record (c-struct) 格式。

Examples

::

item = await session.using(Item).get(id=1234567890)

range

range(
    index_name: str | None = None,
    _left: numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool | None = None,
    _right: numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool | None = None,
    limit: int = 10,
    desc: bool = False,
    phantom_check: bool = True,
    _group: collections.abc.Mapping[str, Any] | None = None,
    **kwargs: tuple[numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool, numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool] | numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool,
) -> numpy.rec.recarray

Source: hetu/data/backend/repo.py:498

从数据库查询索引,返回区间内数据,限制 limit 条。 本指令会去数据库执行 1~2 次往返:先查索引拿 id 列表,缓存未命中的行再一次批量读回。

结果按本事务眼里的数据(同 get):本事务 insert 的行、update 后落进区间的行 会出现在结果里,和库里的行按索引顺序排在一起;delete 掉的、索引列改走了的行不在 结果里,也不占 limit 名额。unique 列点查(如 name=("x", "x"))命中本事务从库里 读过、这一列没改过的行时,直接返回、不去数据库。例外是提交序号列(commit_seq)的 索引:本事务 insert 的行还没有号(是 0),它的位置要到提交时才定,不在结果里。

读到的区间会在提交时校验(防幻读):若同样的查询届时会返回不同的行——别的事务往 区间里插了一行、删改了返回的行,或者这次读到的是滞后的副本——提交时抛 RaceCondition ,System 会自动重试。所以"range 查不到就 insert、查到就 update" 的写法是安全的。

截断读(返回了 limit 行)也防幻读,和语法一致,只保护看到的前 limit 行: 区间外的行本来就没读到,它们的增减不算冲突。用 range 判断"有没有"时必须读全 (limit=-1),否则没读到的行会被当成不存在。

Parameters

  • index_name (Any) — 辅助参数,如果不便使用kwargs参数时使用。

  • _left (Any) — 辅助参数,如果不便使用kwargs参数时使用。

  • _right (Any) — 辅助参数,如果不便使用kwargs参数时使用。

  • _group (Any) — 辅助参数,复合索引(groupby)的分组值 {分组列: 值},配合 index_name 使用。

  • kwargs (Any) — 查询字段和区间,例如 level=(1, 10)。只能查询一个字段,且该字段必须有索引。 复合索引(groupby)要同时用等值给出全部分组列,例如 range(level=(1, 10), zone=3), 结果只含这一组的行;区间之外的 kwarg 都是分组值。 默认闭区间,如果要自定义区间,请转换为字符串并开头指定 ( 或 [。所以字符串 边界本身以 ( / [ 开头时(比如玩家名 “[GM]Bob”),要在前面再加一个 [;只查 一个值请用 get,它按字面比较。 区间里没有值(比如两端都是开区间、值又相同)时返回空;下界大于上界报 ValueError。 不限下界或上界时传 -inf / inf(float("inf") 或 np.inf),比如 level=(10, np.inf) 是 10 级及以上;读全表用 id=(-np.inf, np.inf) 并设 limit=-1。只有数值字段能这么写,字符串字段的边界只能是 str / bytes。 整数字段超出类型范围的边界(含 ±inf)钳到类型的极值:int8 字段上 (0, 1000) 就是 (0, 127),不会溢出或报错;小数边界向区间内取整, (0.5, 10) 就是 (1, 10)。

  • 如果要查询的字段和参数冲突,请使用辅助参数方式。
  • limit (Any) — 限制返回的行数,越少越快。负数表示不限制行数。

  • desc (Any) — 是否降序排列。区间照样按 (下界, 上界) 给出。

  • phantom_check (Any) — 提交时是否校验区间,默认 True。读写频繁的区间(如"读最新 N 条消息再插一条"), 且逻辑不依赖"区间里没有别的行"时可关掉,大幅提升性能。关掉后返回的行仍然 参与版本校验,只是不管区间里新增的行。

Returns

返回 numpy.recarray,如果没有查询到数据,返回空 numpy.recarray。 numpy.recarray 是一种 c-struct array。

Notes

如何复合条件查询? “某一组里按某字段排序"请声明复合索引(property_field(groupby=...))。其他组合条件, 请利用python的特性,先在数据库上筛选出最少量的数据,然后本地二次筛选::

items = await session.using(Item).range(level=(10, 20), limit=100)
few_items = items[items.amount < 10]

由于python numpy支持SIMD,比直接在数据库复合查询快。

insert

insert(row: numpy.record) -> None

Source: hetu/data/backend/repo.py:862

向Session中添加一行待插入数据。

只在本地 IdentityMap 检查 unique:同一事务内已有同值行 → 立即抛 UniqueViolation 。 与数据库既有数据的主键 / unique 冲突不在此检查(0 往返),由 commit() 原子判定: 本事务曾 get 观察该值不存在 → RaceCondition (自动重试),否则 → UniqueViolation 。 要提前确认可调用 is_unique_conflicts。

本事务删掉的库里的行,不能再用同一个 id insert(upsert 锚定这个 id 新建也一样), 抛 ValueError:要改这行请直接 update。

提交序号列(commit_seq)由提交脚本发号,insert 时它必须是 0,否则抛 ValueError。

Parameters

  • row (Any) — 待插入的行数据,必须是 c-struct 格式。

update

update(row: numpy.record) -> None

Source: hetu/data/backend/repo.py:927

向Session中添加一行待更新数据。

只在本地 IdentityMap 检查 unique(同事务内重复 → 立即抛 UniqueViolation ); 与数据库既有数据的冲突由 commit() 判定,规则同 insert。

提交序号列(commit_seq)不能改;库里已经有号的行也不能改它的分组列(搬到别的组会和那 一组的号重复),都抛 ValueError。本事务 insert、还没提交的行,以及库里号 ≤ 0(没有号的 历史行)可以改分组列。

Parameters

  • row (np.record) — 待更新的行数据,必须是 c-struct 格式。

upsert

upsert(
    **kwargs: numpy.integer | numpy.floating | numpy.str_ | numpy.bytes_ | numpy.bool | int | float | str | bytes | bool,
) -> hetu.data.backend.repo.UpsertContext

Source: hetu/data/backend/repo.py:1004

使用async with语法,根据Unique索引,查询并返回一行数据,如果不存在则返回新行数据。 在退出上下文时,自动插入新行,或是更新已有行。

Parameters

  • kwargs (Any) — 查询字段和值,例如 id=1234567890。只能查询一个字段,且该字段必须为unique索引。 组内唯一的复合索引(unique=True, groupby=...)要同时给出全部分组列,例如 upsert(name="abc", zone=3),新建的行会写入这些分组值。 值和 get 一样按字面比较,开头的 ( / [ 不是区间标记。 字符串锚定值超过列宽时没有行能匹配,要新建行时抛 ValueError(存进去会被截断,之后 拿这个值查不到它)。

Examples

::

async with session.using(Order).upsert(id=1234567890) as order:
    order.status = "completed"

delete

delete(row_id: int) -> None

Source: hetu/data/backend/repo.py:1042

向Session中添加一行待删除数据。

Parameters

  • row_id (int) — 待删除行的主键ID。

SystemClusters

SystemClusters(*args, **kwargs)

Source: hetu/system/definer.py:47

储存所有System,并分类成共置簇。可以通过它查询System的定义信息,和所属簇id。簇id每次服务器 启动时按簇大小排序分配,每个namespace下的簇id从0重新分配。 System之间components有交集的,表示这些System互相之间可能有事务冲突,形成一个共置簇, 簇和簇之间无交集,绝不会有事务冲突。

此类只负责储存定义,调度器通过此类查询System信息。

Attributes

  • main_namespace (Any) — No description.

Methods

switch_main

switch_main(main_namespace: str) -> None

Source: hetu/system/definer.py:87

把主 namespace 快速访问表重指到另一个已构建的 namespace。

多 app 共享测试进程时(各包 conftest 在收集期已 import 注册),首个 build_clusters 会把所有 namespace 的簇一次建齐,但 main 快速表只指向 首建者;后续 Sandbox 复用已建簇时用本方法重指即可——定义/簇本就按 namespace 隔离共存,无需清表重建(清表重建对多模块包不可靠:reload 不会重执行已缓存子模块里的装饰器)。

systems_of

systems_of(namespace: str | None = None) -> dict[str, hetu.system.definer.SystemDefine]

Source: hetu/system/definer.py:109

某个 namespace(默认主 namespace)的全部 System 定义,含迁入的 global System 与 core pin 占位 System(名字形如 __core_pin_system_*)。返回副本。

get_startup_systems

get_startup_systems(namespace: str | None = None) -> list[str]

Source: hetu/system/definer.py:119

返回所有标记了 on_start=True 的 System 名字(按定义顺序)。

Return names of all systems marked with on_start=True (in definition order).

get_components

get_components(namespace: str | None = None) -> dict[type[BaseComponent], int]

Source: hetu/system/definer.py:132

返回所有被System引用过的Component及其所属簇id

build_endpoints

build_endpoints()

Source: hetu/system/definer.py:310

把System定义复制到EndpointDefines中,作为Endpoint使用


SystemContext

SystemContext(
    caller: int,
    connection_id: int,
    address: str,
    group: str,
    user_data: dict[str, typing.Any],
    timestamp: float,
    request: Any,
    systems: SystemCaller,
    guard_state: dict[str, typing.Any] = <factory>,
    client_limits: list[list[int]] = <factory>,
    server_limits: list[list[int]] = <factory>,
    max_row_sub: int = 0,
    max_index_sub: int = 0,
    max_table_sub: int = 0,
    race_count: int = 0,
    repo: dict[type[BaseComponent], SessionRepository] = <factory>,
    depend: dict[str, collections.abc.Callable] = <factory>,
) -> None

Source: hetu/system/context.py:19

Bases: EndpointContext

System调用时的上下文,继承自 Context 并添加事务相关属性。 每次System执行时由engine创建并作为第一个参数 ctx 传入。

Attributes

  • race_count (int) — 当前事务因 RaceCondition 重试的次数,初始为0。注意:timeout 引发的再次 触发会从0重新计数。

  • repo (dict[type[BaseComponent ], SessionRepository ]) — 当前事务的repo字典,键为Component类,值为对应的 SessionRepository 。 通过 ctx.repo[ComponentClass] 取得并执行 get / range / upsert / update / delete 等CRUD操作;事务结束时统一提交。

  • depend (dict[str, Callable]) — depends 依赖中声明的父事务函数字典,键为System名(可带”:副本名"后缀)。 通过 ctx.depend["system_name"](ctx, ...) 调用以在同一事务中执行。

Methods

session_commit

session_commit() -> dict[type[BaseComponent], dict[int, int]]

Source: hetu/system/context.py:39

提前显式结束事务,提交所有写入操作。如果遇到事务冲突,会抛出异常,因此后续的代码行不会执行。 注意:调用完 session_commit,ctx 将不再能够读写 repo 。且后续不再属于事务, 也就是说遇到宕机/crash可能导致整个函数执行不完全。

Returns

The numbers this commit handed out to commit sequence columns (commit_seq): {component class: {row id: number}}, keyed like ctx.repo (the master class when the System references a duplicate). Only rows this commit inserted into components with a commit sequence column are included; empty dict if there are none. The automatic commit after the System returns gives no numbers, so call this to get them.

这次提交里提交序号列(commit_seq)发出的号:{组件类: {行 id: 号}},组件类 同 ctx.repo 的键(System 引用的是副本组件时也是主组件类)。只含这次 insert 的、 带提交序号列的组件的行,没有这样的行时是空 dict。System 返回之后的自动提交不返回号, 要拿号就调用它。

Examples

>>> @hetu.define_system(
...     namespace="ssw", components=(ChangeLog,), permission=hetu.Permission.USER
... )
... async def submit(ctx: hetu.SystemContext, kind: int):
...     row = ChangeLog.new_row()
...     row.owner, row.kind = ctx.caller, kind
...     await ctx.repo[ChangeLog].insert(row)
...     seqs = await ctx.session_commit()  # 行里的 seq 仍是 0,号看返回值
...     return hetu.ResponseToClient({"seq": seqs[ChangeLog][row.id]})

Notes

如果有任何其他失败,抛出以下异常:redis.exceptions,RaceCondition,UniqueViolation。 异常一般无需特别处理,系统的默认处理方式为:遇到RaceCondition异常,上游系统会自动重试; UniqueViolation 是确定性的主键 / unique 冲突(本事务未曾 get 观察其不存在),不重试。 其他任何异常会记录日志并断开客户端连接。

session_discard

session_discard() -> None

Source: hetu/system/context.py:87

提前显式结束事务,放弃所有写入操作。 注意:调用完 session_discard,ctx 将不再能够读写 repo 。且后续不再属于事务, 也就是说遇到宕机/crash可能导致整个函数执行不完全。


Table

Table(
    comp_cls: type[BaseComponent],
    instance_name: str,
    cluster_id: int,
    backend: Backend,
) -> None

Source: hetu/data/backend/table.py:55

Bases: TableReference

Table表的地址信息加上所属的Backend,能够让你直接去数据库中操作此表。

Attributes

  • backend (Backend) — 内部数据库连接管理实例

  • servant_get_many (Any) — 按 id 列表批量读行(非事务,走 servant),与 servant_get 同款绑定

Methods

servant_get

servant_get(
    row_id: int,
    row_format=<RowFormat.STRUCT: 1>,
) -> numpy.record | dict[str, Any] | None

Source: hetu/data/backend/base.py:942

从数据库直接获取单行数据。

Parameters

  • row_id (Any) — row id主键

  • row_format (Any) — 返回数据解码格式,见 “Returns”

Returns

如果未查询到匹配数据,则返回 None。 否则根据 row_format 参数返回以下格式之一:

  • RowFormat.STRUCT - 默认值 返回 np.record (c-struct) 的单行数据
  • RowFormat.RAW 返回无类型的原始数据 (dict[str, str])
  • RowFormat.TYPED_DICT 返回符合Component定义的,有格式的dict类型。

servant_range

servant_range(
    index_name: str,
    left: int | float | str | bytes | bool,
    right: int | float | str | bytes | bool | None = None,
    limit: int = 10,
    desc: bool = False,
    row_format=<RowFormat.STRUCT: 1>,
    *,
    group: collections.abc.Mapping[str, Any] | None = None,
)

Source: hetu/data/backend/base.py:1072

从数据库直接查询索引 index_name,返回在 [left, right] 闭区间内数据。 如果 right 为 None,则查询等于 left 的数据,限制 limit 条。 复合索引(groupby)要用 group 给出全部分组列的值,结果只含这一组的行。

Parameters

  • index_name (Any) — 查询Component中的哪条索引

  • left (Any) — 查询范围,闭区间。字符串查询时,可以在开头指定是[闭区间,还是(开区间。 如果right不填写,则精确查询等于left的数据。

  • right (Any) — 查询范围,闭区间。字符串查询时,可以在开头指定是[闭区间,还是(开区间。 如果right不填写,则精确查询等于left的数据。

  • limit (Any) — 限制返回的行数,越少越快。负数表示不限制行数。

  • desc (Any) — 是否降序排列

  • row_format (Any) — 返回数据解码格式,见 “Returns”

  • group (Any) — 复合索引的分组值 {分组列: 值},必须正好给出全部分组列;单列索引不能给。

Returns

根据 row_format 参数返回以下格式之一:

  • RowFormat.STRUCT - 默认值 返回 numpy.recarray,如果没有查询到数据,返回空 numpy.recarray。 numpy.recarray 是一种 c-struct array。
  • RowFormat.RAW 返回无类型的原始数据 (dict[str, str]) 列表,如果没有查询到数据,返回空list
  • RowFormat.TYPED_DICT 返回符合Component定义的,有格式的dict类型列表,如果没有查询到数据,返回空list
  • RowFormat.ID_LIST 返回查询到的 row id 列表,如果没有查询到数据,返回空list

Notes

如何复合条件查询? “某一组里按某字段排序"请声明复合索引(property_field(groupby=...)),查询时给出 group。其他组合条件,先在数据库上筛选出最少量的数据,然后本地二次筛选::

items = client.range(ref, "owner", player_id, limit=100)
few_items = items[items.amount < 10]

由于python numpy支持SIMD,比直接在数据库复合查询快。

servant_seq_head

servant_seq_head(group: collections.abc.Mapping[str, Any] | None = None) -> int

Source: hetu/data/backend/base.py:1264

Read the latest number issued by one commit_seq group.

读提交序号列(commit_seq)一个组最近发出的号,也就是这一组发到了第几号。还没发过号是 0, 易失表维护清空之后也是 0。非事务读,走副本,可能落后。

计数器和索引是两个 key,读计数器不和任何一次读在同一个快照里:只能用来发现有新号、监控 积压、报警,不能拿来把游标推过没见到行的号。库外消费方的写法见 seq_read。

Parameters

  • group (Any) — 分组值 {分组列: 值},规则同 range 的 group:带 groupby 的必须正好给出全部分组列, 不带 groupby 的不给。

Returns

这一组最近发出的号,没发过号是 0。

Notes

Redis 上计数器 key 被写成了别的类型时,这里读成 0,不报错;这时提交本身会报 WRONGTYPE。

servant_seq_head_many

servant_seq_head_many(
    groups: collections.abc.Sequence[collections.abc.Mapping[str, typing.Any] | None],
) -> list[int | None]

Source: hetu/data/backend/base.py:1304

Read the latest numbers issued by many commit_seq groups in one round trip.

批量读多个组的计数器,每个组同 seq_head。一次往返:组很多时按块拆成几条 MGET,放在 一个 pipeline 里。返回值和 groups 一一对应;空列表不访问数据库。

逐组返回:计数器被写坏了的组是 None,不抛异常,别的组照常返回,一组坏了不会拖住所有组。 要看是哪个 key、什么值,对这一组调 seq_head。

Parameters

  • groups (Any) — 每一项是一个组的分组值,规则同 seq_head 的 group。

Returns

每个组最近发出的号,没发过号是 0,计数器被写坏了是 None,顺序同 groups。

servant_seq_read

servant_seq_read(
    after: int,
    limit: int = 100,
    *,
    group: collections.abc.Mapping[str, Any] | None = None,
    after_id: int | None = None,
    row_format=<RowFormat.STRUCT: 1>,
) -> hetu.data.backend.base.SeqReadResult[typing.Any]

Source: hetu/data/backend/base.py:1381

Read a commit_seq group incrementally after a cursor, confirming gaps on the way.

给库外消费方用的提交序号列增量读:读游标 after 之后的行,顺带确认缺口。非事务读,走副本, 不需要 master。

先一条 ZRANGE 读这一组在 after 之后的 member(它落到的那个节点上的原子快照),再取行。 号按提交顺序发,一个节点上能读到 n 号,比它小的号要么也读得到,要么那一行已经不在了,所以:

  • 返回号大于 after 的行,按号升序。设 n 是最后一行的号(没有返回行时 n = after), (after, n] 里没出现在结果里的号都已确认不存在,游标推进到 n;
  • 缺口只按这一条 ZRANGE 确认。取行不一定和它落在同一个节点上(读写分离代理、原生 cluster 都按命令分流),读不到的行(取行落到落后的副本、读完索引之后被删了、索引残留)不跳过: 停在它前面,它记为 blocked,下次再读。所以落到哪个节点只影响进度,不会漏行;有只读节点 断了复制、还在回答读请求时,可能一直被它挡住,直到它恢复或者被摘掉;
  • 计数器(seq_head)不和这次读在同一个快照里,不能用来把游标推过没见到行的号。

注意:没有行的号一律当缺口跳过,分不清处理过了才删的、还是还没处理就被删了。裁剪只删号严格 小于所有消费方已经落盘的游标的行,删之前先核对,见文档"binlog 式同步"一节。

Parameters

  • after (Any) — 游标,也就是最后处理过的那一号;从头读给 0。0 <= after < 2^53。

  • limit (Any) — 最多返回的行数,正整数。一次读太多会长时间占住副本,一般几百到几千行。

  • group (Any) — 分组值 {分组列: 值},规则同 range 的 group。

  • after_id (Any) — 游标那一号的行的雪花 id(锚点)。给了就核对序列:游标那一号换了一行、游标那一行没了而 后面有号、组里有重号,都抛 CommitSeqDiverged 。给的时候 after 必须 >= 1。不给就不核对, 也就发现不了号被复用。

  • row_format (Any) — 返回数据解码格式,同 range,但不支持 RowFormat.ID_LIST。

Returns

(rows, blocked)。rows 是号大于 after 的行;blocked 是挡住后面的行的 (号, 行 id),没被挡住是 None。rows 为空且 blocked 为 None:ZRANGE 落到的那个 节点上 after 之后没有任何行(没有新号、最新的行被删了,或者这个节点落后)。

direct_set

direct_set(id_: int, **kwargs: str) -> bool

Source: hetu/data/backend/base.py:1446

UNSAFE! 只用于易失数据! 不会做类型检查!

直接写入属性到数据库,避免session必须要执行get+事务2条指令。 仅支持非索引字段,索引字段更新是非原子性的,必须使用事务。 一些系统级别的临时数据,使用直接写入的方式效率会更高,但不保证数据一致性。

只改已存在的行:行不存在(比如已被删掉),或行里没有要写的字段时,什么都不写, 返回 False;写入了返回 True。不会建出只有这几个字段的残缺行。(以前不返回值, 实现方请补上;调用方只把 False 当作没写上。)

这是维护类写入:不改 _version、不参与乐观锁,也不保证触发订阅通知——行订阅可能 立刻收到,也可能等该行下一次事务写入时一起推;整表订阅收不到。需要订阅方及时看到的数据 请走事务。(Redis 上行频道就是行 key 的 keyspace 通知,会顺带触发;SQLite 后端不发。)

UNSAFE, volatile components only, no type checks. Only updates an existing row: if the row (or one of the fields) does not exist, nothing is written and False is returned; True means the fields were written (it used to return nothing: implementers should add the return value; callers only treat False as not written). A maintenance-class write: it does not bump _version, takes no part in optimistic locking, and is not guaranteed to notify subscribers (a row subscriber may see it at once or only with the row’s next transactional write; table subscribers never do). Use a transaction for data that subscribers must see promptly.


TableReference

TableReference(
    comp_cls: type[BaseComponent],
    instance_name: str,
    cluster_id: int,
) -> None

Source: hetu/data/backend/table.py:28

Table表的地址信息,在后端,组件持久化的目标称为表。 组件实际储存在数据库中时,需要实例名和cluster id等信息,此类封装了这些信息。

Attributes

  • comp_cls (type[BaseComponent ]) — 该表所属的组件类

  • instance_name (str) — 该表所属服务器实例名

  • cluster_id (int) — 该表所属的System簇ID

  • comp_name (str) — 获得组件名称

Methods

is_same_txn_group

is_same_txn_group(other: hetu.data.backend.table.TableReference) -> bool

Source: hetu/data/backend/table.py:42

内部方法,判断和另一个TableReference 是否可以在同一事务中执行


cancel_future_call

cancel_future_call(ctx: hetu.system.context.SystemContext, key: str) -> bool

Source: hetu/system/future.py:327

按 key 删除 ensure_future_call 创建的未来调用(停止 / 重配循环任务)。

返回 True 表示存在并已删除,False 表示该 key 没有对应的未来调用。重配间隔等参数: 先 cancel 再 ensure(ensure 是 ensure-exists,不会就地改参数)。

Cancel a keyed future call created by ensure_future_call. Returns True if it existed and was deleted, False otherwise. To reconfigure (e.g. change interval): cancel then ensure again.

Parameters

  • ctx (Any) — System默认变量

  • key (Any) — 要删除的未来调用的幂等键,与 ensure_future_call 的 key 一致。

Returns

是否存在并删除


create_future_call

create_future_call(
    ctx: hetu.system.context.SystemContext,
    at: float,
    system: str,
    *args,
    timeout: int = 60,
    recurring: bool = False,
)

Source: hetu/system/future.py:174

创建一个未来调用任务,到约定时间后会由内部进程执行该System。 未来调用储存在FutureCalls组件中,服务器重启不会丢失。 timeout不为0时,则保证目标System事务一定成功,且只执行一次。 只执行一次的保证通过call_lock引发的事务冲突实现,会强制要求定义System时开启call_lock。

Parameters

  • ctx (Any) — System默认变量

  • at (Any) — 正数是执行的绝对时间(POSIX时间戳);负数是相对时间,表示延后几秒执行。

  • system (Any) — 未来调用的目标system名

  • *args (Any) — 目标system的参数,注意,只支持可以通过repr转义为string并不丢失信息的参数,比如基础类型。

  • timeout (Any) — 再次调用时间(秒)。如果超过这个时间System调用依然没有成功,就会再次触发调用。 注意:代码错误/数据库错误也会引发timeout重试。如果是代码错误,虽然重试大概率还是失败, 但任务并不会丢失,等程序员修复完代码任务会再次伟大

如果设为0,则不重试,因此不保证任务成功,甚至会丢失。执行时遇到任何错误/程序关闭/Crash, 则未来调用丢失。

如果timeout再次触发时前一次执行还未完成,会引起事务竞态,其中一个事务会被抛弃。 如果前一次已经成功执行,call_lock会触发,跳过执行。

  • 注意:抛弃的只有事务(所有ctx.repo[components]的操作),修改全局变量、写入文件等操作是永久的
  • 注意:ctx.race_count只是事务冲突的计数,timeout引起的再次触发会从0重新计数
  • 注意:非 recurring 时不能超过 call lock 保留期(配置 CALL_LOCK_RETENTION,默认 30 分钟) 的一半,否则抛 ValueError:重投时锁必须还在,才能认出已经执行过
  • recurring (Any) — 设置后,将永不删除此未来调用,每次执行后按timeout时间再次执行。

Returns

返回未来调用的uuid: int

Examples

>>> import hetu
>>> @hetu.define_system(namespace='test', permission=None)
... async def test_future_call(ctx: hetu.SystemContext, *args):
...     # do ctx.repo[...] operations
...     print('Future call test', args)
>>> @hetu.define_system(namespace='test', permission=hetu.Permission.USER, depends=('create_future_call:test',) )
... async def test_future_create(ctx: hetu.SystemContext):
...     await ctx.depend['create_future_call:test'](ctx, -10, 'test_future_call', 'arg1', 'arg2', timeout=5)

示例中,depends依赖使用’:‘符号创建了create_future_call的test副本。 继承System会和对方的簇合并,而create_future_call是常用System,所以使用副本避免System簇过于集中, 增加backend的扩展性,具体参考簇相关的文档。

Notes

  • System执行时的Context是内部服务,而不是用户连接,无法获取用户ID,要自己作为参数传入
  • 不会早于at执行(按执行它的Worker的时钟),System里读到的ctx.timestamp>=at。各Worker 睡到最早一条到期才醒,到点即触发;新建的调用最迟约1秒后被发现,at离创建不到1秒的可能 晚触发最多约1秒
  • 各Worker逐条执行未来调用,事务持续冲突的调用不会一直占着:原地重试约2秒还冲突就放弃 这一轮,继续执行下一条,这条最迟约5秒后重投(timeout更短的按timeout)。一直冲突就一直 跑不成,要缩小System读写的范围。timeout=0的调用放弃就丢了,所以没有这个限制,会重试到 System的retry上限,这期间占着这个Worker的循环

ensure_future_call

ensure_future_call(
    ctx: hetu.system.context.SystemContext,
    key: str,
    at: float,
    system: str,
    *args,
    timeout: int = 60,
    recurring: bool = False,
)

Source: hetu/system/future.py:252

按 key 等幂地确保一个未来调用存在;已存在则原样保留(不更新参数),返回其 id。

与 create_future_call 相同,但用 key 做幂等:同一 key 多次调用只会创建一条。 适合在 on_start System 里播种"开机即起"的全局循环任务(recurring=True), 服务器重启多次也不会重复堆积。

幂等通过 key 的确定性 id 复用 FutureCalls 主键唯一性实现:已存在则直接返回(不写入, 事务空提交),并发同 key 的多余插入会撞主键引发事务竞态并自动重试,最终只保留一条。 一次性调用(recurring=False)执行完就删掉,之后再 ensure 同一个 key 会新建一条,到点照样 执行。

  • 同create_future_call,目标system必须开启call_lock。

Idempotently ensure a single future call exists, keyed by key; if it already exists, keep it as-is (params are NOT updated) and return its id. Useful for seeding a server-wide recurring background task from an on_start system without piling up duplicates across restarts. A one-shot call is deleted once it has run; ensuring the same key again afterwards creates a new call that runs again when due.

Parameters

  • ctx (Any) — System默认变量

  • key (Any) — 幂等键。同一 key 只会存在一条未来调用。

  • at (Any) — 同 create_future_call:正数为绝对 POSIX 时间戳;负数为相对延后秒数。

  • system (Any) — 未来调用的目标 system 名。

  • *args (Any) — 目标 system 的参数(须能 repr 往返还原,如基础类型)。

  • timeout (Any) — 再次调用时间(秒),含义同 create_future_call;recurring=True 时不能为 0。

  • recurring (Any) — 设置后永不删除,按 timeout 周期重复触发。

Returns

返回未来调用的 id: int(由 key 推导的确定性负数 id)

Examples

>>> import hetu
>>> @hetu.define_system(namespace='game', permission=None, call_lock=True,
...                     components=(World,))
... async def world_tick(ctx): ...
>>> @hetu.define_system(namespace='game', permission=None, on_start=True,
...                     depends=('ensure_future_call:game',))
... async def boot(ctx):
...     await ctx.depend['ensure_future_call:game'](
...         ctx, 'game:world_tick', -30, 'world_tick', recurring=True, timeout=30)

开服时 on_start 跑一次 → ensure 幂等 → 重启 N 次也只有一条 → 由 future_call_task 每 ~1 秒轮询、全局只一个 worker 执行、timeout 重试、重启不丢。