AtomoEdits boolean)?, -- Told after an edit was applied, before it is saved: put right anything that keeps a copy of the data. changed: ((store: string, key: string, edit: any) -> ())?, } -- What this server holds of one player, and how it is saved. type Hold = { kind: string, -- profile, held or direct store: string, key: string, profile: any, data: any, save: any, dataStore: any, waiting: { [string]: any }, -- edits applied, waiting for a save that holds them saving: { [string]: boolean }, -- Save now, waiting for the next save busy: boolean, links: { any }, gone: boolean, } local AtomoEdits = {} local core: any = nil local off = false -- not here: a client, an Actor, or Studio local wrong = false local early = 0 local said: { [string]: boolean } = {} local quiet = false local running = 0 local loops = 0 local wakes = 0 local holding: { [string]: Hold } = {} local allow: any = nil local changed: any = nil local function say(what: string, text: string) if not quiet and not said[what] then said[what] = true pcall(warn, `AtomoEdits: {text}`) end end -- Runs it in a thread of its own, so that nothing it is given can make it error or yield into the game's code. local function apart(fn: () -> any): (boolean, any) local out: any = nil local ended = false local thread = coroutine.create(function() out = fn() ended = true end) local ok = coroutine.resume(thread) if coroutine.status(thread) ~= "dead" then pcall(task.cancel, thread) return false, nil end return ok and ended, out end local function send(url: string, authorization: any) return function(body: string, timeout: number): (number, string, number?) local ok, res: any = pcall(function() return HttpService:RequestAsync({ Url = url, Method = "POST", Headers = { ["Content-Type"] = "application/json", Authorization = authorization }, Body = body, Timeout = timeout, } :: any) end) if not ok then -- Only ever looked at, never printed: it can quote the key. if type(res) == "string" and string.find(res, "requests are not enabled", 1, true) then return -1, "", nil elseif type(res) == "string" and string.find(res, "exceeded limit", 1, true) then return -2, "", nil end return 0, "", nil end local asked = nil pcall(function() for name, value in res.Headers do if string.lower(name) == "retry-after" then asked = tonumber(value) end end end) return if res.StatusCode > 0 then res.StatusCode else 0, res.Body, asked end end -- Nothing here trusts what it is given: whatever is wrong with it, the answer is what to say about it. local function settings(given: any): any local ok, out = apart(function(): any local url, key, scope = given.url, given.key, given.scope if type(url) ~= "string" or #url > 200 then return "start needs an https address" end url = string.gsub(url, "/+$", "") if not (string.match(url, "^https://[%w%-%.]+$") or string.match(url, "^https://[%w%-%.]+:%d+$") or string.match(url, "^http://localhost:%d+$") or string.match(url, "^http://127%.0%.0%.1:%d+$")) then return "start needs an https address" end local authorization: any if typeof(key) == "Secret" then authorization = key:AddPrefix("Bearer ") elseif type(key) == "string" and #key <= 200 and string.match(key, "^[\33-\126]+$") then authorization = `Bearer {key}` else return "start needs the edit key" end local s = if scope == nil then "global" else scope if type(s) ~= "string" or s == "" or #s > 50 then return "a data store's scope isn't one" end local a, c = given.allow, given.changed if (a ~= nil and type(a) ~= "function") or (c ~= nil and type(c) ~= "function") then return "allow and changed are functions" end return { url = url, authorization = authorization, scope = s, allow = a, changed = c } end) return if ok then out else nil end local function loop(me: number) while running == me do local ok, wait = pcall(core.step, core) if ok and wait == nil then running = 0 break end local seconds = if ok then wait else 60 wakes = os.clock() + seconds task.wait(seconds) end end -- The loop runs only while a player is held or an answer waits. One that should have woken a while ago was ended with -- whatever began it. local function wake(after: number) if core and core:waiting() and (running == 0 or os.clock() - wakes > 30) then loops += 1 running, wakes = loops, os.clock() + after if not pcall(task.delay, after, loop, loops) then running = 0 end end end local function answer(id: string, outcome: string, more: any?) pcall(core.answer, core, id, outcome, more) wake(0) end -- What the game's functions are shown: a copy, so that nothing they do changes what is applied or recorded. local function view(edit: any): any return { id = edit.id, kind = edit.kind, changes = Core.copy(edit.changes) } end local function versionOf(info: any): string? local ok, v = pcall(function() if type(info) == "string" then return info end return info.Version end) return if ok and type(v) == "string" then v else nil end -- A save of the game's has happened, with this data in it: what it holds is applied. local function savedWith(h: Hold, data: any, version: string?) local marks = Core.marks(data) for id, edit in h.waiting do if table.find(marks, id) then h.waiting[id] = nil answer(id, "applied", { version = version }) end end for id in h.saving do h.saving[id] = nil answer(id, "saved", { version = version }) end end -- The game's own save function, in this thread. True once it says it has saved, and the version if it gives one. local function gameSave(h: Hold): (boolean, string?) local ok, done, info = pcall(h.save) return ok and done == true, if ok then versionOf(info) else nil end -- Whether this minute's writes have more left than the game's share: what an edit writes, or a save it asks for, comes -- after the game's own. local function room(): boolean local fine, budget = pcall(function() return game:GetService("DataStoreService"):GetRequestBudgetForRequestType(Enum.DataStoreRequestType.UpdateAsync) end) return fine and type(budget) == "number" and budget > BUDGET end local function release(h: Hold) if h.gone then return end h.gone = true local at = Core.slot(h.store, h.key) if holding[at] == h then holding[at] = nil pcall(core.release, core, h.store, h.key) end for _, link in h.links do pcall(function() link:Disconnect() end) end -- What wasn't saved here is decided by the next load: its mark is there, or it is applied there. Should it come back -- here, it is dealt with afresh. for id in h.waiting do core.working[id] = nil end table.clear(h.waiting) for id in h.saving do answer(id, "let_go") -- nothing to save here any more end table.clear(h.saving) end -- Whether a table this server holds stays under what Roblox keeps once the edit is in it: its size now, and every new -- value as if nothing were taken away. Measured as the game's own save would be; a table that can't be measured that -- way is saved some other way, and is the game's to know. local function fits(data: any, edit: any): boolean local fine, size = pcall(function() local n = #HttpService:JSONEncode(data) + 400 -- and the marks for _, c in edit.changes do n += #HttpService:JSONEncode({ c.after }) end return n end) return not fine or size <= MAX_SAVE end -- Whether the player is in this server, where Atomo named them. A hold the game never released, after the player has -- left, would save what this server still has over what they have saved since elsewhere: it is let go instead, and the -- edit is the next server's. Not known (no player named), it is. local function here(edit: any): boolean if edit.user == nil then return true end local fine, player = pcall(function() return game:GetService("Players"):GetPlayerByUserId(edit.user) end) return fine and player ~= nil end -- After a held table's edit is applied: its save, tried a few times while it is still held here. local function saveHeld(h: Hold, id: string) for try = 1, SAVE_TRIES do if h.gone or not h.waiting[id] then return elseif not here(h.waiting[id]) then return release(h) -- left before it was saved: the next load decides end local ok, version = false, nil if room() then ok, version = gameSave(h) end if ok and h.waiting[id] then h.waiting[id] = nil answer(id, "applied", { version = version }) return elseif try < SAVE_TRIES then task.wait(SAVE_AGAIN) end end end -- One edit, from the moment Atomo gives it. In a thread of its own; the change itself is one step. local function process(edit: any) local h = holding[Core.slot(edit.store, edit.key)] if not h or h.gone or core.closing or h.busy then return answer(edit.id, "let_go") elseif not here(edit) then release(h) -- left, and never released: held here no more return answer(edit.id, "let_go") end h.busy = true local ok = pcall(function() if edit.kind ~= "save" and allow then local fine, yes = apart(function() return allow(h.store, h.key, view(edit)) end) if not fine or yes ~= true then if not fine then say("allow", "allow errored or yielded, so an edit was refused.") end return answer(edit.id, "refused", { why = "denied" }) end end if h.kind == "direct" then if edit.kind == "save" then return answer(edit.id, "saved") -- what is stored is all there is end if not room() then return answer(edit.id, "let_go") -- the game needs its writes more end local outcome, detail = nil, nil local wrote, _, info = pcall(function() return h.dataStore:UpdateAsync(h.key, function(value: any, keyInfo: any) local data = value for _, part in edit.base do data = if type(data) == "table" and getmetatable(data) == nil then rawget(data, part) else nil end outcome, detail = Core.apply(data, edit) if outcome ~= "applied" then return nil -- nothing is written end local users, meta = nil, nil pcall(function() users, meta = keyInfo:GetUserIds(), keyInfo:GetMetadata() end) return value, users, meta end) end) if not wrote or not outcome then return answer(edit.id, "let_go") elseif outcome == "applied" then return answer(edit.id, "applied", { version = versionOf(info) }) end return answer(edit.id, outcome, if outcome == "conflict" then { now = detail } elseif outcome == "refused" then { why = detail } else nil) end -- A table this server holds: changed in one step, then saved by the game's own save. if h.kind == "profile" then local _, active = pcall(function() return h.profile:IsActive() end) if active ~= true then release(h) -- its session has ended: not this server's any more return answer(edit.id, "let_go") elseif #edit.base ~= 1 or edit.base[1] ~= "Data" then return answer(edit.id, "refused", { why = "bad_path" }) -- ProfileStore: Data only end end -- A table this server holds is saved once it is changed, by the game's save or ProfileStore's: only when there is room. if not room() then return answer(edit.id, "let_go") -- the game needs its writes more end if edit.kind == "save" then if h.kind == "profile" then h.saving[edit.id] = true pcall(h.profile.Save, h.profile) return end local saved, version = gameSave(h) return answer(edit.id, if saved then "saved" else "let_go", { version = version }) end local data = if h.kind == "profile" then h.profile.Data else h.data if not fits(data, edit) then return answer(edit.id, "refused", { why = "too_large" }) -- its save would fail, and every one after it end local outcome, detail = Core.apply(data, edit) if outcome == "conflict" then return answer(edit.id, outcome, { now = detail }) elseif outcome == "refused" then return answer(edit.id, outcome, { why = detail }) elseif outcome ~= "applied" then return answer(edit.id, outcome) end h.waiting[edit.id] = edit if changed then -- The game's: its errors are its own, and it may yield. pcall(task.spawn, changed, h.store, h.key, view(edit)) end if h.kind == "profile" then pcall(h.profile.Save, h.profile) else saveHeld(h, edit.id) end end) h.busy = false if not ok then answer(edit.id, "let_go") end end --- Once, on the server. Anything wrong is said once, and then nothing is done. function AtomoEdits.start(options: Options) if off then return elseif core then say("twice", "start was already called.") return end quiet = select(2, apart(function() return options.quiet == true end)) == true if not there then off = true say("where", "a part of it is missing. No edit is applied.") return end local _, client = apart(function() return not RunService:IsServer() end) local _, actor = apart(function() return (script :: any):GetActor() ~= nil end) if client ~= false or actor then off = true say("where", if actor then "it does nothing inside an Actor." else "it only works on the server.") return end local _, studio = apart(function() return RunService:IsStudio() end) local _, asked = apart(function() return options.studio == true end) if studio ~= false and not asked then off = true return end local s = settings(options) if type(s) ~= "table" then wrong = true say("settings", if type(s) == "string" then `{s}. No edit is applied.` else "start's settings can't be read. No edit is applied.") return end local _, server = apart(function() return string.lower((string.gsub(HttpService:GenerateGUID(false), "[^%w]", ""))) end) local fine, c = pcall(function() return Core.new({ now = os.clock, random = math.random, encode = function(value) return HttpService:JSONEncode(value) end, decode = function(text) return HttpService:JSONDecode(text) end, send = send(`{s.url}/v1/edits`, s.authorization), warn = warn, wait = function(seconds) task.wait(seconds) end, spawn = task.spawn, handle = function(edit) task.spawn(process, edit) end, }, { scope = s.scope, quiet = quiet, server = if type(server) == "string" and #server >= 8 then string.sub(server, 1, 64) else tostring(math.random(1e8, 9e8)) }) end) if not fine then wrong = true say("settings", "start's settings can't be read. No edit is applied.") return end core, allow, changed = c, s.allow, s.changed pcall(function() game:BindToClose(function() core.closing = true -- What was applied waits for its save: ProfileStore saves every profile as the server closes. local ends = os.clock() + CLOSE_LIMIT local function waiting(): boolean if next(core.working) then return true end for _, h in holding do if next(h.waiting) or next(h.saving) then return true end end return false end while waiting() and os.clock() < ends - 1 do task.wait(0.1) end pcall(core.close, core, math.max(0, ends - os.clock())) end) end) end local function ready(store: any, key: any): boolean if not core then if not off then early += 1 if not wrong then say("early", "a player was held before start.") end end return false end return type(store) == "string" and store ~= "" and #store <= 50 and type(key) == "string" and key ~= "" and #key <= 200 end local function hold(h: Hold, marks: { string }) local at = Core.slot(h.store, h.key) local was = holding[at] if was then release(was) end holding[at] = h core:hold(h.store, h.key, marks) wake(GATHER) end local function newHold(kind: string, store: string, key: string): Hold return { kind = kind, store = store, key = key, profile = nil, data = nil, save = nil, dataStore = nil, waiting = {}, saving = {}, busy = false, links = {}, gone = false } end --- ProfileStore: once a session has started. Held until it ends; saved, and told, through its own save. Only `Data` is --- edited. Never yields and never errors. function AtomoEdits.profile(store: string, profile: any) pcall(function() local key = profile.Key if not ready(store, key) or type(profile.Data) ~= "table" then return end local h = newHold("profile", store, key) h.profile = profile pcall(function() local link: any = profile.OnAfterSave:Connect(function(saved: any) savedWith(h, saved, versionOf(profile.KeyInfo)) end) table.insert(h.links, link) end) pcall(function() local link: any = profile.OnSessionEnd:Connect(function() -- The save that ends a session comes after; a little time for it to be heard. task.delay(30, release, h) end) table.insert(h.links, link) end) hold(h, Core.marks(profile.Data)) end) end --- A table this server holds and saves itself: the player's data, at the data path set in Atomo. `save` saves it now, --- and returns true once it is stored (and the DataStoreKeyInfo, if it has it). Never yields and never errors. function AtomoEdits.held(store: string, key: string, data: any, save: () -> (boolean, any?)) pcall(function() if not ready(store, key) or type(data) ~= "table" or type(save) ~= "function" then return end local h = newHold("held", store, key) h.data, h.save = data, save hold(h, Core.marks(data)) end) end --- A plain data store the game writes straight, holding nothing between saves: the module writes an edit itself, with --- UpdateAsync, while the player is in this server. Never yields and never errors. function AtomoEdits.direct(store: string, key: string, dataStore: any) pcall(function() if not ready(store, key) or dataStore == nil then return end local h = newHold("direct", store, key) h.dataStore = dataStore hold(h, {}) end) end --- The player has left this server, after its last save. Not needed for a profile. Never yields and never errors. function AtomoEdits.released(store: string, key: string) pcall(function() if core and type(store) == "string" and type(key) == "string" then local h = holding[Core.slot(store, key)] if h then release(h) end end end) end --- Optional, for a held table: after each save of the game's, with what was saved, as for Atomo's report. What it --- holds is told as applied. Never yields and never errors. function AtomoEdits.saved(store: string, key: string, data: any, info: any) pcall(function() if core and type(store) == "string" and type(key) == "string" then local h = holding[Core.slot(store, key)] if h and h.kind == "held" then savedWith(h, data, versionOf(info)) end end end) end return AtomoEdits ]]> Core number, -- seconds, only ever forward random: () -> number, -- 0 to 1 encode: (value: any) -> string, -- may error decode: (text: string) -> any, -- may error -- The status; 0 for no answer, -1 if requests are off here, -2 if the game has used up its own. The body. How long it -- asked us to wait. Yields. send: (body: string, timeout: number) -> (number, string, number?), warn: (text: string) -> (), wait: (seconds: number) -> (), spawn: (fn: () -> ()) -> any, -- in a thread of its own, at once -- Each new edit Atomo gives, once. Must not yield. handle: (edit: Edit) -> (), } export type Options = { scope: string, quiet: boolean, server: string } export type Change = { path: { any }, before: any, after: any } export type Edit = { id: string, store: string, scope: string, key: string, kind: string, base: { string }, changes: { Change }, user: number? } type Held = { store: string, key: string, marks: { string }? } type Found = { path: { any }, value: any, cut: boolean? } type Answer = { id: string, outcome: string, version: string?, why: string?, now: { Found }? } local MARK = "AtomoEdits" -- at the top of the player's data: the edits applied to it local MARKS_KEPT = 20 local MAX_ANSWER = 300 * 1024 -- bytes of an answer that are read at all local MAX_EDITS = 20 -- in one answer local MAX_CHANGES = 50 local MAX_PATH = 32 local MAX_BASE = 8 local MAX_NAME = 50 -- a data store's name or scope local MAX_KEY = 200 local MAX_PART = 200 -- one part of a path local MAX_PLACE = 10000000 -- a place in a list local MAX_HELD = 500 -- keys in one request; more wait for the next local MAX_DONE = 100 -- answers in one request local MAX_FOUND = 8 * 1024 -- bytes of values found, in all the answers of one request local MAX_ONE_FOUND = 2 * 1024 -- of one value found local DEEP = 64 local HOLD = 20 -- seconds Atomo may keep a request while it has nothing local TIMEOUT = 30 -- of a request: the hold, and time to answer local CLOSE_TIMEOUT = 4 local PER_MINUTE = 6 -- requests: 1.2% of the game's 500 local MINUTE = 61 local GAP = 2 -- seconds between requests, at least local SHORT = 5 -- an answer this quick with nothing in it wasn't held: the next waits longer local AFTER_SHORT = 10 local FIRST_WAIT = 5 local LONGEST_WAIT = 300 local AWAY = 1800 -- failing for this long: one try in RARELY local RARELY = 600 local WRONG_WAIT = 60 local STUCK = 60 -- a request still going by then never will end local REMEMBERED = 500 -- answers Atomo has taken, so that a late copy of an edit isn't applied as new local KINDS = { update = true, restore = true, save = true } local WHY = { denied = true, not_a_table = true, not_plain = true, bad_path = true, mark_taken = true, bad_edit = true, too_large = true } local Core = {} Core.__index = Core Core.MARK = MARK type Self = { deps: Deps, options: Options, held: { [string]: Held }, heldCount: number, working: { [string]: string }, -- edits being applied, or waiting for their save: whose answers: { [string]: Answer }, -- not yet taken by Atomo answerCount: number, taken: { [string]: Answer }, -- answers Atomo has taken, by edit: what they were, without what was found takenOrder: { string }, sending: boolean, sendingAt: number, asking: number, -- which request is out sent: { number }, -- when the last requests were made notBefore: number, failures: number, failingSince: number, wrongs: number, busy: number, closing: boolean, over: boolean, -- Atomo said to stop warnedAt: { [string]: number }, } export type Core = typeof(setmetatable({} :: Self, Core)) function Core.new(deps: Deps, options: Options): Core local self: Self = { deps = deps, options = options, held = {}, heldCount = 0, working = {}, answers = {}, answerCount = 0, taken = {}, takenOrder = {}, sending = false, sendingAt = 0, asking = 0, sent = {}, notBefore = -math.huge, failures = 0, failingSince = 0, wrongs = 0, busy = 0, closing = false, over = false, warnedAt = {}, } return setmetatable(self, Core) end --- Once in 10 minutes for each kind, or `once` for as long as the server runs. function Core.say(self: Core, what: string, text: string, once: boolean?) local now = self.deps.now() local last = self.warnedAt[what] if self.options.quiet or (last and (once or now - last < RARELY)) then return end self.warnedAt[what] = now pcall(self.deps.warn, `AtomoEdits: {text}`) end -- Plain data ------------------------------------------------------------------------------------------------------------ local function plain(t: any): boolean return type(t) == "table" and getmetatable(t) == nil end -- A table a change can be written into: plain, and not frozen. local function writable(t: any): boolean return plain(t) and not table.isfrozen(t) end --- Whether two values are the same data. Tables are compared by what is in them; a table with a metatable is no data. local function same(a: any, b: any, depth: number?): boolean local d = depth or 0 if type(a) ~= type(b) then return false elseif type(a) ~= "table" then return a == b -- NaN is never the same as anything elseif d > DEEP or not plain(a) or not plain(b) then return false end for k, v in next, a do local w = rawget(b, k) if w == nil or not same(v, w, d + 1) then return false end end for k in next, b do if rawget(a, k) == nil then return false end end return true end Core.same = same local function copy(v: any, depth: number?): any if type(v) ~= "table" then return v end local d = depth or 0 if d > DEEP then return nil end local out = {} for k, x in next, v do out[k] = copy(x, d + 1) end return out end Core.copy = copy local function isId(v: any): boolean return type(v) == "string" and #v == 16 and string.match(v, "^[0-9a-f]+$") ~= nil end --- The marks in a player's data, if they are marks. local function marksIn(data: any): ({ string }?, boolean) if not plain(data) then return nil, false end local marks = rawget(data, MARK) if marks == nil then return {}, true elseif not plain(marks) then return nil, false end local n = 0 for k, v in next, marks do n += 1 if type(k) ~= "number" or not isId(v) then return nil, false end end if n ~= #marks or n > 100 then return nil, false end return marks, true end --- The ids of the edits a player's data says were applied to it. Never more than MARKS_KEPT. function Core.marks(data: any): { string } local marks = marksIn(data) local out = {} if marks then for i = math.max(1, #marks - MARKS_KEPT + 1), #marks do table.insert(out, marks[i]) end end return out end -- What a table is, for Roblox: a list (places from 1, no gaps), fields (text keys), or empty, which can become either. -- A table that is both is saved without its fields, so no change may make one. type Shape = { list: boolean?, n: number, set: { [number]: boolean }, cut: { [number]: boolean } } local function shapeOf(t: any): Shape local n = #t return { list = if n > 0 then true elseif next(t) == nil then nil else false, n = n, set = {}, cut = {} } end -- Whether every list the edit changes is still a list with no gap: places taken away only at its end, and added only -- after it, one after another. Each is looked at in no more steps than the edit has changes. local function noGaps(s: Shape): boolean if not s.list then return true end local lowest = math.huge for i in s.cut do lowest = math.min(lowest, i) end for i = lowest, s.n do if not s.cut[i] then return false end end local top = s.n for i in s.set do if i >= lowest then return false -- set after a place taken away end top = math.max(top, i) end for i = s.n + 1, top do if not s.set[i] then return false end end return true end type Step = { parent: any, last: any, after: any, was: any, held: { [any]: any }? } -- One change written. A table that is there already, and not frozen, is changed in place rather than replaced, so that -- whatever in the game holds it (`local bag = Data.Bag`) still holds the player's data, and its changes are saved. What -- it held is kept, to be put back. local function put(p: Step) local after = copy(p.after) if type(p.was) == "table" and type(after) == "table" and not table.isfrozen(p.was) then p.held = table.clone(p.was) table.clear(p.was) for k, v in next, after do rawset(p.was, k, v) end else rawset(p.parent, p.last, after) end end -- A change written, taken back. local function undo(p: Step) local held = p.held if held then table.clear(p.was) for k, v in next, held do rawset(p.was, k, v) end else rawset(p.parent, p.last, p.was) end end --- Applies an edit to a player's data, in one step: all of it with its mark, or none of it. --- `applied`; `found` if its mark is there already; `conflict` and the values found; `refused` and why. function Core.apply(data: any, edit: Edit): (string, any) if not writable(data) then return "refused", if type(data) == "table" then "not_plain" else "not_a_table" elseif #data > 0 then return "refused", "not_a_table" -- a list: it has no fields, and no place for the marks end local marks, fine = marksIn(data) if not fine or not marks then return "refused", "mark_taken" elseif table.find(marks, edit.id) then return "found", nil end -- Everything is looked at before anything is written. local plan: { Step } = {} local found: { { path: { any }, value: any } } = {} local shapes: { [any]: Shape } = { [data] = { list = false, n = 0, set = {}, cut = {} } } for _, c in edit.changes do local parent: any = data for i = 1, #c.path - 1 do if parent == nil then break elseif not plain(parent) then return "refused", if type(parent) == "table" then "not_plain" else "bad_path" end parent = rawget(parent, c.path[i]) end local last = c.path[#c.path] if parent ~= nil and not plain(parent) then return "refused", if type(parent) == "table" then "not_plain" else "bad_path" end local current = if parent == nil then nil else rawget(parent, last) if type(current) == "table" and not plain(current) then return "refused", "not_plain" elseif not same(current, c.before) then table.insert(found, { path = c.path, value = current }) elseif parent == nil then return "refused", "bad_path" -- what holds it isn't there elseif not writable(parent) then return "refused", "not_plain" else local s = shapes[parent] or shapeOf(parent) shapes[parent] = s local place = type(last) == "number" if s.list == nil then s.list = place elseif s.list ~= place then return "refused", "bad_path" -- a place in fields, or a field in a list end if place then if c.after == nil then s.cut[last] = true else s.set[last] = true end end table.insert(plan, { parent = parent, last = last, after = c.after, was = current }) end end if #found > 0 then return "conflict", found end for _, s in shapes do if not noGaps(s) then return "refused", "bad_path" -- Roblox would save only what is before a gap end end for i, p in plan do if not pcall(put, p) then for j = i - 1, 1, -1 do undo(plan[j]) -- none of it, then end return "refused", "not_plain" end end local kept = {} for i = math.max(1, #marks - MARKS_KEPT + 2), #marks do table.insert(kept, marks[i]) end table.insert(kept, edit.id) rawset(data, MARK, kept) return "applied", nil end -- Reading Atomo's answers ------------------------------------------------------------------------------------------------- local function name(v: any, most: number): boolean return type(v) == "string" and v ~= "" and #v <= most end local function readPath(p: any, most: number, base: boolean): { any }? if not plain(p) or #p > most then return nil end local n = 0 for _ in next, p do n += 1 end if n ~= #p then return nil end local out = {} for _, part in ipairs(p) do if type(part) == "string" and #part <= MAX_PART then table.insert(out, part) elseif not base and type(part) == "number" and part >= 1 and part <= MAX_PLACE and part % 1 == 0 then table.insert(out, part) else return nil end end return out end local function prefix(a: { any }, b: { any }): boolean if #a > #b then return false end for i, part in a do if b[i] ~= part then return false end end return true end -- Whether a list in a value has an empty place, as `[1, null, 3]` becomes: Roblox would save only what comes before it. local function gap(v: any, depth: number?): boolean if type(v) ~= "table" then return false end local d = depth or 0 if d > DEEP then return false end local places, top = 0, 0 for k, x in next, v do if type(k) == "number" then places += 1 top = math.max(top, k) end if gap(x, d + 1) then return true end end return places ~= top end --- An edit as Atomo gave it, checked to its last part. Nil, and whether it had an id to answer to. function Core.read(given: any): (Edit?, string?) if not plain(given) then return nil, nil end local id = rawget(given, "id") if not isId(id) then return nil, nil end local store, scope, key, kind = rawget(given, "store"), rawget(given, "scope"), rawget(given, "key"), rawget(given, "kind") local base = readPath(rawget(given, "base"), MAX_BASE, true) local changes: any = rawget(given, "changes") if not (name(store, MAX_NAME) and name(scope, MAX_NAME) and name(key, MAX_KEY) and type(kind) == "string" and KINDS[kind] and base and plain(changes)) then return nil, id end if #changes > MAX_CHANGES or (kind == "save") ~= (#changes == 0) then return nil, id end local out: { Change } = {} for i, c in ipairs(changes) do local path = if plain(c) then readPath(rawget(c, "path"), MAX_PATH, false) else nil if not path or #path == 0 or path[1] == MARK then return nil, id end local before, after = rawget(c, "before"), rawget(c, "after") if (before == nil and after == nil) or gap(after) then return nil, id end for j = 1, i - 1 do if prefix(out[j].path, path) or prefix(path, out[j].path) then return nil, id -- two that overlap can't both say what they expect end end table.insert(out, { path = path, before = copy(before), after = copy(after) }) end local n = 0 for _ in next, changes do n += 1 end if n ~= #changes then return nil, id end -- The player, where Atomo knows them: a whole number, or nothing. local user = rawget(given, "user") if user ~= nil and not (type(user) == "number" and user >= 1 and user <= 2 ^ 53 and user % 1 == 0) then return nil, id end return { id = id, store = store, scope = scope, key = key, kind = kind, base = base :: { string }, changes = out, user = user }, id end -- Which players this server holds --------------------------------------------------------------------------------------- local function slot(store: string, key: string): string return `{store}\0{key}` end Core.slot = slot --- A player's data is held here from now on. `marks`: what its data said was applied, as it was loaded. function Core.hold(self: Core, store: string, key: string, marks: { string }?) local at = slot(store, key) if not self.held[at] then self.heldCount += 1 end self.held[at] = { store = store, key = key, marks = if marks and #marks > 0 then marks else nil } end function Core.release(self: Core, store: string, key: string) local at = slot(store, key) if self.held[at] then self.held[at] = nil self.heldCount -= 1 end end function Core.holds(self: Core, store: string, key: string): boolean return self.held[slot(store, key)] ~= nil end -- Answers --------------------------------------------------------------------------------------------------------------- local DONE = { applied = true, found = true, saved = true } --- What became of an edit. A word that it was applied is never taken back; any other is replaced by the latest. function Core.answer(self: Core, id: string, outcome: string, more: { version: any, why: string?, now: { Found }? }?) self.working[id] = nil local was = self.answers[id] if was and DONE[was.outcome] then return end if not was then self.answerCount += 1 end local m: any = more or {} local now: { Found }? = nil if m.now then -- As they are now: the values are the game's, and change. local list: { Found } = {} for _, f in m.now do local ok, text = pcall(self.deps.encode, f.value) local small = ok and type(text) == "string" and #text <= MAX_ONE_FOUND table.insert(list, { path = f.path, value = if small then copy(f.value) else nil, cut = if small then nil else true }) end now = list end self.answers[id] = { id = id, outcome = outcome, version = if type(m.version) == "string" and #m.version <= 200 then m.version else nil, why = if type(m.why) == "string" and WHY[m.why] then m.why else nil, now = now, } end --- Whether anything is left to do: players held, answers to give, or edits on their way. function Core.waiting(self: Core): boolean return not self.over and (self.heldCount > 0 or self.answerCount > 0) end local function remember(self: Core, id: string, a: Answer) if not self.taken[id] then table.insert(self.takenOrder, id) if #self.takenOrder > REMEMBERED then self.taken[table.remove(self.takenOrder, 1) :: string] = nil end end self.taken[id] = { id = id, outcome = a.outcome, version = a.version, why = a.why } end -- What was found, as much as fits: a value too large to send is left out, and the answer says so. local function foundList(self: Core, now: { Found }, room: number): (any, number) local out: { any } = {} for _, f in now do local ok, text = pcall(self.deps.encode, f.value) if not f.cut and ok and type(text) == "string" and #text <= room then room -= #text table.insert(out, { path = f.path, value = f.value }) else table.insert(out, { path = f.path, cut = true }) end end return out, room end -- The request --------------------------------------------------------------------------------------------------------- local function bodyOf(self: Core): (string?, { [string]: Answer }, { Held }) local held = {} local marked: { Held } = {} local n = 0 for _, h in self.held do n += 1 if n > MAX_HELD then break end local one: any = { store = h.store, scope = self.options.scope, key = h.key } if h.marks then one.marks = h.marks table.insert(marked, h) end table.insert(held, one) end local done = {} local ids: { [string]: Answer } = {} local room = MAX_FOUND for id, a in self.answers do if #done >= MAX_DONE then break end local one: any = { id = id, outcome = a.outcome, version = a.version, why = a.why } if a.now then one.now, room = foundList(self, a.now, room) end table.insert(done, one) ids[id] = a end local ok, body = pcall(self.deps.encode, { server = self.options.server, wait = if self.closing then 0 else HOLD, held = held, done = done, }) return if ok and type(body) == "string" then body else nil, ids, marked end -- No request until then. Half of the wait is by chance, so that servers don't all come back at once. local function waitFor(self: Core, seconds: number, atLeast: number) self.notBefore = self.deps.now() + math.max(seconds * (0.5 + self.deps.random() / 2), atLeast) end local function backOff(self: Core, asked: number?) local now = self.deps.now() if self.failures == 0 then self.failingSince = now end self.failures += 1 if now - self.failingSince >= AWAY then self.notBefore = now + RARELY else waitFor(self, math.min(LONGEST_WAIT, FIRST_WAIT * 2 ^ math.min(self.failures - 1, 10)), if asked and asked == asked then math.min(asked, LONGEST_WAIT) else 0) end end -- Whether an edit of this player is being dealt with. As many steps as edits under way. local function busyWith(self: Core, at: string): boolean for _, whose in self.working do if whose == at then return true end end return false end -- Takes in what Atomo gave. Each edit is handed on once; one already being dealt with, or answered, isn't. local function takeIn(self: Core, answer: any) local edits: any = rawget(answer, "edits") if not plain(edits) then return end for i, given in ipairs(edits) do if i > MAX_EDITS then break end local edit, id = Core.read(given) if not id then continue elseif self.working[id] or self.answers[id] then continue -- the same edit twice: it is being dealt with elseif self.taken[id] and self.taken[id].outcome ~= "let_go" then -- Atomo hasn't the answer it took. It is given again, the same. local was = self.taken[id] Core.answer(self, id, was.outcome, { version = was.version, why = was.why }) continue elseif not edit then Core.answer(self, id, "refused", { why = "bad_edit" }) elseif edit.scope ~= self.options.scope or not self.held[slot(edit.store, edit.key)] or self.closing or busyWith(self, slot(edit.store, edit.key)) then -- Also a second edit of a player while one is being dealt with: Atomo gives one at a time, so it waits. Core.answer(self, id, "let_go") else self.working[id] = slot(edit.store, edit.key) local ok = pcall(self.deps.handle, edit) if not ok then Core.answer(self, id, "let_go") end end end end -- Sends one request, and deals with its answer. Yields. True if Atomo answered. local function ask(self: Core, timeout: number): boolean local body, ids, marked = bodyOf(self) if not body then return false end local started = self.deps.now() local ok, status: any, text: any, asked: any = pcall(self.deps.send, body, timeout) if not ok then status, text, asked = 0, "", nil end local answer: any = {} if type(text) == "string" and #text <= MAX_ANSWER then local read, value = pcall(self.deps.decode, text) if read and plain(value) then answer = value end end if status == 200 then self.failures, self.wrongs, self.busy = 0, 0, 0 for id, a in ids do -- Only what was sent: one that took its place meanwhile is sent next time. if self.answers[id] == a then self.answers[id] = nil self.answerCount -= 1 remember(self, id, a) end end for _, h in marked do h.marks = nil -- told end takeIn(self, answer) local edits: any = rawget(answer, "edits") local nothing = not plain(edits) or #edits == 0 local later = rawget(answer, "wait") if type(later) == "number" and later == later and later > 0 then waitFor(self, math.min(later, RARELY), math.min(later, RARELY) / 2) elseif nothing and self.deps.now() - started < SHORT and not self.closing then self.notBefore = self.deps.now() + AFTER_SHORT -- it wasn't held: asking at once would be asking all the time end return true elseif status == 410 then self.over = true return true elseif status == -1 then self.notBefore = self.deps.now() + RARELY self:say("off", "HTTP requests are off in this experience's security settings.", true) elseif status == -2 then self.notBefore = self.deps.now() + math.min(RARELY, WRONG_WAIT * 2 ^ math.min(self.busy, 10)) self.busy += 1 elseif status == 429 then backOff(self, asked) elseif status >= 300 and status < 500 and status ~= 408 then self.notBefore = self.deps.now() + math.min(RARELY, WRONG_WAIT * 2 ^ math.min(self.wrongs, 10)) self.wrongs += 1 self:say("wrong", if status == 401 then "the key isn't right, or was removed." elseif status == 404 then "a data store isn't connected in Atomo." else `the address is wrong, or it can't answer ({math.floor(status)}).`, true) else backOff(self, asked) if self.failures >= 3 then self:say("unreachable", "Atomo can't be reached. Edits wait.") end end return false end -- When the next request may be made: never more than PER_MINUTE in a minute. local function allowedAt(self: Core): number return if #self.sent >= PER_MINUTE then self.sent[1] + MINUTE else -math.huge end -- The one way out: no request is made but here. In a thread of its own: whoever asked may be ended while it waits. local function post(self: Core, timeout: number) local now = self.deps.now() table.insert(self.sent, now) if #self.sent > PER_MINUTE then table.remove(self.sent, 1) end self.asking += 1 local me = self.asking self.sending, self.sendingAt = true, now local ok = pcall(self.deps.spawn, function() pcall(ask, self, timeout) if self.asking == me then self.sending = false end end) if not ok then self.sending = false end end --- One that was ended with its thread, or that never ends. function Core.unstick(self: Core) if self.sending and self.deps.now() - self.sendingAt > STUCK then self.sending = false self.asking += 1 -- whatever it says now isn't heard backOff(self) end end --- Asks if it is time. How many seconds until it should be asked again, or nil if there is nothing to do. function Core.step(self: Core): number? self:unstick() if not self:waiting() then return nil elseif self.sending then return 1 end local at = math.max(self.notBefore, allowedAt(self), if #self.sent > 0 then self.sent[#self.sent] + GAP else -math.huge) local wait = at - self.deps.now() if wait > 0 then return wait end post(self, if self.closing then CLOSE_TIMEOUT else TIMEOUT) return 1 end --- While closing: one request with every answer that is ready, if one can still be made. Yields, `seconds` at most. --- The request Atomo may be holding isn't waited for: the server ends under it. It may be one more than the minute's six: --- the last this server makes. function Core.close(self: Core, seconds: number) self.closing = true local left = math.floor(seconds) if self.answerCount == 0 or self.over or self.failures >= 3 or left < 1 then return end local now: number = self.deps.now() table.insert(self.sent, now) if #self.sent > PER_MINUTE then table.remove(self.sent, 1) end pcall(ask, self, math.min(CLOSE_TIMEOUT, left)) end return Core ]]>