Ravensight

The ravensight folder for LÖVE games

Pure Lua for LÖVE 11.x and 12.x on Windows, macOS and Linux. It owns the device id, sessions, batching, retries and the offline queue, and it sends requests from a background thread, so a slow network never costs a frame. There are no native files to bundle, sign or notarize.

Code samples scroll horizontally when needed. Focus a sample and use the arrow keys, or swipe to read a long line.

Install

Copy the ravensight folder from ravensight-love into your game, next to main.lua. It can live in a subfolder too (lib/ravensight); require it by that path. The same files are published here: init.lua, core.lua, config.lua, errors.lua, hmac.lua, json.lua, reports.lua, transport.lua, typed.lua, web.lua and worker.lua, the love.js bridge ravensight-love-bridge.js (only for a web build, it goes on the page, not in the game), the README and the MIT license.

my-game/
  main.lua
  conf.lua
  ravensight/
    init.lua
    core.lua
    config.lua
    errors.lua
    hmac.lua
    json.lua
    reports.lua
    transport.lua
    typed.lua
    web.lua
    worker.lua

Set an identity in conf.lua, so the SDK has a save folder for its device id:

function love.conf(t)
  t.identity = "my-game"
end

Use

local ravensight = require("ravensight")

function love.load()
  ravensight.init({
    apiUrl = "https://api.ravensight.io",
    ingestKey = "gt_live_...",   -- from your game's page in the dashboard
    gameVersion = "1.0.0",
  })
end

function love.update(dt)
  ravensight.update(dt)
end

function love.quit()
  return ravensight.quit()
end

-- anywhere in your game
ravensight.track("level_start", { level = "forest_1" })
ravensight.track("level_complete", { level = "forest_1", seconds = 74, deaths = 2 })

game_started is sent for you on launch and game_exited on quit. ravensight.quit() returns true the first time, which tells LÖVE to wait while the last events are sent; the SDK quits again by itself once they are answered, or after 1.5 seconds. If your game already has a love.quit, return its answer from your own handler, or pass handleQuit = false so the SDK never delays a quit.

function love.quit()
  if not saveGame() then return true end
  return ravensight.quit()
end

Options

Pass these to ravensight.init(options).

OptionDefaultNotes
ingestKeyrequiredYour game's publishable gt_live_ key. Safe to ship in a build.
apiUrlhttps://api.ravensight.ioWith or without /api/v1.
gameVersion1.0.0Sent with every session.
enabledtruefalse sends and queues nothing for this run, and is not saved. The player's opt out is setTrackingEnabled.
maxQueueSize500Unsent events kept. The oldest are dropped first.
flushInterval2Seconds an event waits so it can go out with others. 50 waiting events go at once.
handleQuittrueHold the quit up to 1.5 seconds to send the last events.
transportautomatic"https", "winhttp", "libcurl" or "curl" to try first, or "web" for the love.js bridge (chosen for you in a web build).
timeout15Seconds per request.
debugfalsePrint informational messages too. Warnings always print.
performancefalseSample the frame rate once a second and send one health event per session, on quit. Call update(dt) every frame. See typed events.

Functions

FunctionWhat it does
track(name, data)Queue an event. data is a flat table of strings, numbers and booleans. Safe before the session is ready.
purchase(amount, currency, itemType, itemId, opts)A typed purchase. amount is whole minor units and the currency is upper-cased. opts takes cart, transactionId, props and name.
resource(flow, resource, amount, opts)A resource entering ("source") or leaving ("sink") the economy. opts takes itemType and itemId.
progression(status, p1, opts)A progression step: "start", "complete" or "fail". opts takes p2, p3 and score.
error(severity, message, opts)An error or warning, with an optional opts.stack. The message is cut to 200 characters and the stack to 2000.
trackAd(network, format, result, opts)An ad typed event. Returns true, or false and the reason when a field is malformed (nothing is sent).
trackAdRevenue(network, format, placement, revenueMicros, currency, opts)A paid impression (result shown).
microsFromDecimalString(text), microsFromRevenue(number)Revenue in micros as a digit string, without multiplying a float.
setAttribution(attribution)Where this install was acquired, sent once per install.
getDeliveryStats()Desktop: events let go of since launch, dropped_overflow, dropped_too_old and dropped_refused.
flush()Send what is queued now. It cuts a backoff wait short, never a server Retry-After.
submitFeedback(message, category, rating)Send player feedback. category and rating (1 to 5) are optional. Needs an open session.
setTrackingEnabled(enabled)The player's opt-out, remembered across launches. false drops the queue and sends nothing, not even the startup check.
isTrackingEnabled()false when the player opted out or tracking is switched off for your game.
resetDeviceId()Start a fresh analytics identity for this install.
getDeviceId()This install's random id.
getTransport()How requests are sent here, or nil if nothing works.
on(event, fn)Listen for an SDK event. Returns a function that stops listening.
update(dt)Call every frame. Delivers answers and runs retries.
quit()Return it from love.quit.

