feat(dispatch)!: scope stop and fallback to each group

A match in one group must not suppress delivery in another group. Track regular matches and stopped scopes independently, and document the routing-table boundary.

BREAKING CHANGE: stop and fallback no longer apply globally across
groups. Put mutually exclusive routes in the same group and define
fallback routes in each group that needs its own catch-all.
This commit is contained in:
翅膀 committed 2026-10-17 08:39:16 +08:00
1 parent a8418c06d9
commit a2ad4f699e
10 files changed
+78 -26

No files matched your search

+1 -1
View File
@@ -161,7 +161,7 @@ tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
- Store named filter fragments (D1 `d1_fragments`, per group, `GET`/`PUT /admin/api/groups/:groupId/fragments`) as editor-side templates; inserting a fragment inlines its node into the route's `ast` — dispatch never resolves fragment references
- Offer a stateless filter dry-run (`POST /admin/api/test-match`, body `{ node | filters, event?, payload }`) that evaluates in memory and returns `{ matched, explanation }` — no event payload is stored
- Validate route/group config against valibot schemas on load (non-destructive: invalid entries log a warning but still load); `CONFIG_SCHEMA_VERSION` marks the schema version and `migrateRoutes`/`migrateGroups` migrate legacy shapes (e.g. `target` → `targets`)
- Filter routes by group owner restriction (`Group.owners`), group source-platform restriction (`Group.providers`: github/gitea), GitHub App installation restriction (`Group.installationId`), and skip fallback routes whenever a regular route matched; stop evaluating further routes when a matched route has `stop: true`
- Filter routes by group owner restriction (`Group.owners`), group source-platform restriction (`Group.providers`: github/gitea), GitHub App installation restriction (`Group.installationId`), and skip a group's fallback routes whenever a regular route of that group matched; stop evaluating the group's further routes when a matched route has `stop: true` (both scoped per group, so one group's routes never silence another's)
- Auto-provision GitHub App installs: the App's Setup URL flow (`/auth/github/install` choice page + `POST /auth/github/install/bind`, owner-role verified for existing groups) and the `installation.created` webhook fallback both create `inst-{installationId}` groups or bind existing groups
- Enforce role-based access on every admin API: super admins bypass, `owner` manages the group (routes/members/invites/settings), `admin` edits routes, `viewer` is read-only; legacy `adminIds` groups resolve to `owner` members
- Issue single-use 7-day group invite links (`invite:{token}`); accepting joins as admin/viewer (never owner); `ALLOW_SELF_SIGNUP=1` creates a deterministic personal group (`u-{userId}`) on first login
+1 -1
View File
@@ -103,7 +103,7 @@ Routes are stored in D1 (`d1_routes`, seeded from legacy KV `config:routes` on f
]
```
`target.platform` selects the push target: `discord` (default), `telegram`, or `feishu`. Discord targets require `target.channelId` (optional `threadId` for a thread); Telegram targets require `target.chatId` (optional `topicId` for a topic); Feishu targets require `target.chatId` (optional `topicId` for a topic). A route may also set `stop: true` (skip later routes). Routes belong to **groups** (D1 `d1_groups`, seeded from legacy KV `config:groups`) that scope admin access and can restrict which org/user events flow in. See the [Routes & Targets](https://webhooker.docs.elysola.org/guide/routes) and [Groups & Access Control](https://webhooker.docs.elysola.org/guide/groups) guides for the full schema.
`target.platform` selects the push target: `discord` (default), `telegram`, or `feishu`. Discord targets require `target.channelId` (optional `threadId` for a thread); Telegram targets require `target.chatId` (optional `topicId` for a topic); Feishu targets require `target.chatId` (optional `topicId` for a topic). A route may also set `stop: true` (skip later routes of its group). Routes belong to **groups** (D1 `d1_groups`, seeded from legacy KV `config:groups`) that scope admin access and can restrict which org/user events flow in. See the [Routes & Targets](https://webhooker.docs.elysola.org/guide/routes) and [Groups & Access Control](https://webhooker.docs.elysola.org/guide/groups) guides for the full schema.
### Web UI (`/admin`)
+1 -1
View File
@@ -103,7 +103,7 @@ bunx wrangler dev # 启动本地开发服务器
]
```
`target.platform` 选择推送目标:`discord`(默认)、`telegram` 或 `feishu`。Discord 目标需 `target.channelId`(可选 `threadId` 指向子区);Telegram 目标需 `target.chatId`(可选 `topicId` 指向话题);飞书目标需 `target.chatId`(可选 `topicId` 指向子话题)。路由还可设置 `stop: true`(跳过后续路由)。路由隶属于**分组**(D1 `d1_groups`,首次加载时从旧版 KV `config:groups` 同步),分组用于限定管理权限,并可限制哪些组织/用户的事件流入。完整模式见[路由与目标](https://webhooker.docs.elysola.org/zh/guide/routes)与[分组与访问控制](https://webhooker.docs.elysola.org/zh/guide/groups)指南。
`target.platform` 选择推送目标:`discord`(默认)、`telegram` 或 `feishu`。Discord 目标需 `target.channelId`(可选 `threadId` 指向子区);Telegram 目标需 `target.chatId`(可选 `topicId` 指向话题);飞书目标需 `target.chatId`(可选 `topicId` 指向子话题)。路由还可设置 `stop: true`(跳过本分组的后续路由)。路由隶属于**分组**(D1 `d1_groups`,首次加载时从旧版 KV `config:groups` 同步),分组用于限定管理权限,并可限制哪些组织/用户的事件流入。完整模式见[路由与目标](https://webhooker.docs.elysola.org/zh/guide/routes)与[分组与访问控制](https://webhooker.docs.elysola.org/zh/guide/groups)指南。
### Web 控制台(`/admin`)
+6 -4
View File
@@ -219,9 +219,11 @@ const en: Dict = {
"routeEditor.idHint": "Unique, use a-z / 0-9 / dashes",
"routeEditor.enabled": "Route enabled",
"routeEditor.fallback": "Fallback route",
"routeEditor.fallbackHint": "Only fires when no other route matched; filters still apply",
"routeEditor.fallbackHint":
"Only fires when no other route in this group matched; its filters still apply",
"routeEditor.stop": "Stop on match",
"routeEditor.stopHint": "When matched, no further routes are evaluated for this event",
"routeEditor.stopHint":
"When matched, later routes in this group are not evaluated for this event",
"routeEditor.filters": "Filters",
"routeEditor.filtersNote": "(all must match · AND)",
"routeEditor.matchPlaceholder": "match value (* ? wildcards, /regex/)",
@@ -653,9 +655,9 @@ const zh: Dict = {
"routeEditor.idHint": "唯一,使用 a-z / 0-9 / 短横线",
"routeEditor.enabled": "启用路由",
"routeEditor.fallback": "兜底路由",
"routeEditor.fallbackHint": "仅当没有其它路由匹配该事件时才发送,其过滤器仍会生效",
"routeEditor.fallbackHint": "仅当本分组没有其它路由匹配该事件时才发送,其过滤器仍会生效",
"routeEditor.stop": "匹配后停止",
"routeEditor.stopHint": "该路由匹配后,不再评估后续路由",
"routeEditor.stopHint": "该路由匹配后,不再评估本分组的后续路由",
"routeEditor.filters": "过滤器",
"routeEditor.filtersNote": "(全部匹配 · AND)",
"routeEditor.matchPlaceholder": "匹配值(支持 * ? 通配符、/正则/)",
+1 -1
View File
@@ -106,7 +106,7 @@ routes:
# - platform: telegram
# chatId: "-1001234567890"
# Stop routes stop processing further routes when matched.
# Stop routes stop processing further routes of their group when matched.
# - id: exclusive-push
# name: "Exclusive Push"
# enabled: true
+3 -3
View File
@@ -34,14 +34,14 @@ Each entry of `targets` is a push destination, so one route can forward to sever
| Field | Type | Required | Description |
| ---------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `groupId` | string | Yes | Id of the [group](./groups) this route belongs to |
| `fallback` | boolean | No | When `true`, fires only if no non-fallback route matched the event; its own filters are ignored |
| `stop` | boolean | No | When `true` and this route matches, no further routes are evaluated for this event |
| `fallback` | boolean | No | When `true`, fires only if no non-fallback route of the same group matched the event; its filters still apply |
| `stop` | boolean | No | When `true` and this route matches, no further routes of the same group are evaluated for this event |
| `discordRoleIds` | string[] | No | Discord role ids to ping when this route fires; applied to Discord targets only |
| `ast` | object | No | Boolean filter tree (`{all:[...]}` / `{any:[...]}` / `{not:{...}}`); takes precedence over `filters` when present |
## Route Order
Routes are evaluated in the order the console shows them, group by group. To change it, click **Reorder** on the group page, drag routes by their handle (or focus a handle and press <kbd>↑</kbd> / <kbd>↓</kbd>), then **Save order**. The order is stored per group in D1 (`d1_routes.position`, migration `0012`); a database without that migration keeps loading routes in id order.
Routes are evaluated in the order the console shows them, group by group. `stop` and `fallback` act within a group: a matching `stop` route skips the later routes of its own group only, and a group's fallback routes stay silent only when one of that group's regular routes matched — one group never silences another. To change it, click **Reorder** on the group page, drag routes by their handle (or focus a handle and press <kbd>↑</kbd> / <kbd>↓</kbd>), then **Save order**. The order is stored per group in D1 (`d1_routes.position`, migration `0012`); a database without that migration keeps loading routes in id order.
## Discord Role Mentions
+3 -3
View File
@@ -34,14 +34,14 @@
| 字段 | 类型 | 必需 | 说明 |
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------- |
| `groupId` | string | 是 | 路由所属[分组](./groups)的 id |
| `fallback` | boolean | 否 | 为 `true` 时仅在没有其他非 fallback 路由匹配时才触发;其自身过滤器被忽略 |
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估后续路由 |
| `fallback` | boolean | 否 | 为 `true` 时仅在本分组没有其他非 fallback 路由匹配时才触发;其过滤器仍会生效 |
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估本分组的后续路由 |
| `discordRoleIds` | string[] | 否 | 路由触发时要提醒的 Discord 身份组 id;仅对 Discord 目标生效 |
| `ast` | object | 否 | 布尔过滤器树(`{all:[...]}` / `{any:[...]}` / `{not:{...}}`);存在时优先于 `filters` |
## 路由顺序
路由按控制台中显示的顺序逐个分组评估。在分组页点击**调整顺序**,拖动路由左侧的手柄(或聚焦手柄后按 <kbd>↑</kbd> / <kbd>↓</kbd>),再点击**保存顺序**。顺序按分组保存在 D1(`d1_routes.position`,迁移 `0012`);未执行该迁移的数据库会继续按 id 顺序加载路由。
路由按控制台中显示的顺序逐个分组评估。`stop` 与 `fallback` 只在分组内生效:匹配的 `stop` 路由只跳过本分组的后续路由;只有本分组的普通路由匹配时,本分组的兜底路由才不发送——一个分组永远不会屏蔽另一个分组。在分组页点击**调整顺序**,拖动路由左侧的手柄(或聚焦手柄后按 <kbd>↑</kbd> / <kbd>↓</kbd>),再点击**保存顺序**。顺序按分组保存在 D1(`d1_routes.position`,迁移 `0012`);未执行该迁移的数据库会继续按 id 顺序加载路由。
## Discord 身份组提醒
+12 -6
View File
@@ -61,10 +61,15 @@ export async function dispatchEvent(
if (!groupAcceptsOwners(group, owners)) return false;
return groupAcceptsProvider(group, event.provider);
};
const matched = config.routes.filter(
(route) => !route.fallback && matchRoute(route, event) && accepted(route),
// `stop` and `fallback` act within a route's own group (its routing table), so
// one group's routes can never silence another group's.
const scopeOf = (route: Route): string => route.groupId ?? "";
const regularMatched = new Set(
config.routes
.filter((route) => !route.fallback && matchRoute(route, event) && accepted(route))
.map(scopeOf),
);
const anyRegularMatched = matched.length > 0;
const stopped = new Set<string>();
const attempts: DispatchAttempt[] = [];
const sendLogs: SendRecord[] = [];
@@ -88,16 +93,17 @@ export async function dispatchEvent(
const tasks: Promise<void>[] = [];
for (const route of config.routes) {
if (!accepted(route)) continue;
const scope = scopeOf(route);
if (stopped.has(scope) || !accepted(route)) continue;
if (route.fallback) {
if (!anyRegularMatched && matchRoute(route, event)) {
if (!regularMatched.has(scope) && matchRoute(route, event)) {
tasks.push(processRoute(route));
}
continue;
}
if (matchRoute(route, event)) {
tasks.push(processRoute(route));
if (route.stop) break;
if (route.stop) stopped.add(scope);
}
}
await Promise.allSettled(tasks);
+8 -6
View File
@@ -67,15 +67,17 @@ export interface Route {
*/
ast?: FilterNode;
/**
* Fallback route: only fires when no other (non-fallback) route matched the
* event. Multiple fallback routes may exist; they are all skipped whenever at
* least one regular route matches. Its own filters are ignored.
* Fallback route: only fires when no other (non-fallback) route of the same
* group matched the event. Multiple fallback routes may exist; a group's are
* all skipped whenever one of its regular routes matches. Its own filters
* still apply.
*/
fallback?: boolean;
/**
* Stop: when true and this route matches, no further routes are evaluated
* for this event. Useful for exclusive routing where a match should prevent
* fallthrough to subsequent routes.
* Stop: when true and this route matches, no further routes of the same
* group are evaluated for this event (other groups are unaffected). Useful
* for exclusive routing where a match should prevent fallthrough to the
* group's subsequent routes.
*/
stop?: boolean;
/**
+42
View File
@@ -215,6 +215,48 @@ describe("dispatchEvent fallback routing", () => {
expect(sent.filter((u) => u.includes("/222/"))).toHaveLength(1);
});
it("scopes stop and fallback to the route's own group", async () => {
const sent: string[] = [];
mockFetch((url) => {
sent.push(url);
return new Response("{}", { status: 200 });
});
const env = createEnv({ KV: createMockKV(), DB: createMockDB() });
const route = (
id: string,
groupId: string,
extra: Partial<Route>,
channelId: string,
): Route => ({
id,
name: id,
enabled: true,
filters: [{ type: "event", match: "push" }],
targets: [{ channelId }],
groupId,
...extra,
});
const routes: Route[] = [
route("alpha-stop", "alpha", { stop: true }, "301"),
route("alpha-later", "alpha", {}, "302"),
route("zeta-push", "zeta", {}, "303"),
route("zeta-catch-all", "zeta", { fallback: true, filters: [] }, "304"),
route("omega-catch-all", "omega", { fallback: true, filters: [] }, "305"),
route("omega-catch-all-2", "omega", { fallback: true, filters: [] }, "306"),
];
await dispatchEvent({ ...baseConfig, routes }, { event: "push", payload: {} }, env);
const hits = (channel: string): number => sent.filter((u) => u.includes(`/${channel}/`)).length;
// alpha stops after its first match without silencing zeta.
expect(hits("301")).toBe(1);
expect(hits("302")).toBe(0);
expect(hits("303")).toBe(1);
// zeta matched a regular route, omega did not: only omega's fallbacks fire.
expect(hits("304")).toBe(0);
expect(hits("305")).toBe(1);
expect(hits("306")).toBe(1);
});
it("prepends role mentions to the Discord message content", async () => {
const bodies: string[] = [];
mockFetch((url, init) => {