Forest Logo
search
package_2

unite

By @endarke

Roblox

Mirrored from Wally

Unite

A lightweight Roblox framework: server systems, client handlers, and buffer-based networking built in. No dependencies.

[dependencies]
Unite = "endarke/unite@2.0.0"

Systems and handlers

-- Server: src/Server/Systems/CombatSystem.luau
local CombatSystem = Unite.createSystem {
    name = 'CombatSystem',
    network = {
        -- Packets
        hit = Unite.createPacket(Unite.struct {
            target = Unite.inst,
            damage = Unite.uint16
        }),
        aim = Unite.createUnreliablePacket(Unite.vec3),
        ready = Unite.createPacket(),

        -- Queries
        getStats = Unite.createQuery(Unite.nothing, Unite.struct {
            level = Unite.uint8,
            title = Unite.string
        }),
    },
}

function CombatSystem:start(): ()
    -- Listeners
    self.network.ready.listen(function(_, player: Player): ()
        self.network.hit.sendTo({
            target = workspace.Dummy,
            damage = 10
        }, player)
    end)

    self.network.getStats.listen(function(_, player: Player): any
        return {
            level = 5,
            title = player.Name
        }
    end)
end

return CombatSystem
-- Client: src/Client/Handlers/CombatHandler.luau
local CombatHandler = Unite.createHandler {
    name = 'CombatHandler',
}

function CombatHandler:init(): ()
    -- Network & Queries
    self._combatNetwork = Unite.network.CombatSystem
end

function CombatHandler:start(): ()
    -- Listeners
    self._combatNetwork.hit.listen(function(data): ()
        print(data.target, data.damage)
    end)

    self._combatNetwork.ready.send()

    local stats = self._combatNetwork.getStats.invoke()
end

return CombatHandler

Boot each side once: Unite.start(script.Systems, true) / Unite.start(script.Handlers, true) (true also loads subfolders).

  • init() runs for every system first (they may yield; Unite waits), then every start() is spawned. Unite.start returns once the start()s are running, so a start() with a while true do loop is fine. Unite.awaitStart() waits for that point from anywhere.
  • A module that fails to load, or an init() that errors, is reported with its path; the rest keep loading. A system whose init() errored doesn't get start().
  • Unite.getSystem(name) / Unite.getHandler(name) work from init() onward and error (with a suggestion) for unknown names.

Players

function DataSystem:start(): ()
    Unite.playerAdded(function(player: Player): ()
        self.load(player)
    end)

    Unite.playerRemoving(function(player: Player): ()
        self.save(player)
    end)
end

Unite.playerAdded runs once for every player already in the game and every player who joins later; Unite.playerRemoving runs for every player who leaves (only ones playerAdded saw). Each callback runs in its own thread, so it can yield, and errors are reported without stopping the others. Both return a disconnect function and work on either side.

Getting a network on the client

Unite.network.CombatSystemNever yields. Works anywhere in handler modules (even at the top), because Unite.start waits for the server's networks before loading handlers.
Unite.connectSystemNetwork('CombatSystem')Waits for the network to arrive (up to networkTimeout).

On the server, Unite.network.CombatSystem returns any system's network.

Packets

ServerClientBoth
sendTo(data, player)send(data)listen(fn) → disconnect function
sendToAll(data)listenOnce(fn) → disconnect function
sendToList(data, players)wait() → data, player
sendToAllExcept(data, player or players)disconnectAll()
  • Reliable packets keep their order per player, even when sendTo and sendToAll are mixed in a frame.
  • Messages that arrive before anything listens are kept (up to 256) and delivered to the first listener.
  • Unite.createUnreliablePacket sends over an UnreliableRemoteEvent. Batches are split to stay under Roblox's 1000 byte limit; a single message that can never fit is dropped with a one-time warning.
  • Unite.createPacket() with no data type is a signal with no data.
  • Unite.createPacket(type, { rateLimit = 10 }) caps how many times a second each player can send it; extra messages are dropped and reported through onViolation. Works on queries too (createQuery(request, response, { rateLimit = 2 })).
  • Methods work with . or :.

Queries

query.listen(function(request, player) return response end) on the server; query.invoke(request) on the client. invoke raises a descriptive error if the handler errors, returns an invalid response, or nothing answers within queryTimeout.

States

A state is a value the server owns and clients mirror. Only the fields that changed are sent.

roundState = Unite.createState(Unite.struct {
    phase = RacePhase,
    round = Unite.uint16,
    leader = Unite.optional(Unite.string)
}),
ServerClient
set(value, player?) replaces the valueget() → current value (frozen) or nil
patch(changes, player?) changes some fieldsobserve(fn) → runs now with the current value, then on every change
get(player?) → what you setlisten(fn(value, previous)) on change

Without a player, the state is shared by everyone and players who join later get the current value automatically. With a player, each player has their own. Setting the same value again sends nothing. Use set to clear an optional field (a nil in a patch table is just a missing key).

Shared networks

To get types on the client, define a network in a shared module both sides require:

return Unite.defineNetwork('Chat', {
    message = Unite.createPacket(Unite.struct {
        text = Unite.string,
        channel = Unite.optional(Unite.string)
    }),
})

The server publishes it; the client checks its definition against the server's and errors with both layouts if they don't match.

Cross-server signals

local Announcement = Unite.createCrossServerSignal('announcement', Unite.struct {
    text = Unite.string
})

Announcement.listen(function(data, sender): ()
    print(data.text, sender.jobId)
end)

Announcement.send({
    text = 'Hello'
})

