Skip to content

Commit 2f0ea78

Browse files
phasenullclaude
andcommitted
notifications: setOff(user, kinds), a player's switched-off kinds (prefs)
TypeTorch.notifications().setOff(user: Player | number, kinds: string[]): boolean (server) queues a { op: "prefs", u, off, rev } item through the same swap-safe queue as want / drop. It replaces the user's whole off set (at most 32 kind names, duplicates removed, sorted); a newer call replaces one still waiting for the same user. The backend skips that user's intents of an off kind whoever issued them (pref_off) and keeps them. Protocol check cleanPrefs / pushPrefs / the JSON in protocol.ts, a client stub, the inert stub, the Lune test extended, README. Version 0.7.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 58e445a commit 2f0ea78

8 files changed

Lines changed: 123 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,9 @@ TypeTorch.runDetached(() => store.StartSessionAsync(`Player_${userId}`)).then((p
369369
// Server: intents (upsert by user + kind + key; offline players by UserId), batched and swap-safe.
370370
notify.want(userIdOrPlayer, "gift_new", { key: letterId, until: expiresAt, params: { gift: "5 coins" }, data: `mail:${letterId}` });
371371
notify.drop(userIdOrPlayer, "streak", "20034", "played"); // no key: every key of the kind
372+
// The kinds the player switched off in your settings: REPLACES their set ([] = all on), at most 32 names. The backend
373+
// skips those intents whoever issued them (pref_off) and keeps them, so switching a kind back on resumes it.
374+
notify.setOff(player, ["daily", "quests"]);
372375
trove.add(notify.onOpen((player, open) => openMail(player, open.data))); // open: { nid, kind, data, ageSeconds, first }
373376
// Client: Roblox's opt-in prompt, once per session (show your own explainer first). Yields until it closes.
374377
const result = TypeTorch.notifications().promptOptIn("streak_2"); // "shown" | "unavailable" | "error" | "busy" | "already"

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@typetorch/framework",
3-
"version": "0.6.0",
3+
"version": "0.7.0",
44
"description": "TypeTorch framework for roblox-ts: hot-swappable modules (dependency injection, lifecycle, troves), guarded networking, hot assets and the in-game dev menu. Ships inside every TypeTorch artifact.",
55
"license": "MIT",
66
"author": "TypeTorch",

‎scripts/test-notifications.luau‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
--!nocheck
22
-- Offline test of the notifications' pure parts (plans/29) under Lune: the signed launch token (the contract's shared
33
-- vector, sign -> verify, wrong user, too old, previous key within / after 7 days, bad sig, format), the key hash, the
4-
-- intent checks, the queue (rev order, batching at 200, the body JSON, requeue after a failure, a swap's handover) and
5-
-- the client's opt-in rows. Run after `bun run build`:
4+
-- intent checks, the queue (rev order, batching at 200, the body JSON, requeue after a failure, a swap's handover),
5+
-- the prefs item (setOff) and the client's opt-in rows. Run after `bun run build`:
66
-- cd ../kernel && lune run ../framework/scripts/test-notifications.luau ../framework/
77
local fs = require("@lune/fs")
88
local luau = require("@lune/luau")
@@ -307,6 +307,41 @@ do
307307
check("opened state: junk", P.readOpenedState({ state = "x" }) == nil and P.readOpenedState(nil) == nil)
308308
end
309309

310+
-- Prefs (setOff): the user's switched-off kinds -------------------------------------------------------------------------------
311+
do
312+
local prefs = P.cleanPrefs(42, { "streak", "gift_new", "streak", "daily" }, 11)
313+
check("prefs: item, unique and sorted", type(prefs) == "table" and prefs.op == "prefs" and prefs.u == 42 and table.concat(prefs.off, ",") == "daily,gift_new,streak" and prefs.rev == 11, prefs)
314+
check("prefs: empty = every kind on", type(P.cleanPrefs(42, {}, 1)) == "table" and #P.cleanPrefs(42, {}, 1).off == 0)
315+
check("prefs: bad user", type(P.cleanPrefs(0, {}, 1)) == "string" and type(P.cleanPrefs(1.5, {}, 1)) == "string")
316+
check("prefs: bad kind", type(P.cleanPrefs(1, { "Gift" }, 1)) == "string" and type(P.cleanPrefs(1, { string.rep("a", 25) }, 1)) == "string" and type(P.cleanPrefs(1, { 5 }, 1)) == "string")
317+
check("prefs: not a list", type(P.cleanPrefs(1, "gift", 1)) == "string" and type(P.cleanPrefs(1, { a = "gift" }, 1)) == "string" and type(P.cleanPrefs(1, nil, 1)) == "string")
318+
local many = {}
319+
for index = 1, P.OFF_MAX + 1 do
320+
table.insert(many, "k" .. index)
321+
end
322+
check("prefs: over the cap", type(P.cleanPrefs(1, many, 1)) == "string")
323+
local capped = table.clone(many)
324+
capped[P.OFF_MAX + 1] = "k1"
325+
check("prefs: duplicates don't count toward the cap", type(P.cleanPrefs(1, capped, 1)) == "table" and #P.cleanPrefs(1, capped, 1).off == P.OFF_MAX)
326+
check("encode prefs", P.encodeItem(prefs, quote) == '{"op":"prefs","u":42,"off":["daily","gift_new","streak"],"rev":11}', P.encodeItem(prefs, quote))
327+
check("encode prefs: empty list", P.encodeItem(P.cleanPrefs(7, {}, 1762500000123), quote) == '{"op":"prefs","u":7,"off":[],"rev":1762500000123}')
328+
check("encode prefs: valid JSON", serde.decode("json", P.encodeItem(prefs, quote)).off[2] == "gift_new")
329+
330+
-- The queue keeps one prefs item per user (the newest), behind the other items; batching and requeue as any item.
331+
local state = P.newQueueState()
332+
P.pushItem(state, P.cleanWant(42, "daily", nil, P.nextRev(state, 1762500000)))
333+
P.pushPrefs(state, P.cleanPrefs(42, { "daily" }, P.nextRev(state, 1762500000)))
334+
P.pushPrefs(state, P.cleanPrefs(43, { "streak" }, P.nextRev(state, 1762500000)))
335+
P.pushPrefs(state, P.cleanPrefs(42, {}, P.nextRev(state, 1762500000)))
336+
check("prefs queue: one per user, the newest last", #state.items == 3 and state.items[1].op == "want" and state.items[2].u == 43 and state.items[3].u == 42 and #state.items[3].off == 0)
337+
check("prefs queue: revs keep the call order", state.items[3].rev > state.items[2].rev and state.items[2].rev > state.items[1].rev)
338+
local batch, body = unpackBatch(P.takeBatch(state, quote))
339+
local parsed = serde.decode("json", body)
340+
check("prefs batch: body", #batch == 3 and parsed.items[3].op == "prefs" and #parsed.items[3].off == 0 and parsed.items[2].off[1] == "streak")
341+
local handed = serde.decode("json", serde.encode("json", { items = batch }))
342+
check("prefs: plain data across a swap", handed.items[2].off[1] == "streak")
343+
end
344+
310345
-- Opt-in rows from a client ----------------------------------------------------------------------------------------------------
311346
do
312347
local check_ = P.cleanOptInRow({ name = "optin_check", where = "streak_2", can = true, extra = "dropped" })

‎src/notifications/api.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,15 @@ export interface Notifications {
4040
want(user: Player | number, kind: string, options?: WantOptions): boolean;
4141
/** Server: drops the intent (no key: every key of that kind), e.g. the player already did it. Row `drop`. */
4242
drop(user: Player | number, kind: string, key?: string, why?: string): boolean;
43+
/**
44+
* Server: the kinds this user switched off in the game's settings. REPLACES the user's whole off set (an empty list =
45+
* every kind on); at most 32 kind names (1-24 of [a-z0-9_]; need not be pushed yet), duplicates ignored. The backend
46+
* then skips that user's intents of those kinds whoever issued them (another server's `want` for an offline player
47+
* too), keeping them: switched back on, an intent whose window is still open goes out. Test sends and custom one-offs
48+
* ignore it. Batched and swap-safe like `want` (the latest call wins); false (with a warning) when refused here.
49+
* Call it whenever the player's setting changes, and once per join if the game is the source of truth.
50+
*/
51+
setOff(user: Player | number, kinds: string[]): boolean;
4352
/**
4453
* Server: `callback(player, open)` for each player who joined from a notification (verified launch data), including
4554
* those who joined before the first callback connected in this generation. Returns a disconnect (for the trove).

‎src/notifications/client.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,11 @@ export class NotifyClient implements Notifications {
6161
return false;
6262
}
6363

64+
setOff(_user: Player | number, _kinds: string[]): boolean {
65+
$warn("[notifications] setOff() is server-only");
66+
return false;
67+
}
68+
6469
onOpen(_callback: (player: Player, open: NotifyOpen) => void): () => void {
6570
$warn("[notifications] onOpen() is server-only (the launch data is verified on the server)");
6671
return () => {};

‎src/notifications/protocol.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ export const PARAM_VALUE_MAX = 64;
2828
export const DATA_MAX = 64;
2929
export const TEMPLATE_MAX = 128;
3030
export const WHY_MAX = 64;
31+
/** Kinds one user can switch off at most (`setOff`). */
32+
export const OFF_MAX = 32;
3133

3234
export interface WantItem {
3335
op: "want";
@@ -59,7 +61,16 @@ export interface PresenceItem {
5961
at: number;
6062
}
6163

62-
export type Item = WantItem | DropItem | PresenceItem;
64+
/** Replaces the user's switched-off kinds (the backend skips their intents, whoever issued them: `pref_off`). */
65+
export interface PrefsItem {
66+
op: "prefs";
67+
u: number;
68+
/** Sorted, unique kind names (at most OFF_MAX); empty = every kind on. */
69+
off: string[];
70+
rev: number;
71+
}
72+
73+
export type Item = WantItem | DropItem | PresenceItem | PrefsItem;
6374

6475
/** `want` options as game code passes them (checked by `cleanWant`). */
6576
export interface WantOptions {
@@ -197,6 +208,41 @@ export function cleanDrop(userId: unknown, kind: unknown, key: unknown, why: unk
197208
return item;
198209
}
199210

211+
/**
212+
* The prefs item (`setOff`): the kinds as a list of kind names, duplicates removed, sorted; at most OFF_MAX. Kinds need
213+
* not be in the pushed config yet (a kind added later is covered at once).
214+
*/
215+
export function cleanPrefs(userId: unknown, kinds: unknown, rev: number): PrefsItem | string {
216+
if (!isUserId(userId)) return "the user must be a Player or a positive UserId";
217+
if (!typeIs(kinds, "table")) return "kinds must be a list of kind names";
218+
const list = kinds as unknown[];
219+
let count = 0;
220+
for (const [index] of pairs(list as object)) {
221+
count += 1;
222+
if (!typeIs(index, "number")) return "kinds must be a list of kind names";
223+
}
224+
if (count !== list.size()) return "kinds must be a list of kind names";
225+
const seen = new Set<string>();
226+
const off = new Array<string>();
227+
for (const kind of list) {
228+
if (!isKind(kind)) return "every kind must be 1-24 of [a-z0-9_]";
229+
if (seen.has(kind)) continue;
230+
seen.add(kind);
231+
off.push(kind);
232+
}
233+
if (off.size() > OFF_MAX) return `at most ${OFF_MAX} kinds`;
234+
off.sort();
235+
return { op: "prefs", u: userId, off, rev };
236+
}
237+
238+
/** Adds a prefs item, replacing one for the same user still waiting (only the newest set matters). */
239+
export function pushPrefs(state: QueueState, item: PrefsItem) {
240+
const kept = new Array<Item>();
241+
for (const entry of state.items) if (!(entry.op === "prefs" && entry.u === item.u)) kept.push(entry);
242+
state.items = kept;
243+
pushItem(state, item);
244+
}
245+
200246
/** Adds an item; over the cap drops presence items first (the backend re-learns presence on the next join), then the oldest. */
201247
export function pushItem(state: QueueState, item: Item) {
202248
state.items.push(item);
@@ -230,6 +276,10 @@ export function encodeItem(item: Item, quote: Quote): string {
230276
parts.push(`"online":${item.online ? "true" : "false"}`, `"at":${int(item.at)}`);
231277
return `{${parts.join(",")}}`;
232278
}
279+
if (item.op === "prefs") {
280+
parts.push(`"off":[${item.off.map((kind) => quote(kind)).join(",")}]`, `"rev":${int(item.rev)}`);
281+
return `{${parts.join(",")}}`;
282+
}
233283
parts.push(`"k":${quote(item.k)}`);
234284
if (item.key !== undefined) parts.push(`"key":${quote(item.key)}`);
235285
if (item.op === "want") {

‎src/notifications/server.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@ import {
1414
CHANNEL,
1515
cleanDrop,
1616
cleanOptInRow,
17+
cleanPrefs,
1718
cleanWant,
1819
newQueueState,
1920
nextRev,
2021
pushCall,
2122
pushItem,
23+
pushPrefs,
2224
readIntentsAnswer,
2325
readOpenedState,
2426
requeueItems,
@@ -245,6 +247,17 @@ export class NotifyServer implements Notifications {
245247
return true;
246248
}
247249

250+
setOff(user: Player | number, kinds: string[]): boolean {
251+
if (this.stopped) return false;
252+
const item = cleanPrefs(userIdOf(user), kinds, nextRev(this.store.queue, os.time()));
253+
if (typeIs(item, "string")) {
254+
this.warn(`setOff refused: ${item}`);
255+
return false;
256+
}
257+
pushPrefs(this.store.queue, item);
258+
return true;
259+
}
260+
248261
onOpen(callback: (player: Player, open: NotifyOpen) => void): () => void {
249262
this.listeners.add(callback);
250263
// Opens that no callback has seen yet (players who joined before the game connected one).

‎src/typetorch.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ export interface TypeTorchApi {
266266
// Notifications (plans/29) --------------------------------------------------------------------------------------------
267267
/**
268268
* Native Roblox experience notifications through the TypeTorch backend. Server: `want` / `drop` intents (batched,
269-
* swap-safe, offline players by UserId), `onOpen` for players who joined from a verified notification. Client:
269+
* swap-safe, offline players by UserId), `setOff` (a player's switched-off kinds), `onOpen` for players who joined from a verified notification. Client:
270270
* `promptOptIn(where)`. Outside a running generation every call is a no-op. See src/notifications/api.ts.
271271
*/
272272
notifications(): Notifications;
@@ -582,6 +582,9 @@ const INERT_NOTIFICATIONS: Notifications = {
582582
want() {
583583
return false;
584584
},
585+
setOff() {
586+
return false;
587+
},
585588
drop() {
586589
return false;
587590
},

0 commit comments

Comments
 (0)