From 376c84853b4c0f594beca992ef5dae8bc9c777d2 Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Sat, 31 Oct 2026 01:03:04 -0700 Subject: [PATCH] fix(events): bound share-handle session rows by the per-connection cap The count across a holder's connections also counted connections that had dropped but weren't reaped yet (a crashed node, a deploy, a network blip the server hasn't noticed), so resubscribes after a reconnect could be refused with `events_subscription_limit`. Rows made through a share handle now count toward the 50-per-connection cap like any other, and with the open-connections cap per account that bounds what one holder can put in the owner's keyspace. The handle index stays for ending rows on retire. Rows are added to it with the row itself and taken out when the row is dropped, and members whose row is gone are cleared when a retire reads it. --- src/backend/controllers/events/limits.ts | 16 +- .../events/EventSubscriptionStore.test.ts | 101 +++------ .../stores/events/EventSubscriptionStore.ts | 194 ++++++------------ src/docs/src/Events/onLocal.md | 2 +- src/docs/src/rate-limits-and-quotas.md | 3 +- 5 files changed, 100 insertions(+), 216 deletions(-) diff --git a/src/backend/controllers/events/limits.ts b/src/backend/controllers/events/limits.ts index 479049022..9bcf3386b 100644 --- a/src/backend/controllers/events/limits.ts +++ b/src/backend/controllers/events/limits.ts @@ -90,20 +90,14 @@ export interface TieredQuota { * away without saying so, so the cap is really on how much a disconnect can * leave behind. A client watching more than a few dozen distinct anchors wants * one subscription on their common parent instead. + * + * With the connections an account may hold open (`MAX_SOCKETS_PER_USER`), this + * is also what bounds the rows a share holder can put in the owner's keyspace. + * A count across connections would also count ones that dropped and haven't + * been reaped yet, and refuse the resubscribes that replace them. */ export const EVENTS_SESSION_SUBSCRIPTIONS_PER_SOCKET = 50; -/** - * Live subscriptions one user may hold through a share handle someone else - * minted for them, across all of their connections. - * - * Those rows sit in the owner's keyspace, where each one costs a filter - * evaluation on the owner's writes, so opening more connections must not let - * the holder add them without bound. The owner's own rows through the handle - * don't count. - */ -export const EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE = 100; - /** * Durable subscriptions one account may hold, across every app. * diff --git a/src/backend/stores/events/EventSubscriptionStore.test.ts b/src/backend/stores/events/EventSubscriptionStore.test.ts index effb25101..e235a0e49 100644 --- a/src/backend/stores/events/EventSubscriptionStore.test.ts +++ b/src/backend/stores/events/EventSubscriptionStore.test.ts @@ -19,10 +19,7 @@ import MockRedis from 'ioredis-mock'; import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { - EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE, - EVENTS_SESSION_SUBSCRIPTIONS_PER_SOCKET, -} from '../../controllers/events/limits.js'; +import { EVENTS_SESSION_SUBSCRIPTIONS_PER_SOCKET } from '../../controllers/events/limits.js'; import { isHttpError } from '../../core/http/HttpError.js'; import type { IConfig } from '../../types.js'; import { @@ -263,7 +260,6 @@ describe('the per-socket cap', () => { describe('rows made through a share handle', () => { const HANDLE = 'kvh-handle-a'; const OTHER_HANDLE = 'kvh-handle-b'; - const CAP = EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE; /** A row in `USER`'s keyspace, made through a handle by `holderUserId`. */ const through = ( @@ -285,78 +281,43 @@ describe('rows made through a share handle', () => { ...over, }); - const isLimit = (err: unknown) => - isHttpError(err) && - err.statusCode === 429 && - err.legacyCode === 'events_subscription_limit'; - - it('holds another user to the cap through one handle, across their connections', async () => { + it('doesn`t let connections that dropped without being reaped refuse a new one', async () => { const holder = USER + 7000; - for (let i = 0; i < CAP; i++) await store.add(through(holder, i)); + const full = EVENTS_SESSION_SUBSCRIPTIONS_PER_SOCKET; + // Two connections at their cap through one handle, gone but not + // reaped: a crashed node, or a blip the server hasn't noticed yet. + for (const socketId of ['socket-old-1', 'socket-old-2']) + for (let i = 0; i < full; i++) + await store.add( + through(holder, i, { + subId: `${socketId}-${i}`, + socketId, + }), + ); - const overflow = through(holder, CAP); - await expect(store.add(overflow)).rejects.toSatisfy(isLimit); - // Rolled back: nothing of the refused row is left to reap or count. - expect( - await redis.smembers(`ev:s:{${holder}}:${overflow.socketId}`), - ).not.toContain(`${USER}|${overflow.token}|${overflow.subId}`); - expect(await redis.scard(`ev:kh:{${USER}}:${HANDLE}`)).toBe(CAP); - - // Another handle has its own room. - await expect( - store.add( - through(holder, CAP + 1, { subject: `kv:${OTHER_HANDLE}:*` }), - ), - ).resolves.toMatchObject({ userId: USER }); + for (let i = 0; i < full; i++) + await expect( + store.add( + through(holder, i, { + subId: `socket-new-${i}`, + socketId: 'socket-new', + }), + ), + ).resolves.toMatchObject({ userId: USER }); }); - it('frees a slot once a row is unsubscribed or its connection goes', async () => { + it('takes a row out of its handle`s index when it goes', async () => { const holder = USER + 7000; - const rows = Array.from({ length: CAP }, (_, i) => through(holder, i)); - for (const row of rows) await store.add(row); + const unsubscribed = through(holder, 0, { socketId: 'socket-a' }); + const reaped = through(holder, 1, { socketId: 'socket-b' }); + await store.add(unsubscribed); + await store.add(reaped); + expect(await redis.scard(`ev:kh:{${USER}}:${HANDLE}`)).toBe(2); - await store.remove(rows[0]); - await expect(store.add(through(holder, CAP))).resolves.toMatchObject({ - userId: USER, - }); - await expect(store.add(through(holder, CAP + 1))).rejects.toSatisfy( - isLimit, - ); + await store.remove(unsubscribed); + await store.reapSocket(holder, 'socket-b'); - // A whole connection's worth. - await store.reapSocket(holder, rows[CAP - 1].socketId); - for (let i = 0; i < 10; i++) - await store.add(through(holder, CAP + 10 + i)); - await expect(store.add(through(holder, CAP + 20))).rejects.toSatisfy( - isLimit, - ); - }); - - it('never counts the owner`s own rows through the handle', async () => { - for (let i = 0; i < CAP + 20; i++) await store.add(through(USER, i)); - const holder = USER + 7000; - for (let i = 0; i < CAP; i++) await store.add(through(holder, i)); - - await expect(store.add(through(holder, CAP))).rejects.toSatisfy( - isLimit, - ); - await expect(store.add(through(USER, CAP + 20))).resolves.toMatchObject( - { userId: USER }, - ); - }); - - it('never lets concurrent adds through one handle exceed the cap', async () => { - const holder = USER + 7000; - const results = await Promise.allSettled( - Array.from({ length: CAP + 10 }, (_, i) => - store.add(through(holder, i)), - ), - ); - - expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength( - CAP, - ); - expect(await redis.scard(`ev:kh:{${USER}}:${HANDLE}`)).toBe(CAP); + expect(await redis.scard(`ev:kh:{${USER}}:${HANDLE}`)).toBe(0); }); it('lists the rows made through the given handles, and no others', async () => { diff --git a/src/backend/stores/events/EventSubscriptionStore.ts b/src/backend/stores/events/EventSubscriptionStore.ts index b5c0bc8a4..d82bf0b79 100644 --- a/src/backend/stores/events/EventSubscriptionStore.ts +++ b/src/backend/stores/events/EventSubscriptionStore.ts @@ -17,10 +17,7 @@ * along with this program. If not, see . */ -import { - EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE, - EVENTS_SESSION_SUBSCRIPTIONS_PER_SOCKET, -} from '../../controllers/events/limits.js'; +import { EVENTS_SESSION_SUBSCRIPTIONS_PER_SOCKET } from '../../controllers/events/limits.js'; import { HttpError } from '../../core/http/HttpError.js'; import { kvHandleFromSubject } from '../../services/events/subjects.js'; import { bumpGeneration } from '../../util/redisGeneration.js'; @@ -294,13 +291,6 @@ const subscriptionLimitReached = (): HttpError => { legacyCode: 'events_subscription_limit' }, ); -const kvHandleLimitReached = (): HttpError => - new HttpError( - 429, - `You may hold ${EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE} live subscriptions through one share handle`, - { legacyCode: 'events_subscription_limit' }, - ); - /** What a refresh kept alive, and the rows it let go. */ export interface RefreshResult { /** Every (owner, token) the socket still holds, value variants included. */ @@ -363,8 +353,7 @@ export class EventSubscriptionStore extends PuterStore { * * The cap is decided on the cardinality after `sadd`, rolling the member * back when over — `scard` then `sadd` would let two concurrent adds both - * pass. A row made through a share handle is also indexed under it, and - * held to the per-handle cap when its holder isn't the owner. + * pass. */ async add(sub: SessionSubscription): Promise { const { holderUserId, ownerUserId, socketId, token, subId } = sub; @@ -392,21 +381,6 @@ export class EventSubscriptionStore extends PuterStore { throw counted?.[0] ?? subscriptionLimitReached(); } - const handle = kvHandleFromSubject(sub.subject); - if (handle !== null) { - let indexed = false; - try { - indexed = await this.#indexKvHandleRow(sub, handle); - } finally { - if (!indexed) - await this.clients.redis.srem( - socketKey(holderUserId, socketId), - ref, - ); - } - if (!indexed) throw kvHandleLimitReached(); - } - const counts = await this.#writeRow(sub); await this.#keepDurableWindow(ownerUserId, [token]); @@ -421,88 +395,11 @@ export class EventSubscriptionStore extends PuterStore { }; } - /** - * Add a row to its handle's index. `false`, with the member taken back out, - * when the row's holder isn't the owner and already holds the cap through - * this handle. Members whose connection is gone are only cleared once the - * count is over, so the common add is one round trip. - */ - async #indexKvHandleRow( - sub: SessionSubscription, - handle: string, - ): Promise { - const key = kvHandleKey(sub.ownerUserId, handle); - const member = kvHandleMember(sub); - const index = this.clients.redis.pipeline(); - index.sadd(key, member); - index.expire(key, SESSION_SUBSCRIPTION_TTL_SECONDS); - index.scard(key); - const counted = ((await index.exec()) ?? [])[2]; - if (sub.holderUserId === sub.ownerUserId) return true; - if ( - !counted?.[0] && - Number(counted?.[1]) <= EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE - ) - return true; - - const live = await this.#liveKvHandleRefs(sub.ownerUserId, key); - const held = live.filter( - (ref) => ref.holderUserId === sub.holderUserId, - ).length; - if (held <= EVENTS_SESSION_SUBSCRIPTIONS_PER_KV_HANDLE) return true; - await this.clients.redis.srem(key, member); - return false; - } - - /** - * A handle index's members whose socket still holds them. The rest are - * removed: an unsubscribe, a reap or a socket that died without one. - */ - async #liveKvHandleRefs( - ownerUserId: number, - key: string, - ): Promise { - const stale: string[] = []; - const byHolder = new Map>(); - for (const member of await this.clients.redis.smembers(key)) { - const ref = parseKvHandleMember(member); - if (!ref) { - stale.push(member); - continue; - } - byHolder.set(ref.holderUserId, [ - ...(byHolder.get(ref.holderUserId) ?? []), - [member, ref], - ]); - } - - const live: KvHandleRef[] = []; - // One pipeline per holder: their socket sets share a slot. - for (const [holderUserId, held] of byHolder) { - const check = this.clients.redis.pipeline(); - for (const [, ref] of held) - check.sismember( - socketKey(holderUserId, ref.socketId), - socketRef({ - ownerUserId, - token: ref.token, - subId: ref.subId, - }), - ); - const results = (await check.exec()) ?? []; - held.forEach(([member, ref], i) => { - if (Number(results[i]?.[1]) === 1) live.push(ref); - else stale.push(member); - }); - } - if (stale.length > 0) await this.clients.redis.srem(key, ...stale); - return live; - } - /** * The session rows made through these share handles in one owner's * keyspace, for ending them when the handles retire. A handle never used - * from this region costs one read. + * from this region costs one read. Index members whose row is gone are + * cleared on the way. */ async listForKvHandles( ownerUserId: number, @@ -512,33 +409,46 @@ export class EventSubscriptionStore extends PuterStore { const read = this.clients.redis.pipeline(); for (const handle of handles) read.smembers(kvHandleKey(ownerUserId, handle)); - const indexed = ((await read.exec()) ?? []).flatMap(([err, raw]) => - err ? [] : ((raw as string[] | null) ?? []), + const indexed = ((await read.exec()) ?? []).flatMap(([err, raw], i) => + err + ? [] + : ((raw as string[] | null) ?? []).map((member) => ({ + key: kvHandleKey(ownerUserId, handles[i]), + member, + ref: parseKvHandleMember(member), + })), ); - const refs = indexed - .map(parseKvHandleMember) - .filter((ref): ref is KvHandleRef => ref !== null); - if (refs.length === 0) return []; + if (indexed.length === 0) return []; const rows = this.clients.redis.pipeline(); - for (const ref of refs) - rows.hget(tokenKey(ownerUserId, ref.token), ref.subId); + for (const { ref } of indexed) + if (ref) rows.hget(tokenKey(ownerUserId, ref.token), ref.subId); const results = (await rows.exec()) ?? []; - return refs.flatMap((ref, i) => { - const raw = results[i]?.[1]; + + const found: SessionSubscription[] = []; + const gone = this.clients.redis.pipeline(); + let at = 0; + for (const { key, member, ref } of indexed) { + const raw = ref ? results[at++]?.[1] : null; const row = typeof raw === 'string' ? parseRow(raw) : null; - return row?.socketId === ref.socketId && + if ( + ref && + row?.socketId === ref.socketId && row.holderUserId === ref.holderUserId - ? [row as SessionSubscription] - : []; - }); + ) + found.push(row as SessionSubscription); + else gone.srem(key, member); + } + if (found.length < indexed.length) await gone.exec(); + return found; } /** - * Write one row's hash entry, watched-set membership and session counts. - * Returns the resulting counts for that token — `values` only for a row - * asking for KV values. Shared by `add` and `reanchorSession`, which both - * need the row in place before any ref names it. + * Write one row's hash entry, watched-set membership and session counts, + * and index it under its share handle if it was made through one. Returns + * the resulting counts for that token — `values` only for a row asking for + * KV values. Shared by `add` and `reanchorSession`, which both need the row + * in place before any ref names it. */ async #writeRow( sub: SessionSubscription, @@ -563,6 +473,14 @@ export class EventSubscriptionStore extends PuterStore { sessionCountKey(ownerUserId), SESSION_SUBSCRIPTION_TTL_SECONDS, ); + const handle = kvHandleFromSubject(sub.subject); + if (handle !== null) { + rows.sadd(kvHandleKey(ownerUserId, handle), kvHandleMember(sub)); + rows.expire( + kvHandleKey(ownerUserId, handle), + SESSION_SUBSCRIPTION_TTL_SECONDS, + ); + } const results = (await rows.exec()) ?? []; return { rows: Number(results[4]?.[1]), @@ -869,18 +787,30 @@ export class EventSubscriptionStore extends PuterStore { drop.hdel(tokenKey(ownerUserId, token), subId); } const dropResults = (await drop.exec()) ?? []; - const valued = rows.flatMap(({ token }, i) => { + const dropped = rows.map((_ref, i) => { const raw = dropResults[2 * i]?.[1]; - if (Number(dropResults[2 * i + 1]?.[1]) !== 1) return []; + if (Number(dropResults[2 * i + 1]?.[1]) !== 1) return null; const row = typeof raw === 'string' ? parseRow(raw) : null; - return row?.socketId !== undefined && row.includeValue === true - ? [valueWatchToken(token)] - : []; + return row?.socketId !== undefined + ? (row as SessionSubscription) + : null; }); + const valued = rows.flatMap(({ token }, i) => + dropped[i]?.includeValue === true ? [valueWatchToken(token)] : [], + ); const tokens = [...new Set(rows.map((row) => row.token))]; const counts = this.clients.redis.pipeline(); for (const token of tokens) counts.hlen(tokenKey(ownerUserId, token)); + // After the counts, so the result indexes above still line up. + for (const row of dropped) { + const handle = row ? kvHandleFromSubject(row.subject) : null; + if (row && handle !== null) + counts.srem( + kvHandleKey(ownerUserId, handle), + kvHandleMember(row), + ); + } const results = (await counts.exec()) ?? []; const orphaned = tokens.filter( @@ -988,8 +918,8 @@ export class EventSubscriptionStore extends PuterStore { tokenKey(ownerUserId, token), SESSION_SUBSCRIPTION_TTL_SECONDS, ); - // Re-added as well as renewed, so an index that lapsed counts the - // rows it still has. + // Re-added as well as renewed, so an index that lapsed still finds + // the rows a retire has to end. for (const { row, handle } of kept) { if (!row || handle === null) continue; const key = kvHandleKey(ownerUserId, handle); diff --git a/src/docs/src/Events/onLocal.md b/src/docs/src/Events/onLocal.md index 6c2ba2d84..0e1fbb070 100644 --- a/src/docs/src/Events/onLocal.md +++ b/src/docs/src/Events/onLocal.md @@ -59,7 +59,7 @@ The promise rejects with `{ message, code }`: | `events_cross_app_disabled` | The subject names another app's key-value data, and that's turned off on this server. | | `forbidden` | The other app doesn't share its data, or your app hasn't been granted read access to its key-value data (see [`puter.perms.request('appData')`](/Perms/appData/)). | | `subject_does_not_exist` | The subject doesn't exist, or this account can't read it. | -| `events_subscription_limit` | This connection already has 50 subscriptions, or you already have 100 through this share handle across all your connections. | +| `events_subscription_limit` | This connection already has 50 subscriptions. | | `too_many_requests` | Over the subscribe rate limit. | | `events_disabled` | Events aren't enabled on this server. | | `reauth_required` | The session behind this connection is no longer valid. | diff --git a/src/docs/src/rate-limits-and-quotas.md b/src/docs/src/rate-limits-and-quotas.md index cb5164a24..975523eca 100644 --- a/src/docs/src/rate-limits-and-quotas.md +++ b/src/docs/src/rate-limits-and-quotas.md @@ -518,10 +518,9 @@ See [Events](/Events/) for an overview, [`onLocal()`](/Events/subjects/#gaps) fo | KV share handles | Per user, per app | 10,000 | 2,000 | 0 | | KV share handles with one other user | Per owner and holder | 256 | 256 | 0 | | Session subscriptions | Per connection | 50 | 50 | 50 | -| Session subscriptions through one KV share handle | Per holder, all connections | 100 | 100 | 100 | - Over a subscription limit: `events_subscription_limit`. Over a share-handle limit: `events_kv_handle_limit_reached`. -- The limit through one share handle counts the holder's session subscriptions in one region. The owner's own subscriptions through the handle don't count. Unsubscribing or closing the connection frees a slot. +- Session subscriptions through a share handle count toward the limit per connection like any other. With the [open connections per account](#live-connections), that limit is what bounds how many one holder can have. - Anonymous accounts get `events_durable_requires_account` for persistent subscriptions and `events_kv_handle_requires_account` for share handles. - Unsubscribing or revoking frees a slot immediately. Revoked handles don't count. They stay in [`puter.kv.listSharedByMe()`](/KV/listSharedByMe/) for 30 days after they stop, and are then deleted. - A [`puter.kv.share()`](/KV/share/) call with several recipients is refused as a whole with `events_kv_handle_limit_reached` when its new shares would go over the all-apps or per-app limit. Sharing a prefix again with a user who already has it takes no slot. The limit per holder applies to each recipient on its own, and a recipient over it gets the error on their own item.