send reaches every other server, sendToAll every server including this one, and sendTo(data, jobId) one server.

Leave out the data type to send any JSON-friendly value. All signals share one MessagingService subscription, messages sent close together go out as one compressed publish, and a server running a different data type for the same signal ignores the message instead of misreading it. In Studio, signals only reach the current server unless crossServerInStudio is on.

Cross-server queries

local FindPlayer = Unite.createCrossServerQuery('findPlayer', Unite.float64, Unite.string)

FindPlayer.listen(function(userId: number): string?
    if not Players:GetPlayerByUserId(userId) then return end

    return Unite.getServerId()
end)

local jobId = FindPlayer.invoke(userId)
invoke(request)First answer from any server (including this one), or nil after crossServerTimeout. Handlers that return nil stay quiet.
invoke(request, jobId)Ask one server; errors if it doesn't answer.
invokeAll(request)Every answer that arrives within crossServerTimeout, as { { jobId, response } }.

Data types

bool, uint8, uint16, uint32, int8, int16, int32, float32, float64, string, buff, vec2, vec3, color3, cframe, inst, unknown, nothing, and struct { }, array(t), map(k, v), optional(t).

Strings, buffers, arrays and maps have no 65535 limit. inst and unknown travel next to the buffer (any number per frame). color3 is 1 byte per channel, clamped to 0–1.

Compact types

TypeBytesPrecision
float162about 3 significant digits, up to ±65504
vec2f16 / vec3f164 / 6same per axis; for velocities, directions, offsets
angle20.0001 radians, read back in -π to π
cframeCompact18 (vs 24)exact float32 position, rotation within 0.0002

Enums

-- ReplicatedStorage/Shared/Enums/RacePhase.luau
return Unite.enum('RacePhase', {
    'lobby',
    'countdown',
    'racing',
    'results'
})

An enum value is 1 byte (2 past 256 values) instead of a whole string. Use it as a data type (phase = RacePhase) and as a typo-safe set of names: RacePhase.racing == 'racing', while RacePhase.racng errors with a suggestion. Add a value by adding a line; since clients read the layout from the server, order changes can't desync them. Every enum is also in Unite.enums.RacePhase, including on the client, which gets the server's enums through the networks that use them. Unite.enum(Enum.Material) sends any Roblox enum in 1–3 bytes.

Configuration

Unite.configure { ... }, on either side:

OptionDefault
validateStudio onlyCheck outgoing data before sending for exact error paths (data.target.position should be a Vector3, got nil). Failed sends are always explained, even when off.
queryTimeout10Seconds a client waits for a query answer.
networkTimeout10Seconds connectSystemNetwork waits for a network.
incomingBytesPerSecond / incomingBurstBytes32768 / 65536Per-player byte limit on what the server accepts.
incomingMessagesPerSecond / incomingBurstMessages1000 / 2000Per-player message limit, so floods of tiny messages can't run listeners thousands of times.
maxPendingQueries32Queries one player can have waiting at once.
rejectNonFinitetrueServer drops client data containing NaN or infinite numbers.
exposeServerErrorsStudio onlySend query handler error text to the client.
crossServerInStudiofalseLet Studio use MessagingService.
crossServerTimeout5Seconds cross-server queries wait for answers.
statsfalseCount messages and bytes per endpoint (see below).
onViolationnonefunction(player, reason) for bad or excessive client data.

Stats

With stats on, Unite.getStats() returns { seconds, endpoints = { ['CombatSystem.hit'] = { sent, sentBytes, received, receivedBytes } } } since the last Unite.clearStats(). Bytes are the serialized size per call. When off, it costs one check per message.

What the server protects against

Clients can send anything, so the server treats every byte as hostile:

  • Wrong types, oversized lengths and truncated data are rejected before anything is allocated. The batch is dropped, the player is reported (rate-limited in the output), and the server keeps running.
  • A batch can't make the server do unbounded work: lengths are checked against the bytes that arrived, empty items are capped per batch, and both bytes and messages per second are limited per player.
  • NaN and infinite numbers are rejected (rejectNonFinite), so they can't reach parts or physics.
  • Listener and handler errors run in their own threads and are printed at most once a second per endpoint, so an exploiter can't lag the server through the output.
  • Queries are capped per player (maxPendingQueries) and endpoints can have their own rateLimit.

Kick or flag players from onViolation. Networking that can't be crashed removes the usual trigger for duplication exploits, but trades should still be safe at the data layer: save or lock both sides before granting items (session locking, as ProfileStore does).

Editor support

With Luau Language Server, the whole Unite API autocompletes and is typed, including a system's own network (CombatSystem.network.hit.sendTo(data: { damage: number, target: Instance }, player)) and self inside init/start.

Networks looked up by name on the client (Unite.network.X, connectSystemNetwork('X')), systems from getSystem, and enum values can't be typed statically. The Unite Tools VS Code extension in extension/ fills that in by reading your workspace: completions, hovers, go to definition, typo warnings and snippets.

Upgrading from 1.x

  • ByteNet-Max is no longer a dependency; the packet API (sendTo(data, player), listen, invoke, ...) is unchanged.
  • Unite.start no longer waits for start() methods to finish.
  • Unite.getSystem / getHandler error on unknown names instead of returning nil.
  • connectSystemNetwork no longer requires Unite.start to have run.

Package Details

Install command (Click to copy)


Version

2.0.0

License

MPL-2.0

warning

Usable with conditions

infoFile-level copyleft: if you modify this package's own source files, those modified files must be made available under MPL-2.0. Using it unmodified in a closed-source game is fine.

Automated license review — not legal advice.