RoStructureSetup Tag Editor) record more with no code: StageStart and Checkpoint (attribute StageId) and KillPart -- (attribute Cause). For your own events, use the returned client: -- analytics:track(player, "bought_item", { metadata = { item = "sword" } }) local analytics = RoStructure.init({ projectId = PROJECT_ID, ingestionKey = INGESTION_KEY, buildId = BUILD_ID, enableInStudio = ENABLE_IN_STUDIO, map = MAP, }) ]]>RoStructureBackoff d then d = math.min(retryAfter, MAX_RETRY_AFTER) end return d end -- ok: delivered. retry: transient. drop: this batch can never succeed. pause: credentials or -- configuration are wrong, so stop sending for a while instead of hammering the API. function Backoff.classify(status: number): Verdict if status >= 200 and status < 300 then return "ok" elseif status == 401 or status == 403 then return "pause" elseif status == 0 or status == 408 or status == 425 or status == 429 or status >= 500 then return "retry" end return "drop" end return Backoff ]]>Client HTTP {response.StatusCode}`) return response end end local sender = Sender.new({ ring = ring, url = string.gsub(endpoint, "/+$", "") .. INGEST_PATH, headers = { ["Content-Type"] = "application/json", ["X-Ingestion-Key"] = config.ingestionKey, ["X-Project-Id"] = config.projectId, }, sdkVersion = SDK_VERSION, idPrefix = ctx.idPrefix, request = request, warn = function(message: string) warn(`[RoStructure] {message}`) end, batchSize = batchSize, -- The API rejects bodies over 256 KiB; leave headroom for the envelope. maxBatchBytes = 200000, -- One request per server per half minute when quiet. Events carry their own timestamps, so the delay does -- not shift any chart, and players online is recomputed over the last 15 minutes. Studio keeps 5 seconds so -- a test session shows up on the dashboard quickly. flushInterval = config.flushInterval or (if RunService:IsStudio() then 5 else 30), maxRetries = config.maxRetries or 5, baseDelay = 1, maxDelay = 30, -- HttpService allows 500 requests/minute per server; 0.25s spacing caps us at 240. minGap = 0.25, maxInFlight = 2, pauseSeconds = 300, compress = config.compress ~= false, }) local autoTrack = config.autoTrack or {} local self: State = { enabled = true, ctx = ctx, ring = ring, sender = sender, players = {}, connections = {}, sampling = config.sampling or {}, autoDeaths = autoTrack.deaths ~= false, autoQuits = autoTrack.quits ~= false, autoSessions = autoTrack.sessions ~= false, revenue = config.revenue == true, revenueAuto = config.revenue == true and config.revenueAuto ~= false, receipts = {}, receiptCount = 0, salt = config.pseudonymSalt or config.ingestionKey, projectId = config.projectId, shutdownBudget = config.shutdownBudget or 20, warned = {}, rng = Random.new(), namedSteps = {}, } local client = setmetatable(self, Client) client:_connect() if client.revenueAuto then -- Passive: only listens to purchase-finished events. ProcessReceipt is never touched. for _, connection in Revenue.bind(client, function(message: string) warn(`[RoStructure] {message}`) end) do table.insert(client.connections, connection) end end return client end function Client._emit( self: Client, state: PlayerState, eventName: string, position: Vector3?, stageJson: string?, metadataJson: string? ) local ctx, sender = self.ctx, self.sender if not ctx or not sender then return end local x: number?, y: number?, z: number? if position then x, y, z = position.X, position.Y, position.Z end local line = Wire.encode( ctx, state.fragment, eventName, DateTime.now().UnixTimestampMillis, x, y, z, stageJson, state.device, metadataJson ) Ring.push(self.ring, line) sender:notify() end function Client._track(self: Client, player: Player, eventName: string, fields: Types.Fields?) local state = self.players[player] if not state then return end if not Wire.isValidName(eventName) then warnOnce(self, "name:" .. tostring(eventName), `invalid event name {tostring(eventName)}; use snake_case, at most 64 characters`) return end local rate = self.sampling[eventName] if rate and rate < 1 and self.rng:NextNumber() >= rate then return end local position: Vector3? = nil local stageJson = state.stageJson local metadataJson: string? = nil if fields then local requested = fields.position if requested == true then position = rootPosition(player) elseif typeof(requested) == "Vector3" then position = requested end if position and not (isFinite(position.X) and isFinite(position.Y) and isFinite(position.Z)) then position = nil end if position then state.lastPosition = position end if fields.stageId ~= nil then stageJson = Wire.stageJson(fields.stageId) end if fields.metadata then local json, reason = Wire.metadataJson(fields.metadata) if reason then warnOnce(self, "meta:" .. eventName, `{eventName}: {reason}; sending without metadata`) end metadataJson = json end end self:_emit(state, eventName, position, stageJson, metadataJson) end -- Records an event for a player currently in the server. Never throws. function Client.track(self: Client, player: Player, eventName: string, fields: Types.Fields?) if not self.enabled then return end local ok, err = pcall(self._track, self, player, eventName, fields) if not ok then warnOnce(self, "track", `track failed: {err}`) end end function Client._startFunnel(self: Client, player: Player, key: string) local state = self.players[player] if not state then return end if not Wire.isValidName(key) then warnOnce(self, "funnel:" .. tostring(key), `invalid funnel key {tostring(key)}; use snake_case, at most 64 characters`) return end local started = state.funnels if not started then started = {} state.funnels = started end if started[key] then return end local count = state.funnelCount or 0 if count >= MAX_FUNNELS_PER_SESSION then warnOnce(self, "funnels", `a player can be started in at most {MAX_FUNNELS_PER_SESSION} funnels per session`) return end started[key] = true state.funnelCount = count + 1 -- Never sampled: funnel counts must be exact. The key is snake_case, so it needs no JSON escaping. self:_emit(state, "funnel_started", nil, state.stageJson, '{"funnel":"' .. key .. '"}') end function Client._markNewPlayer(self: Client, player: Player) local state = self.players[player] if not state or state.markedNew then return end state.markedNew = true -- Never sampled: retention cohorts must be exact. self:_emit(state, "new_player", nil, nil, nil) end -- Tells RoStructure this is the player's first visit, so Retention measures them as a new player. Call it once, when -- your own save data shows the player has never played before (not on every join). Once a game sends this, only -- players marked this way form retention cohorts, so veterans first seen after you added RoStructure never count as -- new. One small event per new player; repeat calls in the same session send nothing. Never throws. function Client.markNewPlayer(self: Client, player: Player) if not self.enabled then return end local ok, err = pcall(self._markNewPlayer, self, player) if not ok then warnOnce(self, "markNewPlayer", `markNewPlayer failed: {err}`) end end -- Puts a player in the dashboard funnel whose key is `key`. Funnels that start with startFunnel count ONLY players started this way, so call it -- when your game knows the player should be measured, for example when your own save data shows a brand-new player -- reaching the tutorial. Players you never start (such as those who finished the tutorial before you added -- RoStructure) are not counted as entrants or drop-offs. One small event per player, funnel and session; repeat -- calls in the same session send nothing. Never throws. function Client.startFunnel(self: Client, player: Player, key: string) if not self.enabled then return end local ok, err = pcall(self._startFunnel, self, player, key) if not ok then warnOnce(self, "startFunnel", `startFunnel failed: {err}`) end end function Client._logFunnelStep(self: Client, player: Player, key: string, step: number, name: string?) local state = self.players[player] if not state then return end if not Wire.isValidName(key) then warnOnce(self, "funnel:" .. tostring(key), `invalid funnel key {tostring(key)}; use snake_case, at most 64 characters`) return end if type(step) ~= "number" or step % 1 ~= 0 or step < 1 or step > MAX_FUNNEL_STEP then warnOnce(self, "funnelStep:" .. key, `{key}: funnel steps are whole numbers from 1 to {MAX_FUNNEL_STEP}`) return end local id = key .. "#" .. string.format("%d", step) local logged = state.funnelSteps if not logged then logged = {} state.funnelSteps = logged end if logged[id] then return end local count = state.funnelStepCount or 0 if count >= MAX_FUNNEL_STEPS_PER_SESSION then warnOnce(self, "funnelSteps", `a player can log at most {MAX_FUNNEL_STEPS_PER_SESSION} funnel steps per session`) return end logged[id] = true state.funnelStepCount = count + 1 -- Key and step are plain ASCII, so they need no escaping. The name is sent once per server and step, which is all -- the dashboard needs to label it. local metadata = '{"funnel":"' .. key .. '","step":' .. string.format("%d", step) if type(name) == "string" and name ~= "" and not self.namedSteps[id] then local ok, encoded = pcall(HttpService.JSONEncode, HttpService, string.sub(name, 1, MAX_FUNNEL_STEP_NAME)) if ok then self.namedSteps[id] = true metadata ..= ',"name":' .. encoded end end -- Never sampled: funnel counts must be exact. self:_emit(state, "funnel_step", nil, state.stageJson, metadata .. "}") end -- Logs a numbered step of a funnel, like Roblox's AnalyticsService:LogFunnelStepEvent. No start call and no dashboard -- setup: the funnel appears in Funnels on its own, steps ordered by number and named by `name`, and a session enters -- at step 1. To leave out existing players (for example a tutorial they finished before you added RoStructure), only -- log steps for players your game wants measured. Each step is sent once per player and session. Never throws. -- analytics:logFunnelStep(player, "tutorial", 1, "Joined") function Client.logFunnelStep(self: Client, player: Player, key: string, step: number, name: string?) if not self.enabled then return end local ok, err = pcall(self._logFunnelStep, self, player, key, step, name) if not ok then warnOnce(self, "logFunnelStep", `logFunnelStep failed: {err}`) end end -- Records the exact amount from a receipt. Call it at the top of YOUR OWN ProcessReceipt / receipt handler; it only -- reads the table, never yields and returns nothing, so it cannot change what your handler does. Set revenueAuto = -- false in init when you use this, so purchases are not recorded twice. Each PurchaseId is recorded once. function Client.trackReceipt(self: Client, receiptInfo: { [string]: any }) if not self.enabled or not self.revenue then return end pcall(function() local purchaseId = receiptInfo.PurchaseId local userId = receiptInfo.PlayerId local spent = receiptInfo.CurrencySpent if type(purchaseId) ~= "string" or type(userId) ~= "number" or type(spent) ~= "number" then return end if receiptInfo.CurrencyType ~= nil and receiptInfo.CurrencyType ~= Enum.CurrencyType.Robux then return end if self.receipts[purchaseId] then return end if self.receiptCount >= 500 then table.clear(self.receipts) self.receiptCount = 0 end self.receipts[purchaseId] = true self.receiptCount += 1 local player = Players:GetPlayerByUserId(userId) if player then self:trackPurchase(player, { kind = "product", robux = spent, productId = receiptInfo.ProductId }) end end) end local PURCHASE_EVENTS: { [string]: string } = { product = "developer_product_purchased", gamepass = "gamepass_purchased", } -- Records a completed purchase with its Robux amount. Does nothing unless `revenue = true` was set in init, and -- the API additionally discards revenue for projects that have not enabled it in the dashboard. Never throws. function Client.trackPurchase(self: Client, player: Player, purchase: Types.Purchase) if not self.enabled or not self.revenue then return end local robux = purchase.robux if type(robux) ~= "number" or not isFinite(robux) or robux < 0 then warnOnce(self, "purchase", "trackPurchase needs robux >= 0") return end local kind = purchase.kind or "other" local revenue: { [string]: any } = { robux = robux, kind = kind } if purchase.productId ~= nil then revenue.productId = tostring(purchase.productId) end if purchase.productName ~= nil then revenue.productName = purchase.productName end self:track(player, PURCHASE_EVENTS[kind] or "item_purchased", { metadata = { revenue = revenue } }) end -- Default stage for the player's subsequent events. Pass nil to clear. function Client.setStage(self: Client, player: Player, stageId: string?) local state = self.players[player] if state then state.stageJson = if stageId ~= nil then Wire.stageJson(stageId) else nil end end -- Device is client-reported and therefore only a hint. Call it from your own validated remote. function Client.setDevice(self: Client, player: Player, device: string) local state = self.players[player] if state and Wire.DEVICES[device] then state.device = device end end function Client._onCharacter(self: Client, player: Player, character: Model) local humanoid = character:FindFirstChildOfClass("Humanoid") or character:WaitForChild("Humanoid", 10) if not humanoid or not humanoid:IsA("Humanoid") or not self.players[player] then return end humanoid.Died:Once(function() local root = character:FindFirstChild("HumanoidRootPart") local position = if root and root:IsA("BasePart") then root.Position else nil self:track(player, "player_died", { position = position }) end) end function Client._onPlayerAdded(self: Client, player: Player) if self.players[player] then return end local sessionId = HttpService:GenerateGUID(false) local anonymousId = "p_" .. string.sub(Sha256.hex(`{self.salt}|{self.projectId}|{idNumber(player.UserId)}`), 1, 32) local state: PlayerState = { fragment = Wire.playerFragment(sessionId, anonymousId), joinedAt = os.clock(), stageJson = nil, device = nil, lastPosition = nil, characterConn = nil, } self.players[player] = state if self.autoSessions then self:track(player, "session_started") end if self.autoDeaths then state.characterConn = player.CharacterAdded:Connect(function(character) self:_onCharacter(player, character) end) if player.Character then task.spawn(self._onCharacter, self, player, player.Character) end end end function Client._onPlayerRemoving(self: Client, player: Player) local state = self.players[player] if not state then return end if self.autoQuits then self:track(player, "player_quit", { position = rootPosition(player) or state.lastPosition }) end if self.autoSessions then self:track(player, "session_ended", { metadata = { durationSeconds = math.floor(os.clock() - state.joinedAt) }, }) end if state.characterConn then state.characterConn:Disconnect() end self.players[player] = nil end function Client._connect(self: Client) table.insert(self.connections, Players.PlayerAdded:Connect(function(player) self:_onPlayerAdded(player) end)) table.insert(self.connections, Players.PlayerRemoving:Connect(function(player) self:_onPlayerRemoving(player) end)) for _, player in Players:GetPlayers() do task.spawn(self._onPlayerAdded, self, player) end end -- Sends what is queued and waits up to `budgetSeconds` (default: the shutdown budget). Yields. function Client.flush(self: Client, budgetSeconds: number?) if self.sender then self.sender:flush(budgetSeconds or self.shutdownBudget) end end -- Ends open sessions, disconnects and flushes. Bound to game:BindToClose by RoStructure.init. function Client.shutdown(self: Client) if not self.enabled then return end for _, connection in self.connections do connection:Disconnect() end table.clear(self.connections) local remaining = {} for player in self.players do table.insert(remaining, player) end for _, player in remaining do self:_onPlayerRemoving(player) end self:flush() self.enabled = false end function Client.stats(self: Client): Types.Stats if self.sender then return self.sender:stats() end return { queued = 0, inFlight = 0, requests = 0, sentEvents = 0, droppedEvents = 0, retries = 0 } end return Client ]]>Device (), clock: () -> number ): ((any, any) -> boolean, (any) -> ()) local lastAt: { [any]: number } = {} local reports: { [any]: number } = {} local function handle(player: any, value: any): boolean if type(value) ~= "string" or not Wire.DEVICES[value] then return false end local now = clock() local previous = lastAt[player] if previous and now - previous < MIN_GAP then return false end local count = (reports[player] or 0) + 1 if count > MAX_REPORTS_PER_PLAYER then return false end lastAt[player] = now reports[player] = count setDevice(player, value) return true end local function forget(player: any) lastAt[player] = nil reports[player] = nil end return handle, forget end -- Creates the remote, installs the client script for players who join from now on, and connects the handler. -- Returns a function that undoes it. function Device.bind(analytics: any): () -> () local existing = ReplicatedStorage:FindFirstChild(REMOTE_NAME) local remote: RemoteEvent if existing and existing:IsA("RemoteEvent") then remote = existing else remote = Instance.new("RemoteEvent") remote.Name = REMOTE_NAME remote.Parent = ReplicatedStorage end local handle, forget = Device.makeHandler(function(player, device) analytics:setDevice(player, device) end, os.clock) local connections = { remote.OnServerEvent:Connect(function(player: Player, value: any) handle(player, value) end), Players.PlayerRemoving:Connect(forget), } -- The client script ships inside the SDK (a LocalScript there never runs); players get a copy at spawn. local template = script.Parent:FindFirstChild("DeviceClient") local starterScripts = StarterPlayer:FindFirstChild("StarterPlayerScripts") if template and starterScripts and not starterScripts:FindFirstChild(REMOTE_NAME) then local copy = template:Clone() copy.Name = REMOTE_NAME copy.Parent = starterScripts end return function() for _, connection in connections do connection:Disconnect() end table.clear(connections) end end return Device ]]>DeviceClientMapExport any)?, } local MapExport = {} local function vec(x: number, y: number, z: number): Vec -- JSON cannot carry NaN or infinity; a corrupt part would otherwise fail the whole upload. local function clean(n: number): number if n ~= n or n == math.huge or n == -math.huge then return 0 end return math.round(n * 1000) / 1000 end return { x = clean(x), y = clean(y), z = clean(z) } end local function colorHex(color: Color3): string return string.format("#%02X%02X%02X", math.round(color.R * 255), math.round(color.G * 255), math.round(color.B * 255)) end local function attributeUp(part: Instance, root: Instance, name: string): any local node: Instance? = part while node and node ~= root.Parent do local value = node:GetAttribute(name) if value ~= nil then return value end node = node.Parent end return nil end local function primitiveOf(part: BasePart): string if part:IsA("WedgePart") then return "wedge" end if part:IsA("Part") and part.Shape == Enum.PartType.Ball then return "sphere" end return "box" end local function extend(bounds: Bounds?, lo: Vec, hi: Vec): Bounds if not bounds then return { min = { x = lo.x, y = lo.y, z = lo.z }, max = { x = hi.x, y = hi.y, z = hi.z } } end local min, max = bounds.min, bounds.max min.x, min.y, min.z = math.min(min.x, lo.x), math.min(min.y, lo.y), math.min(min.z, lo.z) max.x, max.y, max.z = math.max(max.x, hi.x), math.max(max.y, hi.y), math.max(max.z, hi.z) return bounds end -- JSON for one terrain chunk. Arrays are written by hand because a Luau table cannot hold the nulls that mark cells -- with no terrain. local function terrainBody(meta: { [string]: any }, field: TerrainExport.Heightfield): string local heights = table.create(#field.heights, "null") for i, height in field.heights do if type(height) == "number" then heights[i] = string.format("%.1f", height) end end local head = HttpService:JSONEncode(meta) return string.sub(head, 1, -2) .. `,"heights":[{table.concat(heights, ",")}],"materials":{HttpService:JSONEncode(field.materials)},"cells":[{table.concat(field.cells, ",")}]}` end -- Reads the terrain around the exported objects, one map-grid chunk at a time. Yields between reads so a large map -- does not freeze Studio. local function buildTerrain( options: Options, chunkSize: number, placeId: string, overall: Bounds?, cells: { { gridX: number, gridZ: number } }, report: Report ): ({ { [string]: any } }, { [string]: string }, number) local descriptors: { { [string]: any } } = {} local bodies: { [string]: string } = {} local cellSize = options.terrainCellStuds or DEFAULT_TERRAIN_CELL local terrain = workspace:FindFirstChildOfClass("Terrain") if options.terrain == false or not terrain or not overall or #cells == 0 then return descriptors, bodies, cellSize end assert( cellSize % TerrainExport.VOXEL == 0 and chunkSize % cellSize == 0 and chunkSize // cellSize <= 128, "terrainCellStuds must be a multiple of 4 that divides chunkSizeStuds, with at most 128 cells per chunk side" ) local pad = options.terrainPadChunks or DEFAULT_TERRAIN_PAD local minX, maxX, minZ, maxZ = math.huge, -math.huge, math.huge, -math.huge for _, cell in cells do minX, maxX = math.min(minX, cell.gridX), math.max(maxX, cell.gridX) minZ, maxZ = math.min(minZ, cell.gridZ), math.max(maxZ, cell.gridZ) end minX, maxX, minZ, maxZ = minX - pad, maxX + pad, minZ - pad, maxZ + pad local count = (maxX - minX + 1) * (maxZ - minZ + 1) if count > MAX_TERRAIN_CHUNKS then report.terrainNote = `terrain skipped: the level spans {count} chunks (limit {MAX_TERRAIN_CHUNKS}); use terrainPadChunks = 0, a larger chunkSizeStuds, or terrain = false` return descriptors, bodies, cellSize end local floorY = math.floor((options.terrainMinY or (overall.min.y - TERRAIN_BELOW)) / TerrainExport.VOXEL) * TerrainExport.VOXEL local ceilY = math.ceil((options.terrainMaxY or (overall.max.y + TERRAIN_ABOVE)) / TerrainExport.VOXEL) * TerrainExport.VOXEL ceilY = math.min(ceilY, floorY + 1024) local reads = 0 for gz = minZ, maxZ do for gx = minX, maxX do local field = TerrainExport.readChunk(terrain, gx, gz, chunkSize, cellSize, floorY, ceilY) reads += 1 if reads % 4 == 0 then task.wait() end if not field then continue end local chunkId = `{gx}:{gz}` local body = terrainBody({ schemaVersion = SCHEMA, projectId = options.projectId, placeId = placeId, buildId = options.buildId, chunkId = chunkId, gridX = gx, gridZ = gz, cellSizeStuds = cellSize, size = field.size, }, field) bodies[chunkId] = body report.bytes += #body report.terrainCells += field.filled table.insert(descriptors, { chunkId = chunkId, gridX = gx, gridZ = gz, minHeight = field.minHeight, maxHeight = field.maxHeight, byteSize = #body, contentHash = Sha256.hex(body), }) end end report.terrainChunks = #descriptors return descriptors, bodies, cellSize end function MapExport.build(root: Instance, options: Options): Built assert(options.projectId ~= "" and options.buildId ~= "", "projectId and buildId are required") local chunkSize = options.chunkSizeStuds or DEFAULT_CHUNK assert(chunkSize >= MIN_CHUNK and chunkSize <= MAX_CHUNK, "chunkSizeStuds must be between 64 and 2048") local report: Report = { objects = 0, chunks = 0, skippedHidden = 0, skippedIgnored = 0, stages = 0, oversized = 0, bytes = 0, terrainChunks = 0, terrainCells = 0, } local objects: { Object } = {} local stageNames: { [string]: string } = {} local stageOrder: { string } = {} local overall: Bounds? = nil local stageBounds: { [string]: Bounds } = {} for _, inst in root:GetDescendants() do if not inst:IsA("BasePart") or inst:IsA("Terrain") then continue end local part = inst :: BasePart if part:GetAttribute("RoStructureIgnore") ~= nil then report.skippedIgnored += 1 continue end if not options.includeInvisible and part.Transparency >= HIDDEN_ABOVE then report.skippedHidden += 1 continue end if #objects >= MAX_OBJECTS then break end local size = part.Size local cf = part.CFrame local rx, ry, rz = cf:ToEulerAnglesXYZ() local stageValue = attributeUp(part, root, "StageId") local stageId = if stageValue ~= nil then tostring(stageValue) else nil if stageId and not stageNames[stageId] then local nameValue = attributeUp(part, root, "StageName") stageNames[stageId] = if nameValue ~= nil then tostring(nameValue) else stageId table.insert(stageOrder, stageId) end local tags: { string } = {} for _, tag in part:GetTags() do if #tags < 32 then table.insert(tags, tag) end end local object: Object = { id = "p" .. tostring(#objects + 1), name = string.sub(part.Name, 1, 256), primitive = primitiveOf(part), position = vec(cf.X, cf.Y, cf.Z), rotation = vec(math.deg(rx), math.deg(ry), math.deg(rz)), size = vec(math.max(size.X, 0.001), math.max(size.Y, 0.001), math.max(size.Z, 0.001)), color = colorHex(part.Color), transparency = math.clamp(part.Transparency, 0, 1), material = part.Material.Name, stageId = stageId, tags = tags, } table.insert(objects, object) -- Axis-aligned bounds of the rotated box, from its half-extent projected on each world axis. local hx = (math.abs(cf.RightVector.X) * size.X + math.abs(cf.UpVector.X) * size.Y + math.abs(cf.LookVector.X) * size.Z) / 2 local hy = (math.abs(cf.RightVector.Y) * size.X + math.abs(cf.UpVector.Y) * size.Y + math.abs(cf.LookVector.Y) * size.Z) / 2 local hz = (math.abs(cf.RightVector.Z) * size.X + math.abs(cf.UpVector.Z) * size.Y + math.abs(cf.LookVector.Z) * size.Z) / 2 local lo, hi = vec(cf.X - hx, cf.Y - hy, cf.Z - hz), vec(cf.X + hx, cf.Y + hy, cf.Z + hz) overall = extend(overall, lo, hi) if stageId then stageBounds[stageId] = extend(stageBounds[stageId], lo, hi) end if math.max(size.X, size.Z) > chunkSize then report.oversized += 1 end end local zero: Bounds = { min = vec(0, 0, 0), max = vec(0, 0, 0) } local stages = {} for _, id in stageOrder do table.insert(stages, { id = id, name = string.sub(stageNames[id], 1, 256), bounds = stageBounds[id] }) end -- Group by chunk cell: floor(position / chunkSize), the grid rule in the contract. local grouped: { [string]: { gridX: number, gridZ: number, items: { Object }, bounds: Bounds? } } = {} local order: { string } = {} for _, object in objects do local gx = math.floor(object.position.x / chunkSize) local gz = math.floor(object.position.z / chunkSize) local key = `{gx}:{gz}` local cell = grouped[key] if not cell then cell = { gridX = gx, gridZ = gz, items = {}, bounds = nil } grouped[key] = cell table.insert(order, key) end table.insert(cell.items, object) cell.bounds = extend(cell.bounds, object.position, object.position) end table.sort(order) local exportedAt = DateTime.now():ToIsoDate() local universeId = options.universeId or tostring(game.GameId) local placeId = options.placeId or tostring(game.PlaceId) local chunks: { [string]: { [string]: any } } = {} local bodies: { [string]: string } = {} local descriptors = {} for _, key in order do local cell = grouped[key] assert(#cell.items <= MAX_PER_CHUNK, `chunk {key} has {#cell.items} objects; use a smaller chunkSizeStuds`) local cellBounds: Bounds = { min = vec(cell.gridX * chunkSize, (cell.bounds :: Bounds).min.y, cell.gridZ * chunkSize), max = vec((cell.gridX + 1) * chunkSize, (cell.bounds :: Bounds).max.y, (cell.gridZ + 1) * chunkSize), } local chunk = { schemaVersion = SCHEMA, projectId = options.projectId, placeId = placeId, buildId = options.buildId, chunkId = key, gridX = cell.gridX, gridZ = cell.gridZ, bounds = cellBounds, objects = cell.items, } local body = HttpService:JSONEncode(chunk) chunks[key] = chunk bodies[key] = body report.bytes += #body table.insert(descriptors, { chunkId = key, gridX = cell.gridX, gridZ = cell.gridZ, bounds = cellBounds, objectCount = #cell.items, byteSize = #body, contentHash = Sha256.hex(body), }) end local gridCells: { { gridX: number, gridZ: number } } = {} for _, key in order do table.insert(gridCells, { gridX = grouped[key].gridX, gridZ = grouped[key].gridZ }) end local terrainDescriptors, terrainBodies, terrainCell = buildTerrain(options, chunkSize, placeId, overall, gridCells, report) report.objects = #objects report.chunks = #descriptors report.stages = #stages local hasTerrain = #terrainDescriptors > 0 local manifest: { [string]: any } = { schemaVersion = SCHEMA, format = "chunked", projectId = options.projectId, universeId = universeId, placeId = placeId, buildId = options.buildId, exportedAt = exportedAt, bounds = overall or zero, chunkSizeStuds = chunkSize, capabilities = { geometry = "primitives-v1", terrain = if hasTerrain then "heightfield-v1" else "none" }, stages = stages, chunks = descriptors, } if hasTerrain then manifest.terrain = { cellSizeStuds = terrainCell, chunks = terrainDescriptors } end return { manifest = manifest, chunks = chunks, chunkBodies = bodies, terrainBodies = terrainBodies, report = report } end -- Uploads the manifest, then each chunk. Returns ok plus a one-line summary or the first error. function MapExport.publish(config: PublishConfig, built: Built): (boolean, string) local base = string.gsub(config.endpoint, "/+$", "") local headers = { ["Content-Type"] = "application/json", ["X-Project-Id"] = config.projectId, ["X-Ingestion-Key"] = config.ingestionKey, } local send = config.request or function(options) return HttpService:RequestAsync(options) end local function put(path: string, body: string): (boolean, string) local ok, response = pcall(send, { Url = base .. path, Method = "PUT", Headers = headers, Body = body }) if not ok then return false, `request failed: {response}` end if response.StatusCode >= 200 and response.StatusCode < 300 then return true, tostring(response.StatusCode) end return false, `{path} -> {response.StatusCode} {response.Body or ""}` end local ok, detail = put("/v1/maps", HttpService:JSONEncode(built.manifest)) if not ok then return false, detail end local sent = 0 for chunkId, body in built.chunkBodies do local chunkOk, chunkDetail = put("/v1/maps/chunks", body) if not chunkOk then return false, `chunk {chunkId}: {chunkDetail}` end sent += 1 end local terrainSent = 0 for chunkId, body in built.terrainBodies do local terrainOk, terrainDetail = put("/v1/maps/terrain", body) if not terrainOk then return false, `terrain chunk {chunkId}: {terrainDetail}` end terrainSent += 1 end local r = built.report local terrainText = if terrainSent > 0 then `, {terrainSent} terrain chunks` else "" local note = if r.terrainNote then ` ({r.terrainNote})` else "" return true, `published build {built.manifest.buildId}: {r.objects} objects, {sent} chunks{terrainText}, {r.stages} stages, {r.bytes} bytes{note}` end return MapExport ]]>Revenue (number?, string?))?, getPlayer: ((userId: number) -> Player?)?, clock: (() -> number)?, spawn: ((fn: () -> ()) -> ())?, } export type Observer = { handle: (self: Observer, kind: string, userId: number, id: number) -> (), } local CACHE_SECONDS = 600 local CACHE_MAX = 200 -- The same purchase seen twice within this window (an event delivered twice) is recorded once. local DUPLICATE_SECONDS = 5 local Revenue = {} local function defaultLookup(kind: string, id: number): (number?, string?) local infoType = if kind == "gamepass" then Enum.InfoType.GamePass else Enum.InfoType.Product local ok, info = pcall(function() return MarketplaceService:GetProductInfoAsync(id, infoType) end) if not ok or type(info) ~= "table" then return nil, nil end local price = info.PriceInRobux local name = info.Name return (if type(price) == "number" then price else nil), (if type(name) == "string" then name else nil) end -- `client` only needs a trackPurchase(player, purchase) method. function Revenue.newObserver(client: any, deps: Deps?): Observer local d: Deps = deps or {} local lookup = d.lookup or defaultLookup local getPlayer = d.getPlayer or function(userId: number): Player? return Players:GetPlayerByUserId(userId) end local clock = d.clock or os.clock local spawn = d.spawn or task.spawn local cache: { [string]: { price: number?, name: string?, at: number } } = {} local cacheSize = 0 local recent: { [string]: number } = {} local function info(kind: string, id: number): (number?, string?) local key = `{kind}:{id}` local hit = cache[key] local now = clock() if hit and now - hit.at < CACHE_SECONDS then return hit.price, hit.name end local price, name = lookup(kind, id) if price == nil and hit then return hit.price, hit.name -- keep serving the last good answer if a lookup fails end if not hit then if cacheSize >= CACHE_MAX then table.clear(cache) cacheSize = 0 end cacheSize += 1 end cache[key] = { price = price, name = name, at = now } return price, name end local observer = {} :: any function observer.handle(_self: Observer, kind: string, userId: number, id: number) local now = clock() local key = `{userId}:{kind}:{id}` local last = recent[key] if last and now - last < DUPLICATE_SECONDS then return end recent[key] = now -- A lookup can yield, so it runs on its own thread; nothing here blocks or reaches the game's handlers. spawn(function() local ok = pcall(function() local price, name = info(kind, id) if price == nil then return -- free items, removed items and failed lookups carry no revenue end local player = getPlayer(userId) if player == nil then return end client:trackPurchase(player, { kind = kind, robux = price, productId = id, productName = name }) end) if not ok then -- Never raise into the game; the purchase simply is not recorded. return end end) end return observer :: Observer end -- Connects the observer to Roblox's purchase-finished events. Returns the connections so they can be disconnected. function Revenue.bind(client: any, warn: (string) -> ()): { RBXScriptConnection } local observer = Revenue.newObserver(client) local connections: { RBXScriptConnection } = {} local ok, err = pcall(function() table.insert( connections, MarketplaceService.PromptProductPurchaseFinished:Connect(function(userId: number, productId: number, isPurchased: boolean) if isPurchased then observer:handle("product", userId, productId) end end) ) table.insert( connections, MarketplaceService.PromptGamePassPurchaseFinished:Connect(function(player: Player, gamePassId: number, wasPurchased: boolean) if wasPurchased and player then observer:handle("gamepass", player.UserId, gamePassId) end end) ) end) if not ok then warn(`could not watch purchases: {err}`) end return connections end return Revenue ]]>Ring 0 and bytes + size > maxBytes then break end taken += 1 out[taken] = item bytes += size buf[head] = "" head = head % cap + 1 end r.head = head r.count -= taken return out, bytes end return Ring ]]>Sender Types.Response, warn: (string) -> (), batchSize: number, maxBatchBytes: number, flushInterval: number, maxRetries: number, baseDelay: number, maxDelay: number, minGap: number, maxInFlight: number, pauseSeconds: number, -- Gzip request bodies. Turned off for the rest of the server if the API refuses a compressed body. compress: boolean, clock: (() -> number)?, random: (() -> number)?, } type State = { o: Options, ring: Ring.Ring, clock: () -> number, random: () -> number, inFlight: number, resumeAt: number, nextSendAt: number, timerArmed: boolean, wakeArmed: boolean, deferArmed: boolean, closing: boolean, deadline: number, requests: number, sent: number, dropped: number, retries: number, compress: boolean, warned: { [string]: boolean }, } local Sender = {} Sender.__index = Sender export type Sender = typeof(setmetatable({} :: State, Sender)) local rng = Random.new() function Sender.new(o: Options): Sender local self: State = { o = o, ring = o.ring, clock = o.clock or os.clock, random = o.random or function() return rng:NextNumber() end, inFlight = 0, resumeAt = 0, nextSendAt = 0, timerArmed = false, wakeArmed = false, deferArmed = false, closing = false, deadline = math.huge, requests = 0, sent = 0, dropped = 0, retries = 0, compress = o.compress, warned = {}, } return setmetatable(self, Sender) end function Sender._warnOnce(self: Sender, key: string, message: string) if not self.warned[key] then self.warned[key] = true self.o.warn(message) end end function Sender._armTimer(self: Sender) if self.timerArmed then return end self.timerArmed = true task.delay(self.o.flushInterval, function() self.timerArmed = false self:pump(true) end) end function Sender._wakeIn(self: Sender, seconds: number) if self.wakeArmed then return end self.wakeArmed = true task.delay(seconds, function() self.wakeArmed = false self:pump(true) end) end -- Call after every enqueue. A full batch is sent on the next scheduler pass; a partial one waits for -- the flush timer, which is armed only while there is something to send. function Sender.notify(self: Sender) if self.ring.count >= self.o.batchSize then if not self.deferArmed then self.deferArmed = true task.defer(function() self.deferArmed = false self:pump(false) end) end else self:_armTimer() end end -- Starts as many requests as concurrency, rate spacing and backoff allow. `force` also sends a -- partial batch (timer, wake-up and shutdown paths). function Sender.pump(self: Sender, force: boolean) local o, ring = self.o, self.ring while ring.count > 0 and self.inFlight < o.maxInFlight do if not (force or self.closing or ring.count >= o.batchSize) then break end local now = self.clock() local readyAt = math.max(self.resumeAt, if self.closing then 0 else self.nextSendAt) if now < readyAt then self:_wakeIn(readyAt - now) return end local parts, _ = Ring.take(ring, o.batchSize, o.maxBatchBytes) self.inFlight += 1 self.nextSendAt = now + o.minGap task.spawn(self._run, self, table.concat(parts, ","), #parts) end if ring.count > 0 and self.inFlight < o.maxInFlight then self:_armTimer() end end function Sender._run(self: Sender, joined: string, count: number) local ok, err = pcall(self._deliver, self, joined, count) if not ok then self.dropped += count self:_warnOnce("internal", `internal sender error: {err}`) end self.inFlight -= 1 self:pump(false) end -- 400 for a body the API could not parse at all, as opposed to a batch it read and found invalid. local function isUnreadable(response: Types.Response): boolean return response.StatusCode == 400 and string.find(response.Body or "", '"invalid_request"', 1, true) ~= nil end function Sender._deliver(self: Sender, joined: string, count: number) local o = self.o self.requests += 1 local body = `\{"requestId":"{o.idPrefix}r{self.requests}","sdkVersion":"{o.sdkVersion}","events":[{joined}]}` local options: Types.RequestOptions = { Url = o.url, Method = "POST", Headers = o.headers, Body = body } if self.compress then options.Compress = Enum.HttpCompression.Gzip end local attempt = 0 while true do attempt += 1 local verdict: Backoff.Verdict | "resend" local retryAfter: number? = nil local ok, res = pcall(o.request, options) if not ok then verdict = if string.find(tostring(res), "not enabled", 1, true) then "pause" else "retry" if verdict == "pause" then self:_warnOnce("http", "HttpService requests are disabled; enable HttpEnabled in Game Settings") end else local response = res :: Types.Response verdict = Backoff.classify(response.StatusCode) local headers = response.Headers if headers then retryAfter = tonumber(headers["retry-after"] or headers["Retry-After"]) end if verdict == "drop" and options.Compress and (response.StatusCode == 415 or isUnreadable(response)) then -- An API that cannot read gzip sees a garbled body. Send this batch and every later one uncompressed. self.compress = false options.Compress = nil self:_warnOnce("compress", `API refused a gzip batch (HTTP {response.StatusCode}); sending uncompressed`) verdict = "resend" elseif verdict == "ok" then local reply = response.Body if reply and not string.find(reply, '"rejected"%s*:%s*%[%s*%]') then self:_warnOnce("rejected", `server rejected some events: {string.sub(reply, 1, 300)}`) end elseif verdict == "pause" then self:_warnOnce("auth", `ingestion key or project rejected (HTTP {response.StatusCode})`) elseif verdict == "drop" then self:_warnOnce("drop", `batch refused (HTTP {response.StatusCode}): {string.sub(response.Body or "", 1, 300)}`) end end if verdict == "ok" then self.sent += count return elseif verdict == "pause" then self.dropped += count self.resumeAt = self.clock() + o.pauseSeconds return elseif verdict == "drop" then self.dropped += count return elseif verdict == "resend" then attempt -= 1 continue end local delay = Backoff.delay(attempt, o.baseDelay, o.maxDelay, self.random(), retryAfter) if attempt > o.maxRetries or (self.closing and self.clock() + delay > self.deadline) then self.dropped += count self:_warnOnce("giveup", "dropped a batch after repeated delivery failures") return end self.retries += 1 -- Backoff is shared: other in-flight batches also hold off instead of piling onto a struggling API. self.resumeAt = math.max(self.resumeAt, self.clock() + delay) task.wait(delay) end end -- Sends everything queued and waits until delivered or the budget runs out. Yields. function Sender.flush(self: Sender, budgetSeconds: number) self.closing = true self.deadline = self.clock() + budgetSeconds self:pump(true) while (self.ring.count > 0 or self.inFlight > 0) and self.clock() < self.deadline do if self.ring.count > 0 and self.inFlight == 0 and self.resumeAt > self.deadline then break end task.wait(0.05) self:pump(true) end end function Sender.stats(self: Sender): Types.Stats return { queued = self.ring.count, inFlight = self.inFlight, requests = self.requests, sentEvents = self.sent, droppedEvents = self.dropped + self.ring.evicted, retries = self.retries, } end return Sender ]]>Sha256 candidate then break end if candidate % p == 0 then isPrime = false break end end if isPrime then table.insert(primes, candidate) end candidate += 1 end for i = 1, 64 do K[i] = math.floor((primes[i] ^ (1 / 3) % 1) * MOD) end for i = 1, 8 do H0[i] = math.floor((primes[i] ^ 0.5 % 1) * MOD) end end local Sha256 = {} function Sha256.hex(message: string): string local length = #message message ..= "\128" .. string.rep("\0", (55 - length) % 64) .. string.pack(">I4I4", 0, length * 8) local h = table.clone(H0) local w = table.create(64, 0) for chunk = 1, #message, 64 do for i = 0, 15 do w[i + 1] = string.unpack(">I4", message, chunk + i * 4) end for i = 17, 64 do local w15, w2 = w[i - 15], w[i - 2] local s0 = bxor(rrotate(w15, 7), rrotate(w15, 18), rshift(w15, 3)) local s1 = bxor(rrotate(w2, 17), rrotate(w2, 19), rshift(w2, 10)) w[i] = (w[i - 16] + s0 + w[i - 7] + s1) % MOD end local a, b, c, d, e, f, g, hh = h[1], h[2], h[3], h[4], h[5], h[6], h[7], h[8] for i = 1, 64 do local s1 = bxor(rrotate(e, 6), rrotate(e, 11), rrotate(e, 25)) local ch = bxor(band(e, f), band(bnot(e), g)) local t1 = (hh + s1 + ch + K[i] + w[i]) % MOD local s0 = bxor(rrotate(a, 2), rrotate(a, 13), rrotate(a, 22)) local maj = bxor(band(a, b), band(a, c), band(b, c)) local t2 = (s0 + maj) % MOD hh, g, f, e, d, c, b, a = g, f, e, (d + t1) % MOD, c, b, a, (t1 + t2) % MOD end h[1] = (h[1] + a) % MOD h[2] = (h[2] + b) % MOD h[3] = (h[3] + c) % MOD h[4] = (h[4] + d) % MOD h[5] = (h[5] + e) % MOD h[6] = (h[6] + f) % MOD h[7] = (h[7] + g) % MOD h[8] = (h[8] + hh) % MOD end return string.format("%08x%08x%08x%08x%08x%08x%08x%08x", h[1], h[2], h[3], h[4], h[5], h[6], h[7], h[8]) end return Sha256 ]]>Tags Tag Editor) and the right events are recorded with no code: StageStart attribute StageId (string) First touch records stage_started and makes it the player's stage. Checkpoint attribute StageId (string) Records checkpoint_reached once per player. KillPart attribute Cause (string) Kills on touch and remembers why, so deaths carry a cause. Deaths are recorded here, once per life, with the position and the cause (the built-in death event has no cause). Everything is server-side. Per-part connections are held weakly and per-player state is removed when the player leaves, so a long-running server does not accumulate anything. ]] local CollectionService = game:GetService("CollectionService") local Players = game:GetService("Players") local Tags = {} type Analytics = { track: (any, Player, string, any?) -> (), setStage: (any, Player, string?) -> (), } local function playerFromHit(hit: BasePart): (Player?, Model?) local model = hit:FindFirstAncestorOfClass("Model") local player = model and Players:GetPlayerFromCharacter(model) return player, model end -- Binds the three tags for a client. Returns a function that disconnects everything. function Tags.bind(analytics: Analytics): () -> () local global: { RBXScriptConnection } = {} -- Weak keys: a destroyed part drops out on its own, along with its connection. local partConnections: { [Instance]: RBXScriptConnection } = setmetatable({}, { __mode = "k" }) :: any local characterConnections: { [Player]: RBXScriptConnection } = {} local currentStage: { [Player]: string } = {} local checkpoints: { [Player]: { [Instance]: boolean } } = {} local function stageIdOf(part: Instance): string? local value = part:GetAttribute("StageId") return if type(value) == "string" and value ~= "" then value else nil end local function bindStageStart(part: Instance) local stageId = stageIdOf(part) if not part:IsA("BasePart") or not stageId then return end partConnections[part] = part.Touched:Connect(function(hit) local player = playerFromHit(hit) if not player or currentStage[player] == stageId then return end currentStage[player] = stageId analytics:setStage(player, stageId) analytics:track(player, "stage_started", { stageId = stageId, position = true }) end) end local function bindCheckpoint(part: Instance) local stageId = stageIdOf(part) if not part:IsA("BasePart") or not stageId then return end partConnections[part] = part.Touched:Connect(function(hit) local player = playerFromHit(hit) local reached = player and checkpoints[player] if not player or not reached or reached[part] then return end reached[part] = true analytics:track(player, "checkpoint_reached", { stageId = stageId, position = true }) end) end local function bindKillPart(part: Instance) if not part:IsA("BasePart") then return end local cause = part:GetAttribute("Cause") partConnections[part] = part.Touched:Connect(function(hit) local _, model = playerFromHit(hit) local humanoid = model and model:FindFirstChildOfClass("Humanoid") if humanoid and model and humanoid.Health > 0 then model:SetAttribute("LastCause", if type(cause) == "string" and cause ~= "" then cause else part.Name) humanoid.Health = 0 end end) end local function bindTagged(tag: string, bind: (Instance) -> ()) for _, instance in CollectionService:GetTagged(tag) do bind(instance) end table.insert(global, CollectionService:GetInstanceAddedSignal(tag):Connect(bind)) end bindTagged("StageStart", bindStageStart) bindTagged("Checkpoint", bindCheckpoint) bindTagged("KillPart", bindKillPart) -- One death event per life, with the position and the cause. local function onCharacter(player: Player, character: Model) local humanoid = character:WaitForChild("Humanoid", 10) if not humanoid or not humanoid:IsA("Humanoid") then return end humanoid.Died:Once(function() local cause = character:GetAttribute("LastCause") analytics:track(player, "player_died", { position = true, metadata = { cause = if type(cause) == "string" then cause else "Unknown" }, }) end) end local function onPlayerAdded(player: Player) checkpoints[player] = {} characterConnections[player] = player.CharacterAdded:Connect(function(character) onCharacter(player, character) end) if player.Character then task.spawn(onCharacter, player, player.Character) end end table.insert(global, Players.PlayerAdded:Connect(onPlayerAdded)) for _, player in Players:GetPlayers() do onPlayerAdded(player) end table.insert( global, Players.PlayerRemoving:Connect(function(player) currentStage[player] = nil checkpoints[player] = nil local connection = characterConnections[player] if connection then connection:Disconnect() characterConnections[player] = nil end end) ) return function() for _, connection in global do connection:Disconnect() end table.clear(global) for _, connection in partConnections do connection:Disconnect() end table.clear(partConnections) for _, connection in characterConnections do connection:Disconnect() end table.clear(characterConnections) end end return Tags ]]>TerrainExport= MIN_OCCUPANCY then return (y - 1) + filled, (material :: EnumItem).Name end end end return nil, nil end -- Reduces voxel arrays to a size x size heightfield. `span` is voxels per cell side (cellSize / 4). Each cell takes -- the highest surface among its columns. `floorY` is the world height of the arrays' lowest voxel. function TerrainExport.heightfield( materials: any, occupancy: any, size: number, span: number, yCount: number, floorY: number ): Heightfield local heights: { number | boolean } = table.create(size * size, false) local cells: { number } = table.create(size * size, 0) local palette: { string } = {} local paletteIndex: { [string]: number } = {} local minHeight, maxHeight = math.huge, -math.huge local filled = 0 for j = 0, size - 1 do for i = 0, size - 1 do local bestTop: number? = nil local bestMaterial: string? = nil for dz = 1, span do for dx = 1, span do local top, name = TerrainExport.columnTop(materials, occupancy, i * span + dx, j * span + dz, yCount) if top and (bestTop == nil or top > bestTop) then bestTop, bestMaterial = top, name end end end if bestTop and bestMaterial then local height = math.round((floorY + bestTop * VOXEL) * 10) / 10 local index = paletteIndex[bestMaterial] if not index then table.insert(palette, bestMaterial) index = #palette - 1 paletteIndex[bestMaterial] = index end local at = j * size + i + 1 heights[at] = height cells[at] = index filled += 1 minHeight = math.min(minHeight, height) maxHeight = math.max(maxHeight, height) end end end if filled == 0 then minHeight, maxHeight = 0, 0 end return { size = size, heights = heights, materials = palette, cells = cells, minHeight = minHeight, maxHeight = maxHeight, filled = filled, } end -- Reads one map-grid chunk of terrain. `floorY` and `ceilY` must be multiples of 4. Returns nil for an empty chunk. function TerrainExport.readChunk( terrain: Terrain, gridX: number, gridZ: number, chunkSize: number, cellSize: number, floorY: number, ceilY: number ): Heightfield? local minCorner = Vector3.new(gridX * chunkSize, floorY, gridZ * chunkSize) local maxCorner = Vector3.new(minCorner.X + chunkSize, ceilY, minCorner.Z + chunkSize) local materials, occupancy = terrain:ReadVoxels(Region3.new(minCorner, maxCorner), VOXEL) local result = TerrainExport.heightfield( materials, occupancy, chunkSize // cellSize, cellSize // VOXEL, materials.Size.Y, floorY ) if result.filled == 0 then return nil end return result end return TerrainExport ]]>Types Revenue). -- It is private to your project; RoStructure uses it only to debug and fix the service. The API discards -- revenue for projects that have not enabled it, so setting only this has no effect. revenue: boolean?, -- With revenue on, the SDK watches the purchase-finished events and records each purchase at its list price. It never -- takes over ProcessReceipt. Set false if you report exact amounts yourself with client:trackReceipt(receiptInfo). revenueAuto: boolean?, -- Per-event keep probability in [0, 1], e.g. { custom_event = 0.1 }. sampling: { [string]: number }?, -- Seconds a partial batch waits before it is sent (default 30, or 5 in Studio). A full batch of 100 is sent at once, and -- shutdown always flushes, so a longer wait only delays data, never loses it. flushInterval: number?, -- Gzip each batch (default true), which makes requests roughly 10x smaller. Set false only for an endpoint that -- cannot read gzip; the SDK also falls back on its own if the API refuses a compressed batch. compress: boolean?, batchSize: number?, maxQueue: number?, maxRetries: number?, shutdownBudget: number?, -- Replace HttpService:RequestAsync (tests, dry runs, proxies). request: ((RequestOptions) -> Response)?, debug: boolean?, } return {} ]]>Wire 0 and #s <= ID_MAX end function Wire.newContext( projectId: string, universeId: string, placeId: string, buildId: string, serverId: string, idPrefix: string ): (Context?, string?) for name, value in { projectId = projectId, universeId = universeId, placeId = placeId, buildId = buildId, serverId = serverId } do if not validId(value) then return nil, `{name} must be a non-empty string of at most {ID_MAX} characters` end end local staticJson = `"projectId":{quote(projectId)},"universeId":{quote(universeId)},` .. `"placeId":{quote(placeId)},"buildId":{quote(buildId)},"serverId":{quote(serverId)}` return { staticJson = staticJson, idPrefix = idPrefix, counter = 0 }, nil end function Wire.playerFragment(sessionId: string, playerAnonymousId: string): string return `"sessionId":{quote(sessionId)},"playerAnonymousId":{quote(playerAnonymousId)}` end local nameCache: { [string]: boolean } = {} -- snake_case, starting with a letter, at most 64 characters. Verdicts are cached per name. function Wire.isValidName(name: any): boolean if type(name) ~= "string" then return false end local cached = nameCache[name] if cached ~= nil then return cached end local ok = #name <= 64 and string.match(name, "^[a-z][a-z0-9_]*$") ~= nil nameCache[name] = ok return ok end local stageCache: { [string]: string } = {} local stageCacheSize = 0 -- Encoded stage ID, or nil when it is not a valid opaque ID. Stage sets are small, so cache them. function Wire.stageJson(stageId: any): string? if not validId(stageId) then return nil end local cached = stageCache[stageId] if cached then return cached end local json = quote(stageId) if stageCacheSize < STAGE_CACHE_MAX then stageCache[stageId] = json stageCacheSize += 1 end return json end -- Encoded metadata object, or nil plus a reason. Empty tables are omitted. function Wire.metadataJson(metadata: { [string]: any }): (string?, string?) local firstKey = next(metadata) if firstKey == nil then return nil, nil end if type(firstKey) ~= "string" then return nil, "metadata must be a dictionary with string keys" end local ok, json = pcall(HttpService.JSONEncode, HttpService, metadata) if not ok then return nil, "metadata contains values that cannot be JSON encoded" end if #json > METADATA_MAX_BYTES then return nil, `metadata exceeds {METADATA_MAX_BYTES} bytes` end return json, nil end local lastSecond = -1 local lastPrefix = "" -- UTC ISO-8601 with milliseconds. The date prefix is recomputed only when the second changes. function Wire.timestamp(unixMillis: number): string local second = unixMillis // 1000 if second ~= lastSecond then lastSecond = second lastPrefix = os.date("!%Y-%m-%dT%H:%M:%S.", second) end return string.format("%s%03dZ", lastPrefix, unixMillis - second * 1000) end -- Position components must already be finite. Numbers are rounded to 0.01 stud to cut payload size. function Wire.encode( ctx: Context, playerFragment: string, eventName: string, unixMillis: number, x: number?, y: number?, z: number?, stageJson: string?, device: string?, metadataJson: string? ): string local counter = ctx.counter + 1 ctx.counter = counter local s = `\{"eventId":"{ctx.idPrefix}{counter}",{ctx.staticJson},{playerFragment},` .. `"eventName":"{eventName}","timestamp":"{Wire.timestamp(unixMillis)}"` if x and y and z then s ..= string.format(',"position":{"x":%.2f,"y":%.2f,"z":%.2f}', x, y, z) end if stageJson then s ..= `,"stageId":{stageJson}` end if device then s ..= `,"device":"{device}"` end if metadataJson then s ..= `,"metadata":{metadataJson}` end return s .. "}" end return Wire ]]>