Atomo any): any local out: any = nil local thread = coroutine.create(function() out = fn() end) coroutine.resume(thread) if coroutine.status(thread) ~= "dead" then pcall(task.cancel, thread) return nil end return 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 -- the game's own 500 a minute 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 nil, or what to say about it. local function settings(given: any): any return apart(function(): any local url, key, store, scope, maxSize = given.url, given.key, given.store, given.scope, given.maxSize -- Never a key or a save in the open, except to this machine; and without the slash people copy. 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 reporting key" end for _, name in { if store == nil then "store" else store, if scope == nil then "global" else scope } do if type(name) ~= "string" or name == "" or #name > 50 then return "a data store's name or scope isn't one" end end if maxSize ~= nil and not (type(maxSize) == "number" and maxSize >= 1) then return "maxSize isn't a number of bytes" end local out: Settings = { url = url, authorization = authorization, store = store, options = { scope = if scope == nil then "global" else scope, quiet = quiet, maxSize = math.min(maxSize or SIZE, MAX_SIZE) }, } return out end) end local function loop(q: any, me: number) while running == me do local ok, wait = pcall(q.step, q) 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 something waits. One that should have woken a while ago was ended with whatever began it. local function wake(q: any, after: number) if q.count > 0 and not held and (running == 0 or os.clock() - wakes > 30) then loops += 1 running, wakes = loops, os.clock() + after if not pcall(task.delay, after, loop, q, loops) then running = 0 end end end --- Once, on the server. Anything wrong is said once, and then nothing is reported. function Atomo.start(options: Options) if off then return elseif queue then say("twice", "start was already called.") return end quiet = apart(function() return options.quiet == true end) == true if not there then off = true say("where", "a part of it is missing. Nothing is reported.") 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) ~= false local asked = apart(function() return options.studio == true end) if studio 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}. Nothing is reported.` else "start's settings can't be read. Nothing is reported.") return end local q: any = apart(function() return Queue.new({ now = os.clock, wait = function(seconds) task.wait(seconds) end, -- Once may be later in this same frame. Twice isn't. frame = function(fn) task.delay(0, function() task.delay(0, fn) end) end, random = math.random, encode = function(value) return HttpService:JSONEncode(value) end, decode = function(text) return HttpService:JSONDecode(text) end, spawn = task.spawn, close = task.cancel, send = send(`{s.url}/v1/saves`, s.authorization), warn = warn, }, s.options) end) if not q then wrong = true say("settings", "start's settings can't be read. Nothing is reported.") return end queue, mine = q, s.store if not studio then pcall(function() game:BindToClose(function() q.closing = true held, running = true, 0 -- one that sleeps until long after the server has ended pcall(q.flush, q) held = false wake(q, 0) local left = q:stats().queued if left > 0 then q:say("closed", `the server closed. Not sent: {left}.`) end end) end) end end local function tell(removal: boolean, store: any, key: any, data: any, info: any) local q = queue if not q then if not off then early += 1 if not wrong then say("early", "something was reported before start.") end end return elseif type(info) == "nil" then if removal then -- Without key info, as ProfileStore's RemoveAsync gives: dated by when it was called. q:push(true, store, key, nil, function() return { untold = true } :: any end) wake(q, if q.closing then 0 else GATHER) end return -- a report of a key that isn't there, as a new player's end q:push(removal, store, key, data, function() return { version = info.Version, time = info.UpdatedTime, users = info:GetUserIds() } end) wake(q, if q.closing then 0 else GATHER) end --- After a load or a save has succeeded. `info` is the DataStoreKeyInfo that came with it. Never yields and never errors. function Atomo.report(store: string, key: string, data: any, info: any) tell(false, store, key, data, info) end --- After a key has been removed. `info` is the DataStoreKeyInfo that RemoveAsync gave, or nil where there is none, as with --- ProfileStore: then it is dated by when this was called. Never yields and never errors. function Atomo.removed(store: string, key: string, info: any) tell(true, store, key, nil, info) end --- As `report`, of the store named at `start`. function Atomo.reportSaved(key: string, saved: any, info: any) tell(false, mine, key, saved, info) end -- Not needed: it closes by itself. Sends what is waiting now, and yields. True if nothing is left. function Atomo.flush(seconds: number?): boolean local q = queue if not q then return true end local ok, all = pcall(q.flush, q, if type(seconds) == "number" and seconds == seconds then seconds else nil) return ok and all end -- What became of the saves so far. function Atomo.stats(): any local q = queue if not q then return { queued = 0, taken = 0, refused = 0, dropped = early, replaced = 0, skipped = 0 } end local stats = q:stats() stats.dropped += early return stats end return Atomo ]]> Queue number, -- seconds, only ever forward wait: (seconds: number) -> (), spawn: (fn: () -> ()) -> thread, -- in a thread of its own, at once frame: (fn: () -> ()) -> (), -- calls it once a whole frame has gone by random: () -> number, -- 0 to 1 encode: (value: any) -> string, -- may error decode: (text: string) -> any, -- may error close: (thread: thread) -> (), -- ends one that has yielded -- 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. May yield. send: (body: string, timeout: number) -> (number, string, number?), warn: (text: string) -> (), } export type Options = { scope: string, quiet: boolean, maxSize: number } export type Info = { version: any, time: any, users: any, untold: boolean? } -- `before`, `value` and `after` are its JSON, in three parts so that a big save is put together only once. type Item = { id: string, store: string, before: string, value: string, after: string, version: string, time: number, size: number, at: number, out: boolean, alone: number, failedAt: number, removal: boolean, whole: boolean, calledAt: number? } type Large = { tooLarge: boolean, takenAt: number } export type Stats = { queued: number, taken: number, refused: number, dropped: number, replaced: number, skipped: number } local MB = 1024 * 1024 local MAX_ITEMS = 500 local MAX_BYTES = 8 * MB -- with what is being sent local MAX_KEY = 200 local MAX_NAME = 50 -- of a data store, as Roblox allows local MAX_USERS = 20 local MAX_STORES = 10 local LARGE = 500 * 1024 local LARGE_PLAYER = 290 -- seconds between one key's large saves: a little under 5 minutes, for one that comes early local LARGE_SERVER = 10 -- and between any two, with up to half as much again, so that it isn't always the same ones that are skipped local REMEMBERED = 1000 -- keys known to be large local FRAME = 0.004 -- seconds of one frame that the copies may take together local BATCH_ITEMS = 50 local BATCH_BYTES = 900 * 1024 -- one bigger save goes alone local MINUTE = 61 -- a little more, for a clock that isn't exact local PER_MINUTE = 12 -- requests, whatever they are for: 2.4% of the game's 500 local GAP = 7.5 -- seconds between requests: 8 a minute, so that 4 are left for closing local CLOSE_GAP = 1 local FIRST_JITTER = 10 local FIRST_WAIT = 5 local LONGEST_WAIT = 300 local AWAY = 1800 -- gone for this long: one try in RARELY local RARELY = 600 local WRONG_WAIT = 60 -- a wrong key won't fix itself soon, nor will the game have requests to spare local TIMEOUT = 6 local CLOSE_LIMIT = 5 local CLOSE_QUIET = 1 -- of those, without a report: the game is still saving local CLOSE_GATHER = 0.5 -- so that one request takes many local MAX_ANSWER = 16 * 1024 local AGE_BYTES = 40 -- "age" and what follows it, at most local MOST_AGE = 86400000 -- milliseconds a removal may wait, as Atomo allows local STUCK = 60 -- a request that still hasn't ended by then never will local GIVE_UP = 5 -- times one save fails alone, while others arrive local QUIET_FAILURES = 3 local WARN_EVERY = 600 -- Nothing a server says is printed but these. local REASONS: { [string]: boolean } = { bad_save = true, bad_key = true, bad_version = true, bad_time = true, bad_value = true, bad_users = true, too_large = true, too_deep = true, cant_store = true, mock_save = true, storage_full = true, } -- ProfileStore's stand-in for a data store starts its versions like this. What it saves isn't in Roblox, and its -- versions begin again each time. local MOCK = "0000000000000000." local Queue = {} Queue.__index = Queue type Self = { deps: Deps, options: Options, items: { [number]: Item? }, first: number, last: number, byId: { [string]: Item? }, count: number, bytes: number, stores: { [string]: number }, -- each one's name, and until when it is left alone names: { [string]: string }, -- each one's name as JSON scope: string, -- as JSON storeCount: number, large: { [string]: Large }, largeCount: number, nextLarge: number, untold: number, -- large saves skipped that Atomo hasn't been told about spent: number, -- seconds of this frame frameAt: number?, sending: boolean, sendingAt: number, sender: thread?, lastOk: boolean, -- what was sent last is dealt with flying: { Item }, -- the batch being sent. Those still `out` count as queued flyingBytes: number, sent: { number }, -- when the last requests were made notBefore: number, noUse: boolean, -- the last try says closing needn't try failures: number, failingSince: number, wrongs: number, busy: number, -- times in a row that the game had no requests to spare tagged: boolean, -- NaN and infinity are written so that they can be read most: number, -- saves in a batch: fewer while sends fail, in case it is the size hunting: boolean, -- for one save that can't be read fine: number, -- saves that arrived since the hunt began arrivedAt: number, lastPush: number, closing: boolean, over: boolean, -- Atomo said to stop warnedAt: { [string]: number }, tally: { taken: number, refused: number, dropped: number, replaced: number, skipped: number }, } export type Queue = typeof(setmetatable({} :: Self, Queue)) -- Roblox's docs say it writes NaN and infinity as they are, which isn't JSON: then nothing else in the batch could be -- read. Its engine writes them as tables instead (measured in Studio 0.748). local function tags(encode: (any) -> string): boolean local ok, text = pcall(encode, { 0 / 0 }) return ok and string.sub(text, 1, 2) == "[{" end function Queue.new(deps: Deps, options: Options): Queue local self: Self = { deps = deps, options = options, items = {}, first = 1, last = 0, byId = {}, count = 0, bytes = 0, stores = {}, names = {}, scope = deps.encode(options.scope), storeCount = 0, large = {}, largeCount = 0, nextLarge = -math.huge, untold = 0, spent = 0, frameAt = nil, sending = false, sendingAt = 0, lastOk = true, flying = {}, flyingBytes = 0, sent = {}, notBefore = deps.now() + deps.random() * FIRST_JITTER, noUse = false, failures = 0, failingSince = 0, wrongs = 0, busy = 0, tagged = tags(deps.encode), most = BATCH_ITEMS, hunting = false, fine = 0, arrivedAt = -math.huge, lastPush = -math.huge, closing = false, over = false, warnedAt = {}, tally = { taken = 0, refused = 0, dropped = 0, replaced = 0, skipped = 0 }, } return setmetatable(self, Queue) end --- Once in 10 minutes for each kind, or `once` for as long as the server runs. function Queue.say(self: Queue, 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 < WARN_EVERY)) then return end self.warnedAt[what] = now pcall(self.deps.warn, `Atomo: {text}`) end local function finite(value: any): boolean if type(value) == "number" then return value == value and value ~= math.huge and value ~= -math.huge elseif type(value) == "table" then for k, v in next, value do if not finite(k) or not finite(v) then return false end end end return true end local function newer(a: Item, b: Item): boolean if a.time ~= b.time then return a.time > b.time end return a.version > b.version end local function remove(self: Queue, item: Item) self.items[item.at] = nil self.byId[item.id] = nil self.count -= 1 self.bytes -= item.size while self.first <= self.last and not self.items[self.first] do self.first += 1 end end local function put(self: Queue, item: Item, at: number) item.at = at self.items[at] = item self.byId[item.id] = item self.count += 1 self.bytes += item.size self.first = math.min(self.first, at) self.last = math.max(self.last, at) -- One that waits long at the front leaves a long row of empty places behind it. if self.last - self.first > 4 * MAX_ITEMS then local row: { [number]: Item? } = {} local n = 0 for place = self.first, self.last do local one = self.items[place] if one then n += 1 one.at = n row[n] = one end end self.items, self.first, self.last = row, 1, n end end local function makeRoom(self: Queue) while self.count > 0 and (self.count > MAX_ITEMS or self.bytes + self.flyingBytes > MAX_BYTES) do remove(self, self.items[self.first] :: Item) self.tally.dropped += 1 self:say("full", "the queue is full, so the oldest saves are dropped.") end end -- Time taken of this frame. local function charge(self: Queue, seconds: number) self.spent += math.max(0, seconds) if self.frameAt == nil then self.frameAt = self.deps.now() pcall(self.deps.frame, function() self.spent, self.frameAt = 0, nil end) end end local function remember(self: Queue, id: string, what: Large?) if what and not self.large[id] then if self.largeCount >= REMEMBERED then -- One goes: if it can be, one that is only large. local goes = next(self.large) for one, about in self.large do if not about.tooLarge then goes = one break end end self.large[goes :: string] = nil self.largeCount -= 1 end self.largeCount += 1 elseif not what and self.large[id] then self.largeCount -= 1 end self.large[id] = what :: any end -- "skipped" if it isn't taken this time; another word if it can't be, which is why; nil if it was. The words are ours -- alone: what Roblox says can name a player. local function add(self: Queue, removal: boolean, store: any, key: any, saved: any, read: () -> Info): string? if type(store) ~= "string" or store == "" or #store > MAX_NAME then return "no data store's name" elseif type(key) ~= "string" or key == "" or #key > MAX_KEY then return "no key" elseif saved == nil and not removal then return "no data" end local now = self.deps.now() local alone = self.stores[store] local name: string? = nil if alone == nil then if self.storeCount >= MAX_STORES then return "too many data stores" end name = self.deps.encode(store) -- before the copy, which may be big elseif now < alone then return "skipped" end -- A removal and a save of one key don't replace each other. local id = `{if removal then "-" else "+"}{store}\0{key}` local known = self.large[id] if known and (known.tooLarge or now < self.nextLarge or now - known.takenAt < LARGE_PLAYER) then self.untold += 1 return "skipped" end local info = read() if removal and info.untold then -- No key info, as ProfileStore's RemoveAsync gives. How long ago it was called is added as it is sent, from this -- server's steady clock; Atomo dates it on arrival. The server's own date can be wrong by any amount. local item: Item = { id = id, store = store, before = `\{"key":{self.deps.encode(key)},"removed":true,`, value = "", after = "", version = "", time = math.huge, size = 0, at = 0, out = false, alone = 0, failedAt = 0, removal = true, whole = false, calledAt = now } item.size = #item.before + AGE_BYTES if self.over then return nil elseif self.stores[store] == nil then if self.storeCount >= MAX_STORES then return "too many data stores" end self.names[store] = name :: string self.storeCount += 1 end self.stores[store] = now local waiting = self.byId[id] if waiting then self.tally.replaced += 1 if waiting.calledAt then waiting.calledAt = now -- the same removal, told again: the later call counts return nil end remove(self, waiting) end put(self, item, self.last + 1) makeRoom(self) return nil end local version, time, users = info.version, info.time, info.users if type(version) ~= "string" or not string.match(version, "^[\33-\126]+$") or #version > 200 then return "no version" elseif string.sub(version, 1, #MOCK) == MOCK then return "it's from a mock data store" elseif type(time) ~= "number" or not (time > 0 and time < 2 ^ 53 and time % 1 == 0) then return "no time" end local ids = {} for _, user in users or {} do if #ids >= MAX_USERS or not (user > 0 and user < 2 ^ 53 and user % 1 == 0) then return "its user IDs" end table.insert(ids, string.format("%d", user)) end local about = `"version":{self.deps.encode(version)},"time":{string.format("%d", time)},"users":[{table.concat(ids, ",")}]}` local before, value, after = `\{"key":{self.deps.encode(key)},`, "", about if removal then before ..= '"removed":true,' else -- The copy: the game may change its table afterwards. value = self.deps.encode(saved) if value == "null" then return "no data" elseif not self.tagged and not finite(saved) then return "NaN or infinity" end before ..= '"value":' after = `,{about}` if #value > self.options.maxSize then remember(self, id, { tooLarge = true, takenAt = now }) return "too large" elseif #value > LARGE then if now < self.nextLarge then remember(self, id, { tooLarge = false, takenAt = -math.huge }) self.untold += 1 return "skipped" end remember(self, id, { tooLarge = false, takenAt = now }) self.nextLarge = now + LARGE_SERVER * (1 + self.deps.random() / 2) else remember(self, id, nil) end end if self.over then return nil elseif self.stores[store] == nil then if self.storeCount >= MAX_STORES then return "too many data stores" end self.names[store] = name :: string self.storeCount += 1 end self.stores[store] = now local item: Item = { id = id, store = store, before = before, value = value, after = after, version = version, time = time, size = #before + #value + #after, at = 0, out = false, alone = 0, failedAt = 0, removal = removal, whole = false } local waiting = self.byId[id] if waiting then self.tally.replaced += 1 if not newer(item, waiting) then return nil end remove(self, waiting) end put(self, item, self.last + 1) makeRoom(self) return nil end -- Whatever was to say that the frame is over didn't. local function newFrame(self: Queue) if self.frameAt and self.deps.now() - self.frameAt > 1 then self.spent, self.frameAt = 0, nil end end --- Never yields and never errors, whatever it is given. function Queue.push(self: Queue, removal: boolean, store: any, key: any, saved: any, read: () -> Info) if self.over then return end local started = self.deps.now() self.lastPush = started newFrame(self) if self.spent >= FRAME and not self.closing then self.tally.skipped += 1 return end local why: string? = "it yielded" -- In a thread of its own, so even a strange `info` can't hold up the game's save code. local thread = coroutine.create(function() local ok, reason = pcall(add, self, removal, store, key, saved, read) why = if ok then reason else "it can't be read" end) coroutine.resume(thread) if coroutine.status(thread) ~= "dead" then pcall(self.deps.close, thread) end charge(self, self.deps.now() - started) if why == "skipped" then self.tally.skipped += 1 elseif why ~= nil then self.tally.refused += 1 self:say("unreadable", `a save couldn't be reported: {why}.`) end end -- The oldest, and whatever goes with it: of the same data store, because one request is about one. local function take(self: Queue): { Item } local out: { Item } = {} local size = 0 local now = self.deps.now() local stale: { Item } = {} for at = self.first, self.last do local item = self.items[at] if item and item.calledAt and now - item.calledAt > MOST_AGE / 1000 then -- Atomo takes no wait longer than a day, and a wrong one would date it wrongly. table.insert(stale, item) elseif item and (#out == 0 or item.store == out[1].store) then if #out >= self.most or (#out > 0 and (item.alone >= 2 or size + item.size > BATCH_BYTES)) then break end table.insert(out, item) size += item.size if item.alone >= 2 then break end end end for _, item in stale do remove(self, item) self.tally.dropped += 1 end for _, item in out do remove(self, item) item.out = true end return out end -- Back to the front, or the end, unless something newer for that player came meanwhile. local function giveBack(self: Queue, items: { Item }, last: boolean?) for i = #items, 1, -1 do local item = items[i] item.out = false self.flyingBytes -= item.size local waiting = self.byId[item.id] if waiting and not newer(item, waiting) then self.tally.replaced += 1 continue elseif waiting then self.tally.replaced += 1 remove(self, waiting) end put(self, item, if last then self.last + 1 else self.first - 1) -- What goes to the end takes the removal of its key along: a save before its removal. local removal = if last and not item.removal then self.byId["-" .. string.sub(item.id, 2)] else nil if removal then remove(self, removal) put(self, removal, self.last + 1) end end makeRoom(self) end -- They won't come back. local function done(self: Queue, items: { Item }) for _, item in items do item.out = false self.flyingBytes -= item.size end end local function bodyOf(self: Queue, items: { Item }): string local first = items[1] if first.whole then return first.value end local big = first.size > BATCH_BYTES -- alone, then, also the next time local parts = table.create(#items * 4 + 1) table.insert(parts, `\{"store":{self.names[first.store]},"scope":{self.scope},{if self.untold > 0 and not big then `"skipped":{string.format("%d", self.untold)},` else ""}"saves":[`) for i, item in items do if i > 1 then table.insert(parts, ",") end table.insert(parts, item.before) table.insert(parts, item.value) if item.calledAt then table.insert(parts, `"age":{string.format("%d", math.clamp(math.floor((self.deps.now() - item.calledAt) * 1000), 0, MOST_AGE))},"users":[]}`) else table.insert(parts, item.after) end end table.insert(parts, "]}") local body = table.concat(parts) if big then -- Not kept twice. first.before, first.value, first.after, first.whole = "", body, "", true end return body end local function clear(self: Queue) self.items, self.byId, self.first, self.last, self.count, self.bytes = {}, {}, 1, 0, 0, 0 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: Queue, seconds: number, atLeast: number) self.notBefore = self.deps.now() + math.max(seconds * (0.5 + self.deps.random() / 2), atLeast) end local function backOff(self: Queue, 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 -- No answer, or not now. It may be the network, or that this was too much at once: the next batch is smaller, -- and one save that still fails alone lets the others past. It is given up only when they arrive and it doesn't. local function failed(self: Queue, items: { Item }, asked: number?) if #items > 1 then self.most = math.max(1, #items // 2) giveBack(self, items) else local item = items[1] local now = self.deps.now() -- Counts only if something else arrived since it last failed: an outage is nobody's fault. if item.alone == 0 or self.arrivedAt > item.failedAt then item.alone += 1 end item.failedAt = now if item.alone >= GIVE_UP then done(self, items) self.tally.dropped += 1 self:say("stuck", "a save couldn't be sent, and was dropped.") else giveBack(self, items, true) end end backOff(self, asked) if self.failures >= QUIET_FAILURES then self:say("unreachable", `can't be reached. Saves waiting: {self.count}.`) end end -- Sends these once, or gives them back. True if they're dealt with. local function deliver(self: Queue, items: { Item }, timeout: number): boolean local before = self.deps.now() local telling = if items[1].size > BATCH_BYTES then 0 else self.untold local body = bodyOf(self, items) charge(self, self.deps.now() - before) if not items[1].whole then self.flyingBytes += #body makeRoom(self) end local ok, status: any, text: any, asked: any = pcall(self.deps.send, body, timeout) if self.flying ~= items then return false -- it was given up meanwhile end 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 type(value) == "table" then answer = value end end self.noUse = false if status == 200 then local taken: any, refused: any = answer.taken, answer.refused if type(taken) == "number" and type(refused) == "table" and taken >= 0 and taken + #refused == #items then self.failures, self.wrongs, self.busy = 0, 0, 0 self.fine += #items if self.fine >= BATCH_ITEMS or self.count == 0 then self.hunting = false -- what couldn't be read isn't there any more end if not self.hunting then self.most = math.min(BATCH_ITEMS, self.most * 2) end self.arrivedAt, self.notBefore = self.deps.now(), -math.huge self.untold -= telling done(self, items) self.tally.taken += taken self.tally.refused += #refused for _, one: any in ipairs(refused) do local about: any = if type(one) == "table" then one else {} local item = if type(about.i) == "number" then items[about.i + 1] else nil -- A server from before removals knows none. if not (item and item.removal and about.why == "bad_value") then self:say("refused", `refused {#refused} of {#items} saves: {if type(about.why) == "string" and REASONS[about.why] then about.why else "no reason given"}.`) break end end return true end status = 0 -- something else answered end if status == 410 then self.over = true done(self, items) clear(self) return true elseif status == 404 and answer.error == "no_such_store" then -- What is being sent and what waits for it go; the other stores aren't held up. local store = items[1].store done(self, items) self.tally.dropped += #items for at = self.first, self.last do local item = self.items[at] if item and item.store == store then remove(self, item) self.tally.dropped += 1 end end self.stores[store] = self.deps.now() + RARELY self:say("store", "a data store isn't connected. Its saves aren't reported.", true) return true elseif (status == 400 and answer.error == "not_json") or status == 413 then -- Only these two are about what was sent. Anything else that calls itself 400 isn't a reason to lose a save. self.failures, self.wrongs, self.busy = 0, 0, 0 if #items == 1 then done(self, items) self.most, self.hunting = BATCH_ITEMS, false self.tally.refused += 1 self:say("refused", `refused a save ({status}).`) return true end -- One of them can't be read. The next batch is half as big, until it is alone. self.most, self.hunting, self.fine = #items // 2, true, 0 giveBack(self, items) return true elseif status == -1 then giveBack(self, items) self.noUse = true self.notBefore = self.deps.now() + RARELY self:say("off", "HTTP requests are off in this experience's security settings.", true) elseif status == -2 then giveBack(self, items) self.noUse = true self.notBefore = self.deps.now() + math.min(RARELY, WRONG_WAIT * 2 ^ math.min(self.busy, 10)) self.busy += 1 elseif status == 429 then giveBack(self, items) backOff(self, asked) if self.failures >= QUIET_FAILURES then self:say("slow", `has to wait, too many requests. Saves waiting: {self.count}.`) end elseif status >= 300 and status < 500 and status ~= 408 then giveBack(self, items) 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." else `the address is wrong, or it can't answer ({math.floor(status)}).`, true) else failed(self, items, asked) end return false 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: Queue, timeout: number) local now = self.deps.now() table.insert(self.sent, now) if #self.sent > PER_MINUTE then table.remove(self.sent, 1) end local items = take(self) self.sending, self.sendingAt, self.lastOk, self.flying, self.flyingBytes = true, now, false, items, 0 for _, item in items do self.flyingBytes += item.size end self.sender = self.deps.spawn(function() local ok, dealt = pcall(deliver, self, items, timeout) if self.flying ~= items then return elseif not ok then -- Sent twice does no harm. local left: { Item } = {} for _, item in items do if item.out then table.insert(left, item) end end giveBack(self, left) backOff(self) end self.sending, self.lastOk, self.flying, self.flyingBytes = false, ok and dealt, {}, 0 end) end -- A request that was ended with its thread, or that never ends. What it held waits again. function Queue.unstick(self: Queue) if self.sending and self.deps.now() - self.sendingAt > STUCK then local items = self.flying self.sending, self.flying = false, {} pcall(self.deps.close, self.sender :: thread) giveBack(self, items) self.flyingBytes = 0 backOff(self) end end -- When the next request may be made: never more than PER_MINUTE in a minute. local function allowedAt(self: Queue): number return if #self.sent >= PER_MINUTE then self.sent[1] + MINUTE else -math.huge end --- Sends one batch if it is time. How many seconds to wait before the next, or nil if there is nothing to send. function Queue.step(self: Queue): number? self:unstick() newFrame(self) if self.over or (self.count == 0 and not self.sending) then return nil elseif self.sending then return 1 elseif self.spent >= FRAME and not self.closing then return 0.05 end local gap = if self.closing then CLOSE_GAP else GAP 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, TIMEOUT) return gap end --- Sends what is waiting, for this long at most and never over 5 s, and ends as soon as a try fails or nothing is left: --- when closing, once nothing has come for a second either. True if nothing is left. Yields. function Queue.flush(self: Queue, seconds: number?): boolean self:unstick() local start = self.deps.now() local ends = start + math.min(CLOSE_LIMIT, seconds or CLOSE_LIMIT) local quiet = if self.closing and self.lastPush > -math.huge then CLOSE_QUIET else 0 local tried = false while not self.over do local now = self.deps.now() local left = ends - now local still = now - math.max(start, self.lastPush) local empty = self.count == 0 and not self.sending local away = self.noUse or self.failures >= QUIET_FAILURES or (now < self.notBefore and not self.closing) if empty and still >= quiet then return true elseif away or left <= 0 or (tried and not self.sending and not self.lastOk) then return false elseif self.sending or empty or (quiet > 0 and still < CLOSE_GATHER and left > 1.5 and self.count < BATCH_ITEMS and self.bytes < BATCH_BYTES) then self.deps.wait(math.min(0.1, left)) elseif left < 1 or now < allowedAt(self) then return false else tried = true post(self, math.min(TIMEOUT, math.floor(left))) end end return true end function Queue.stats(self: Queue): Stats local t = self.tally local queued = self.count for _, item in self.flying do queued += if item.out then 1 else 0 end return { queued = queued, taken = t.taken, refused = t.refused, dropped = t.dropped, replaced = t.replaced, skipped = t.skipped } end return Queue ]]>