Events

EventArgumentsWhen
session_readynoneA session is open.
session_failedreasonOpening a session failed. It is retried for you.
tracking_disabledsource"server" when tracking is switched off for your game, "player" after an opt-out.
events_flushedcountA batch was accepted.
flush_failedreasonA batch failed. It is retried for you. "event_too_large": one event's data was over 8,192 bytes as JSON and the event was dropped, not retried.
feedback_submittednoneFeedback was accepted.
feedback_failedreasonFeedback failed, including "no_session" when sent too early.
event_trackedname, dataEvery queued event, with the data actually queued.
ravensight.on("tracking_disabled", function(source)
  print("analytics off:", source)
end)

How requests are sent

LÖVE 11 has no built-in HTTPS, and the API only accepts HTTPS, so the SDK uses the first of these that works. Nothing native is bundled.

  1. require("https"): built into LÖVE 12, or the lua-https library if you added it to an 11.x game.
  2. WinHTTP on Windows, the HTTP library every Windows version ships, called through LuaJIT's FFI.
  3. libcurl on macOS and Linux, the system's own copy, through the FFI.
  4. The curl command on macOS and Linux, if libcurl would not load.

If none of them works, the SDK prints one warning, keeps events queued, saves them when the game quits and tries again next launch. getTransport() tells you which one is in use. The libcurl and curl paths have been run against the live API on macOS. The WinHTTP path and Linux are written but not yet verified in a shipped build.

Delivery

On the desktop; a love.js build delivers through the page's JavaScript SDK.

  • Batches of 50. Up to 50 events per request.
  • Saved queue. Unsent events are written to ravensight/queue-<16 hex>.json in the save folder, one file per ingest key, whenever the queue changes, through a temporary file renamed over the old one. At most 500 events are kept, oldest dropped first, and events older than 89 days are dropped when it is read. An event leaves the file only after a 2xx answer, or a 400 that refuses it. The 0.5 ravensight_queue.json is read once and removed.
  • Device backups. On macOS the SDK excludes the file from Time Machine itself. On Android and iOS the game does it; the README says how.
  • Origin. Each session's events are saved with that session's origin, so a later launch sends them under the session, build and platform they happened in. Timestamps are unix milliseconds.
  • Errors behind gameplay. Gameplay events, a game's own error() included, go before captured errors. A capture evicts only the oldest capture, never a gameplay event, and an error's rs_trail is never written to the file.
  • Compression and signing. A request body of 1,024 bytes or more is sent gzip compressed; a 415 is sent once more uncompressed. When the session answer has signing (public keys), every batch carries X-Ravensight-Timestamp and an HMAC-SHA256 X-Ravensight-Signature, computed in hmac.lua. The secret stays in memory.
  • Backoff. A failed request is retried after 10 seconds, doubling up to 5 minutes, each wait multiplied by a random factor from 0.5 up to 1. A 429, or a 503 with Retry-After, waits exactly the server's time. A batch 401 opens a new session once, then waits for the backoff.
  • Refusals. A 400 naming one event by index drops that event and resends the rest. Only batch_too_large and 413 halve the batch. Any other 400 drops the request's events. An event whose data is over 8,192 bytes as JSON is dropped before it is queued.
  • Refused key and kill switch. Either stops the SDK for the rest of the run; the queued events stay on disk for the next launch. Turning tracking off as the player, or resetDeviceId(), deletes the saved queue.

Privacy and the opt-out

The SDK generates a random device id per install: 32 hex characters, a dash and the OS name, from the operating system's random source on first launch, saved in your game's save folder. It is not derived from hardware or an account, and resetDeviceId() replaces it. Each event carries a timestamp, your game version and the OS. There is no advertising identifier, and no field for names, emails or accounts, so a game using it needs no tracking permission prompt. The row by row store answers are in what your privacy label can say.

Ravensight ships no consent screen. If your game shows one, wire it to setTrackingEnabled(false), which is saved and holds across launches, and resetDeviceId().

Public builds

