EZProfilestore - Server-owned profile data with automatic client replication

Github Wally Roblox Docs

EZProfileStore

A typed ProfileStore wrapper. The server edits player data as plain Luau; only the changes replicate to the client.

Installation

[dependencies]
EZProfileStore = "breezy1214/ezprofilestore@0.1.5"

Requires Luau’s new type solver (luau-lsp: luau-lsp.fflags.enableNewSolver).

Data

Share one template between server and client:

-- ReplicatedStorage/PlayerData.luau
export type Data = {
	Coins: number,
	Inventory: { string },
	Stats: { Wins: number, Losses: number },
}

local template: Data = {
	Coins = 0,
	Inventory = {},
	Stats = { Wins = 0, Losses = 0 },
}

return { template = template }

Server

local store = EZProfileStore.Server.new({
	storeName = "PlayerData_v1",
	template = PlayerData.template,
	mode = "studio", -- mock data in Studio, live data elsewhere
})

store:Update(player, function(data)
	if data.Coins < 25 then
		return false -- abort, nothing changes
	end
	data.Coins -= 25
	table.insert(data.Inventory, "Potion")
end)

local data = store:Get(player) -- read-only; change data with Update

Update commits all-or-nothing. It returns false if the function errors, yields, returns false, or writes a value DataStores can’t save. Use for k, v in data (not pairs) inside it, and don’t keep data after it returns.

Trades across players:

store:UpdateMany({ buyer, seller }, function(drafts)
	if drafts[buyer].Coins < price then
		return false
	end
	drafts[buyer].Coins -= price
	drafts[seller].Coins += price
end)

Client

local client = EZProfileStore.Client.new({ template = PlayerData.template })

local wins = client:Select(function(data)
	return data.Stats.Wins
end)

wins:Get() -- number?
wins:Observe(function(new, old) end) -- returns a disconnect function
wins.State -- Fusion state, e.g. use(wins.State)
wins:Destroy()

Config

local config: EZProfileStore.ServerConfig<PlayerData.Data> = {
	storeName = "PlayerData_v1",
	template = PlayerData.template,

	leaderstats = {
		{ name = "Coins", type = "IntValue", value = function(data) return data.Coins end },
		{ name = "Games", type = "IntValue", value = function(data) return data.Stats.Wins + data.Stats.Losses end },
	},

	privatePaths = { -- never sent to the client
		function(data) return data.Inventory end,
	},

	validate = function(data) -- checked on load and before every Update commits
		return data.Coins >= 0, "Coins must not be negative"
	end,
}

local store = EZProfileStore.Server.new(config)

Annotating the config as ServerConfig<Data> gives the functions inside it full type checking.

Other options: keyPrefix, mode ("live", "studio", "mock"), migrations, migrateNewProfiles, remoteParent, autoLoadPlayers, store, profileStore.

Migrations

migrations = EZProfileStore.Migrations.new({
	{
		name = "move-coins",
		up = function(data)
			data.Currency = { Coins = data.Coins or 0 }
			data.Coins = nil
		end,
	},
}),

Append a migration whenever the stored shape changes. Only versions newer than the profile’s run, before Reconcile. New profiles skip them unless migrateNewProfiles = true. A failing migration restores the data and fires ProfileLoadFailed.

Testing

local store = EZProfileStore.Server.mock({
	storeName = "Test",
	template = template,
	autoLoadPlayers = false,
})

To fake the backend, pass store = fakeStore or profileStore = fakeModule.

API

Server

Member Description
Server.new(config) / Server.mock(config) Create a store.
Get(player) / GetAsync(player, timeout?) Read-only data.
Update(player, fn) / UpdateMany(players, fn) Edit data, all-or-nothing.
Changed, FirstJoin, ProfileLoaded, ProfileReleased, ProfileLoadFailed Signals.
PreSave, PostSave, LastSave, Migrated, RolledBack Signals.
GetProfile(player) / GetProfileAsync(player, timeout?) The ProfileStore profile.
IsReady(player), SaveAsync(player), GetKey(target), GetStore() Utilities.
SendMessageAsync(target, message) / OnMessage(handler) Offline messages.
PreviewRollbackAsync(target, selector?) / ApplyRollbackAsync(preview) / RollbackAsync(target, selector?) Restore an older save. The selector is { stepsBack }, { before }, or { version }.
WipeAsync(target) Delete a profile.
Destroy() End sessions and disconnect.

