Skip to content

Commit 5e3b8e6

Browse files
authored
Merge pull request #20 from typetorch/feat/live-events
Scheduled live events: liveConfig follows the signed game["tt.events"] schedule
2 parents 637848e + b741a2e commit 5e3b8e6

5 files changed

Lines changed: 462 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,24 @@ TypeTorch.runDetached(() => store.StartSessionAsync(`Player_${userId}`)).then((p
352352
changes; generation-scoped). The default without a record or key, when `parse` throws (warned per value), and on older
353353
kernels (warned once: "needs kernel 0.3.8"; no ConfigService fallback). `TypeTorch.settings()` is the whole copy
354354
(`seq`, `at`, `game`, `analytics`, `fleet`, ...): server only, it holds tokens.
355+
- **Scheduled live events** (`liveEvents()`, server only): the explorer's Live events page schedules "double cash,
356+
Saturday 12:00 to Sunday 23:59 UTC" as a change to `game` keys, and the owner signs the schedule with the CLI like any
357+
other value (`typetorch settings set game.tt.events -`, the page gives the exact command). While an event runs
358+
(`start <= now < end` on the server's own clock) its values replace the record's `game[key]` for `liveConfig`, so
359+
`get()` and `onChanged` switch at the start and end times with no message: a server that starts mid-event has it at
360+
once, and the event ends on time even when the backend is down. Cancelling = signing the schedule without it. The
361+
game only reads its usual `liveConfig` keys; `parse` still checks an event's value (keep your bounds there):
362+
363+
```ts
364+
const multiplier = TypeTorch.liveConfig("cash.multiplier", { default: 1, parse: (raw) => (typeIs(raw, "number") && raw >= 1 && raw <= 3 ? raw : 1) });
365+
const events = TypeTorch.liveEvents();
366+
events.active(); // [{ id, name, startsAt, endsAt, set }]: "Double cash ends in 3h"
367+
this.trove.add(events.onChanged((active) => this.showBanner(active)));
368+
```
369+
370+
The schedule is `game["tt.events"] = { v: 1, events: [{ id, name, start, end, set: { [key]: JSON } }] }` (unix
371+
seconds); two events on one key at once: the later start wins. Nothing unsigned reaches servers: the backend only
372+
prepares the JSON.
355373
- **`runDetached(fn)`** (kernel 0.3.8, server only): runs `fn` on a thread the kernel owns, so a deploy's hard stop
356374
(which kills this generation's threads mid-call) can't cut it off: for ProfileStore / ProfileService loads, saves and
357375
releases. Returns a Promise that settles while this generation runs; after a swap the result is dropped, so a job
@@ -672,7 +690,7 @@ bun run build # rbxtsc --type package -> out/
672690
Attention issues.
673691
The others, each on the compiled `out/`: `test-hot-assets` (manifest parser, AssetSync decisions incl. the backup
674692
vouch, live-copy rules), `test-messaging` (messaging and the server list), `test-settings` (`liveConfig` and the
675-
settings lines), `test-detached` (`runDetached`), `test-dev-access` (the dev-only tools rule and every gate through
693+
settings lines), `test-live-events` (scheduled live events on a fake clock), `test-detached` (`runDetached`), `test-dev-access` (the dev-only tools rule and every gate through
676694
it), `test-remote-debug` (the remote debug ops and their limits), `test-net-inspect` (packet capture),
677695
`test-explorer-core` (Dex), `test-toolbox-sanitize` (the Creator Store sanitizer), `test-sha256` (SHA-256 / HMAC in util and the
678696
pairing-code fingerprint), `test-notifications` (the launch token with the contract's shared vector, intent checks,

‎scripts/test-live-events.luau‎

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
--!nocheck
2+
-- Offline test of scheduled live events (out/settings.luau: the signed `game["tt.events"]` schedule, liveConfig's
3+
-- overrides while an event runs, liveEvents()) under Lune, against a stub kernel and a fake clock (os.time): an event
4+
-- before, during and after its window; a server that starts mid-event; the switch at the start and end times with no
5+
-- new settings copy (the backend down); the latest start wins on one key; bad entries skipped; a cancelled event
6+
-- (a new copy without it) ends at once; the generation stop ends the timer; server only.
7+
-- Run after the build:
8+
-- cd ../kernel && lune run ../framework/scripts/test-live-events.luau ../framework/
9+
local fs = require("@lune/fs")
10+
local luau = require("@lune/luau")
11+
local process = require("@lune/process")
12+
local serde = require("@lune/serde")
13+
local task = require("@lune/task")
14+
local root = process.args[1] or "./"
15+
16+
local passed, failed = 0, 0
17+
local function check(label, condition, detail)
18+
if condition then
19+
passed += 1
20+
else
21+
failed += 1
22+
print("FAIL " .. label .. (if detail ~= nil then ": " .. tostring(detail) else ""))
23+
end
24+
end
25+
local function has(text, needle)
26+
return string.find(tostring(text), needle, 1, true) ~= nil
27+
end
28+
29+
-- The fake clock: unix seconds the module's os.time() returns.
30+
local NOW = 1_763_200_000
31+
local fakeOs = setmetatable({
32+
time = function()
33+
return NOW
34+
end,
35+
}, { __index = os })
36+
37+
local services = {
38+
HttpService = {
39+
JSONEncode = function(_, value)
40+
return serde.encode("json", value)
41+
end,
42+
},
43+
}
44+
local function signal()
45+
local handlers = {}
46+
return {
47+
Connect = function(_, fn)
48+
table.insert(handlers, fn)
49+
return { Disconnect = function() end }
50+
end,
51+
Fire = function(_, ...)
52+
for _, fn in table.clone(handlers) do
53+
task.spawn(fn, ...)
54+
end
55+
end,
56+
}
57+
end
58+
local Instance = {
59+
new = function()
60+
local event = signal()
61+
return { Event = event, Fire = function(_, ...) event:Fire(...) end, Destroy = function() end }
62+
end,
63+
}
64+
local warnings = {}
65+
local env
66+
local modules = {}
67+
local PATHS = { relay = "out/runtime/relay.luau", settings = "out/settings.luau" }
68+
local function loadModule(name)
69+
if modules[name] then
70+
return modules[name]
71+
end
72+
modules[name] = luau.load(fs.readFile(root .. PATHS[name]), { debugName = name, environment = env })()
73+
return modules[name]
74+
end
75+
local script = { Parent = { Parent = {} } }
76+
local TS = {
77+
getModule = function()
78+
return "services"
79+
end,
80+
import = function(_, from, ...)
81+
if from == "services" then
82+
return services
83+
end
84+
local parts = { ... }
85+
return loadModule(parts[#parts])
86+
end,
87+
}
88+
env = setmetatable({
89+
script = script,
90+
_G = { [script] = TS },
91+
Instance = Instance,
92+
task = task,
93+
os = fakeOs,
94+
warn = function(...)
95+
table.insert(warnings, table.concat({ ... }, " "))
96+
end,
97+
}, { __index = _G })
98+
99+
local S = loadModule("settings")
100+
101+
local function trove()
102+
return {
103+
add = function(_, value)
104+
return value
105+
end,
106+
connect = function(_, event, fn)
107+
return event:Connect(fn)
108+
end,
109+
}
110+
end
111+
112+
local START = NOW + 2
113+
local END_ = NOW + 4
114+
local function schedule(events)
115+
return { v = 1, events = events }
116+
end
117+
local doubleCash = { id = "ev_cash", name = "Double cash", start = START, ["end"] = END_, set = { ["cash.multiplier"] = 2, banner = "double" } }
118+
119+
local handler
120+
local copy = { seq = 1, at = "a", game = { ["cash.multiplier"] = 1, ["tt.events"] = schedule({ doubleCash }) } }
121+
local kernel = {
122+
kernelVersion = "0.5.3",
123+
settings = function()
124+
return copy
125+
end,
126+
onSettingsChanged = function(_, fn)
127+
handler = fn
128+
end,
129+
}
130+
131+
-- Before the window.
132+
S.bindSettings("server", kernel, trove(), "0.5.3")
133+
local mult = S.liveConfig("cash.multiplier", { default = 1 })
134+
local banner = S.liveConfig("banner", { default = "none" })
135+
local events = S.liveEvents()
136+
check("before: the record's value", mult:get() == 1)
137+
check("before: an unset key's default", banner:get() == "none")
138+
check("before: nothing active", #events:active() == 0)
139+
local upcoming = events:upcoming()
140+
check("before: one upcoming, its fields", #upcoming == 1 and upcoming[1].id == "ev_cash" and upcoming[1].name == "Double cash" and upcoming[1].startsAt == START and upcoming[1].endsAt == END_, #upcoming)
141+
142+
local changes = {}
143+
mult:onChanged(function(value, previous)
144+
table.insert(changes, { value, previous })
145+
end)
146+
local activeChanges = {}
147+
events:onChanged(function(active)
148+
table.insert(activeChanges, #active)
149+
end)
150+
151+
-- The start time passes with no new settings copy: the timer switches it on.
152+
NOW = START
153+
task.wait(2.3)
154+
check("start: switched on by the clock alone", mult:get() == 2 and banner:get() == "double")
155+
check("start: onChanged fired once with (2, 1)", #changes == 1 and changes[1][1] == 2 and changes[1][2] == 1, #changes)
156+
check("start: liveEvents.onChanged fired with one active", #activeChanges == 1 and activeChanges[1] == 1, #activeChanges)
157+
check("start: active() lists it, upcoming() is empty", #events:active() == 1 and #events:upcoming() == 0)
158+
159+
-- A settings copy that doesn't touch the key: no extra change.
160+
copy = { seq = 2, at = "b", game = { ["cash.multiplier"] = 1, other = true, ["tt.events"] = schedule({ doubleCash }) } }
161+
handler(copy)
162+
task.wait(0.05)
163+
check("during: an unrelated copy fires nothing", #changes == 1 and #activeChanges == 1)
164+
165+
-- The end time passes (the backend is down: no copy, no message): the timer switches it off.
166+
NOW = END_
167+
task.wait(2.3)
168+
check("end: switched off by the clock alone", mult:get() == 1 and banner:get() == "none")
169+
check("end: onChanged fired with (1, 2)", #changes == 2 and changes[2][1] == 1 and changes[2][2] == 2, #changes)
170+
check("end: liveEvents.onChanged fired with none active", #activeChanges == 2 and activeChanges[2] == 0, #activeChanges)
171+
S.unbindSettings()
172+
173+
-- A server that starts mid-event picks it up at boot.
174+
NOW = START + 1
175+
copy = { seq = 3, at = "c", game = { ["cash.multiplier"] = 1, ["tt.events"] = schedule({ doubleCash }) } }
176+
S.bindSettings("server", kernel, trove(), "0.5.3")
177+
check("mid-event boot: the event's value at once", mult:get() == 2 and #events:active() == 1)
178+
179+
-- Cancelled: the owner signs a schedule without it; servers drop it with that copy.
180+
local cancelled = {}
181+
mult:onChanged(function(value)
182+
table.insert(cancelled, value)
183+
end)
184+
copy = { seq = 4, at = "d", game = { ["cash.multiplier"] = 1, ["tt.events"] = schedule({}) } }
185+
handler(copy)
186+
task.wait(0.05)
187+
check("cancel: a copy without the event ends it at once", mult:get() == 1 and #cancelled == 1 and cancelled[1] == 1)
188+
189+
-- Two events on one key: the later start wins; an event with only other keys leaves it alone.
190+
local early = { id = "ev_a", name = "Early", start = NOW - 10, ["end"] = NOW + 100, set = { ["cash.multiplier"] = 3 } }
191+
local late = { id = "ev_b", name = "Late", start = NOW - 5, ["end"] = NOW + 100, set = { ["cash.multiplier"] = 2.5 } }
192+
local other = { id = "ev_c", name = "Other", start = NOW - 20, ["end"] = NOW + 100, set = { banner = "x" } }
193+
copy = { seq = 5, at = "e", game = { ["cash.multiplier"] = 1, ["tt.events"] = schedule({ late, other, early }) } }
194+
handler(copy)
195+
task.wait(0.05)
196+
check("overlap: the later start wins", mult:get() == 2.5, mult:get())
197+
local active = events:active()
198+
check("overlap: active() in start order", #active == 3 and active[1].id == "ev_c" and active[2].id == "ev_a" and active[3].id == "ev_b")
199+
200+
-- Bad entries are skipped, never an error; a wrong version is ignored whole.
201+
copy = {
202+
seq = 6,
203+
at = "f",
204+
game = {
205+
["cash.multiplier"] = 1,
206+
["tt.events"] = schedule({
207+
{ id = "ev_noend", start = NOW - 1, set = { ["cash.multiplier"] = 9 } },
208+
{ id = "ev_back", start = NOW + 5, ["end"] = NOW - 5, set = { ["cash.multiplier"] = 9 } },
209+
{ id = 7, start = NOW - 1, ["end"] = NOW + 5, set = { ["cash.multiplier"] = 9 } },
210+
"junk",
211+
{ id = "ev_ok", start = NOW - 1, ["end"] = NOW + 5, set = { ["cash.multiplier"] = 4 } },
212+
}),
213+
},
214+
}
215+
handler(copy)
216+
task.wait(0.05)
217+
check("bad entries: skipped, the good one applies", mult:get() == 4 and #events:active() == 1 and events:active()[1].name == "ev_ok")
218+
copy = { seq = 7, at = "g", game = { ["cash.multiplier"] = 1, ["tt.events"] = { v = 2, events = { doubleCash } } } }
219+
handler(copy)
220+
task.wait(0.05)
221+
check("unknown schedule version: ignored", mult:get() == 1 and #events:active() == 0 and #events:upcoming() == 0)
222+
copy = { seq = 8, at = "h", game = { ["cash.multiplier"] = 1, ["tt.events"] = "nope" } }
223+
handler(copy)
224+
task.wait(0.05)
225+
check("a schedule that isn't a table: ignored", mult:get() == 1)
226+
227+
-- parse still applies to an event's value (a refused value gives the default).
228+
copy = { seq = 9, at = "i", game = { ["tt.events"] = schedule({ { id = "ev_bad", start = NOW - 1, ["end"] = NOW + 5, set = { ["cash.multiplier"] = "lots" } } }) } }
229+
handler(copy)
230+
task.wait(0.05)
231+
local parsed = S.liveConfig("cash.multiplier", {
232+
default = 1,
233+
parse = function(raw)
234+
assert(type(raw) == "number" and raw >= 1 and raw <= 3, "1 to 3")
235+
return raw
236+
end,
237+
})
238+
check("parse: refuses an event's out-of-bounds value -> default", parsed:get() == 1)
239+
240+
-- The generation stops: the timer stops too (no listener runs after unbind).
241+
local stoppedChanges = 0
242+
copy = { seq = 10, at = "j", game = { ["tt.events"] = schedule({ { id = "ev_soon", start = NOW + 1, ["end"] = NOW + 50, set = { banner = "soon" } } }) } }
243+
handler(copy)
244+
task.wait(0.05)
245+
banner:onChanged(function()
246+
stoppedChanges += 1
247+
end)
248+
S.unbindSettings()
249+
NOW += 1
250+
task.wait(1.3)
251+
check("generation stopped: the timer fired nothing", stoppedChanges == 0)
252+
253+
-- Client: server only.
254+
S.bindSettings("client", kernel, trove(), "0.5.3")
255+
local ok, err = pcall(function()
256+
return events:active()
257+
end)
258+
check("client: server-only", not ok and has(err, "server-only"), err)
259+
S.unbindSettings()
260+
261+
print(`live events: {passed} passed, {failed} failed`)
262+
process.exit(if failed == 0 then 0 else 1)

‎src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export { TypeTorch } from "./typetorch";
3030
export type { BranchChange, TypeTorchApi, TypeTorchFeatures } from "./typetorch";
3131
export type { MessageSource, MessagingApi, MessagingSubscribeOptions } from "./messaging";
3232
export type { GameServer, ServerListOptions } from "./servers";
33-
export type { LiveConfig, LiveConfigOptions } from "./settings";
33+
export type { LiveConfig, LiveConfigOptions, LiveEvent, LiveEvents } from "./settings";
3434
export type { Notifications, NotifyOpen, OptInResult, WantOptions } from "./notifications/api";
3535
export type {
3636
Feedback,

0 commit comments

Comments
 (0)