For a demo, a web build or an open-source game, ship a public key with ravensight-love 0.3.0 or later. Without a key, init is inert: it writes no files, makes no requests, and ravensight.enabled() returns false; pass optional = true to silence its one warning. With consent = "opt_in" nothing happens, no device id, no queue and no settings call, until the player turns analytics on with setTrackingEnabled(true), and that choice is saved. The distribution option is sent on the session, and every event carries an rs_event_id so a resend is never stored twice. A 401 or 403 on the settings check or the session stops the run instead of retrying a revoked key. On the web, installRavensightBridge(null, Module) installs a sink for a page with no key: the game's tagged lines are swallowed and the game never knows, and the bridge's opt-in check defaults to off when storage is missing or blocked.

Keep the key out of your repository. A tracked example file with placeholders sits beside an untracked config file that your ignore list excludes; your release job writes the real config from a CI secret when it builds a release. A clone or a fork has only the example, so its builds run with analytics off.

-- analytics.config.example.lua (tracked)
return {
  ingestKey = "",               -- written by the release job, never committed
  distribution = "native-dev",
}

-- main.lua: analytics.config.lua is untracked, and absent in a clone
local file = "analytics.config.lua"
local config = love.filesystem.getInfo(file) and love.filesystem.load(file)() or {}
ravensight.init({
  ingestKey = config.ingestKey ~= "" and config.ingestKey or nil,
  distribution = config.distribution or "native-dev",
  optional = true,
  consent = "opt_in",
  gameVersion = "1.0.0",
})

Shipping to the web

A love.js build cannot make requests from Lua, so the page does the sending. Load the JavaScript SDK (0.4.0 or newer; 0.5.1 or newer for the bridge to report experiment exposure, and 0.7.0 for millisecond timestamps) on the page and install web/ravensight-love-bridge.js from the repository before Love(Module) runs. The Lua SDK notices the web build by itself and hands every track, submitFeedback, setTrackingEnabled and flush to the page, whose SDK owns the session, the device id and the two lifecycle events. The snippet and the details are in the README's shipping to the web section.

Not supported yet

Android and iOS are not supported yet. Ravensight Playtest plays a love.js build like any web build, in the cloud or locally with --build-dir (see Which builds play where); a desktop build driven through the experimental desktop adapter (with an automation server you run yourself) or a custom bridge reads the RAVENSIGHT_PLAYTEST_TOKEN and RAVENSIGHT_PLAYTEST_RUN_ID variables, so its persona sessions are tagged synthetic.

Where each SDK finds a playtest run: Godot, LÖVE, Unity (desktop), Unreal, C++ and Odin read RAVENSIGHT_PLAYTEST_TOKEN and RAVENSIGHT_PLAYTEST_RUN_ID; iOS reads them from the launch environment; Android reads the intent extras ravensight_playtest_token and ravensight_playtest_run_id; the JavaScript SDK reads the page global __RAVENSIGHT_PLAYTEST__. The table below has the other sources each one accepts.

How the SDKs compare

JavaScript SDK 0.7.0, LÖVE 0.7.0, Godot 0.5.0, Unity 0.5.0, Unreal 0.5.0, C++ 0.5.0, Odin 0.6.0, iOS 0.6.0 and Android 0.5.0, side by side on the behaviour that most often differs. A cell that says not yet is a feature that SDK does not have. Unity, Unreal, C++, Odin, iOS and Android are Beta: see where the SDKs run for what has been verified.