Client

Member Description
Client.new(config?) Connect and request the snapshot.
Ready, IsReady(), OnReady(fn) Load state.
Get() / GetAsync(timeout?) Read-only data.
Select(selector) A Selection with Get, Observe, State, and Destroy.
Destroy() Disconnect.

Exported types: Server<Data>, Client<Data>, Selection<V>, ReadOnly<T>, ServerConfig<Data>, ClientConfig<Data>, Profile<Data>, LeaderstatEntry<Data>.

Why use this versuses the many other wrappers such as Scribe?

I think the fundamental difference is architectural. Scribe aims to be a complete player-data framework, which is great if you want typed accessors, monetization, leaderboards, gifting and ton of other things are handled for you under one roof. The problem is (well depending on who you ask), you also have to buy into much larger abstraction even if you only need a small part of the library. Where Scribe is clearly ahead is typing which i will improve in an update

EZProfileStore is more narrow and focused, letting ProfileStore be the center with added safety, mutations, transactions, auto-replication clients and state management for ui without tying you to a monolithic solution. You can still get to the lower level profile if you need to and have other systems (inventories, monetization, leaderboards, progression, etc) be separate entities not coupled to your persistence layer.

So if someone wants an all-in-one framework, Scribe makes sense. EZProfileStore is more for developers who want the convenience and safety improvements around ProfileStore without the extra framework bloat (depending on you ask it actually is better or just bloat) or lock-in.

1 Like

Update

0.1.5

EZProfileStore is now fully typed, and data is written through one API. On the server, Update hands you a typed draft of the player’s data; edit it as plain Luau and only what changed replicates. On the client, Select reads a typed value and notifies you when it changes. Typing requires Luau’s new type solver.

Breaking

  • The string-path methods are replaced by Update and UpdateMany. Removed: UpdateData, InsertData, IncrementData, DecrementData, RemoveData, UpdateArrayItem, RemoveArrayItem, BatchSetValues, ReadData, Mutate, and MutateMany.
  • GetData / GetDataAsync are renamed Get / GetAsync on both server and client. The data they return is typed read-only.
  • DataUpdated is replaced by Changed(player, data), which fires once per committed Update.
  • Client Read, WatchPath, OnChanged, Updated, and GetDataState are replaced by Select(selector).
  • leaderstats entries take a value selector instead of path.
  • privatePaths takes selectors (function(data) return data.Receipts end) instead of string paths.
  • useMockInStudio is removed. Use mode = "studio".
  • Migrations receive RawData ({ [unknown]: unknown }) instead of { [any]: any }.
  • The PathWatcher dependency is removed. The array opcodes (aupd, arm) are no longer sent.

Added

  • Server:Update(player, transform): edit a draft, commit all-or-nothing. Return false to abort. Only touched sections are copied, and the commit sends the minimal set, delete, and append operations.
  • Server:UpdateMany(players, transform): atomic updates across players, such as trades.
  • Client:Select(selector): a Selection with Get(), Observe(callback), a Fusion State, and Destroy(). Selectors can derive values.
  • Client data is deep-frozen, so selections of unchanged tables don’t re-notify.
  • Derived leaderstats, e.g. value = function(data) return data.Stats.Wins + data.Stats.Losses end.
  • Server<Data> and Client<Data> types inferred from the template. The package exports Server, Client, Selection, ReadOnly, ServerConfig, Profile, and related types.
  • Client.new({ template = template }) to type the client mirror.
  • autoLoadPlayers config option. Set it to false in unit tests so stores don’t start sessions for players in the game.

Fixed

  • A StartSessionAsync that throws now fires ProfileLoadFailed and kicks the player instead of leaving them waiting for data forever.
  • A malformed entry in a replicated batch is skipped instead of aborting the whole batch.
  • Leaderstats skip values of the wrong type instead of erroring.

Migrating from 0.1.4

store:IncrementData(player, "Stats.Wins")                          -- before
store:BatchSetValues(player, { { path = "Coins", value = 0 } })

store:Update(player, function(data)                                 -- after
	data.Stats.Wins += 1
	data.Coins = 0
end)

client:OnChanged("Stats.Wins", function(new) 
    print(new) 
end)        -- before

client:Select(function(data) return data.Stats.Wins end)            -- after
	:Observe(function(new) print(new) 
end)