BehaviourJavaScriptLÖVEGodotUnityUnrealC++OdiniOSAndroid
Automatic eventsgame_started and game_exited in a browser only, option autoEventsgame_started and game_exitedgame_started and game_exitedgame_started and game_exited; pause events only with Track Pause Eventsgame_started and game_exited; pause events only with Track Pause Eventsgame_started and game_exitedgame_started and game_exitedgame_started and game_exited; pause events only with trackPauseEventsgame_started and game_exited; pause events only with trackPauseEvents
Mobile backgroundNot applicableNot applicable, desktop only30 minute rule on Android and iOS (session_timeout)30 minute rule on iOS and Android30 minute rule on iOS and AndroidNot yet: call flush() from your own background handlerNot applicable, desktop only30 minute rule (sessionTimeout)30 minute rule (sessionTimeoutMs)
apiUrl formWith or without /api/v1With or without /api/v1api_url with or without /api/v1Api Url with or without /api/v1Api Url with or without /api/v1api_url with or without /api/v1api_url with or without /api/v1apiUrl with or without /api/v1apiUrl with or without /api/v1
Queue cap defaultmaxQueueSize 500maxQueueSize 500max_queue_size 500Max Queue Size 500Max Queue Size 500max_queue_size 500max_queue_size 500maxQueueSize 500maxQueueSize 500
Option that turns sending offenabledenabledenabledEnabled On StartEnabledenabledstart_disabledenabledenabled
Player opt outsetEnabled(false)setTrackingEnabled(false)set_tracking_enabled(false)SetTrackingEnabled(false)SetTrackingEnabled(false)set_tracking_enabled(false)set_tracking_enabled(client, false)setTrackingEnabled(false)setTrackingEnabled(context, false)
Opt-out savedNo: keep it in your own settingsYes, in the save folderYes, in user://Yes, in PlayerPrefsYes, in GameUserSettings.iniYes, in a state fileYes, in a JSON fileYes, in UserDefaultsYes, in SharedPreferences
Reset callresetDeviceId()resetDeviceId()reset_device_id()ResetDeviceId()ResetDeviceId()reset_device_id()reset_device_id(client)resetDeviceId()resetDeviceId()
BatchingOn a timer, every 15 seconds by default (autoFlushMs), or at 50 queued2 seconds after the first waiting event (flushInterval), or at 50 queued5 seconds after the first waiting event (flush_interval), or at 50 queuedEvery 15 seconds (Auto Flush Seconds), or at 50 queuedEvery 5 seconds (Flush Interval Seconds), or at 50 queuedEvery 5 seconds (flush_interval_seconds), or at 50 queuedAt least every 5 seconds (flush_interval_ms), or at 50 queuedEvery 5 seconds (flushInterval), or at 50 queuedEvery 5 seconds (flushIntervalMs), or at 50 queued
Startup reasonreason in the result of init()Not yetget_status_reason(), signal status_changedRavensight.StatusReason, event StatusChangedGetStatusReason(), delegate OnStatusChangedclient.status(), callback on_statusinit_reason(client), callback on_reason_changedRavensight.statusReason, callback Ravensight.shared?.onStatusChangeRavensight.statusReason, listener onStatusChanged
Playtest token sourcePage global __RAVENSIGHT_PLAYTEST__, then localStorage ravensight.playtestRAVENSIGHT_PLAYTEST_* variables, command line arguments, or setPlaytestContextset_playtest_context, RAVENSIGHT_PLAYTEST_* variables, or command line argumentsSetPlaytestContext, then on desktop RAVENSIGHT_PLAYTEST_* variables or command line argumentsSetPlaytestContext, RAVENSIGHT_PLAYTEST_* variables, or command line arguments on desktopConfig fields, RAVENSIGHT_PLAYTEST_* variables, then command line arguments through apply_playtest_argsConfig fields, RAVENSIGHT_PLAYTEST_* variables, then command line argumentsConfiguration fields, then the launch environmentConfig or setPlaytestContext, intent extras (debuggable builds, or with a manifest opt-in), then environment variables
Session tokenrs.sessionTokenNot yetsession_tokenRavensight.SessionTokenGetSessionToken()client.session_token()session_token(client)Ravensight.sessionTokenRavensight.sessionToken
WebNativeThrough the ravensight-js bridgeNative, on the web export, without game_exitedWebGL, not yet verified in a browserNo web target in UE5Not applicableNot applicableNot applicableNot applicable
Typed event helpersYes: trackPurchase, trackResource, trackProgression, trackErrorYes: purchase, resource, progression, errorYes: track_purchase, track_resource, track_progression, track_errorYes: TrackPurchase, TrackResource, TrackProgression, TrackErrorYes: TrackPurchase, TrackResource, TrackProgression, TrackErrorYes: track_purchase, track_resource, track_progression, track_errorYes: track_purchase, track_resource, track_progression, track_errorYes: trackPurchase, trackResource, trackProgression, trackErrorYes: trackPurchase, trackResource, trackProgression, trackError
Performance samplingYes: option performance, one health event when the page is hidden; browser onlyYes: option performance with update(dt), one health event on quitYes: option performance, one health event on background, page hide or quitYes: Performance field, one health event on background (iOS, Android) or quit (desktop)Yes: Performance setting, one health event on background (iOS, Android) or quitYes: Config::performance with sample_frame(dt), one health event on shutdownYes: Config.performance with tick(client, dt), one health event from shutdown; no memory figureYes: performance, one health event when the app enters the backgroundYes: performance, one health event when the app first goes to the background