local z={}local p={[Enum.DataStoreRequestType.GetAsync]={},[Enum.DataStoreRequestType.GetSortedAsync]={};[Enum.DataStoreRequestType.OnUpdate]={},[Enum.DataStoreRequestType.SetIncrementAsync]={};[Enum.DataStoreRequestType.SetIncrementSortedAsync]={}}local function u()for p,u in pairs(ConstantsMapping)do z[p]=u.START end z[Enum.DataStoreRequestType.UpdateAsync]=math.min(z[Enum.DataStoreRequestType.GetAsync],z[Enum.DataStoreRequestType.SetIncrementAsync])end local function P(p,u,P,U)if not Constants.BUDGETING_ENABLED then return end local d=u.RATE+U*u.RATE_PLR z[p]=math.min(z[p]+P*d,u.MAX_FACTOR*d)end local function U(p)if not Constants.BUDGETING_ENABLED then return end for p,u in pairs(p)do if z[u]then z[u]=math.max(0,z[u]-1)end end z[Enum.DataStoreRequestType.UpdateAsync]=math.min(z[Enum.DataStoreRequestType.GetAsync],z[Enum.DataStoreRequestType.SetIncrementAsync])end local function d(p)if not Constants.BUDGETING_ENABLED then return true end for p,u in pairs(p)do if z[u]and z[u]<1 then return false end end return true end local T=false if RunService:IsServer()then u()task.spawn(function()local u=tick()while task.wait(Constants.BUDGET_UPDATE_INTERVAL)do local D=tick()local B=(D-u)/60 u=D local k=#Players:GetPlayers()if not T then for z,p in pairs(ConstantsMapping)do P(z,p,B,k)end z[Enum.DataStoreRequestType.UpdateAsync]=math.min(z[Enum.DataStoreRequestType.GetAsync],z[Enum.DataStoreRequestType.SetIncrementAsync])end for z,p in pairs(p)do for z=#p,1,-1 do local u=p[z]local P=u.Thread local T=u.Budget local D=u.Key local B=u.Lock local k=u.Cache if not(B and(B[D]or tick()-(k[D]or 0)<Constants.WRITE_COOLDOWN))and d(T)then table.remove(p,z)U(T)coroutine.resume(P)end end end end end)game:BindToClose(function()for p,u in pairs(ConstantsMapping)do z[p]=math.max(z[p],Constants.BUDGET_ONCLOSE_BASE*(u.RATE/Constants.BUDGET_BASE))end z[Enum.DataStoreRequestType.UpdateAsync]=math.min(z[Enum.DataStoreRequestType.GetAsync],z[Enum.DataStoreRequestType.SetIncrementAsync])end)end function MockDataStoreManager.GetGlobalData()return Data.GlobalDataStore end function MockDataStoreManager.GetData(z,p)assert(type(z)=="\115\116\114\105\110\103")assert(type(p)=="\115\116\114\105\110\103")if not Data.DataStore[z]then Data.DataStore[z]={}end if not Data.DataStore[z][p]then Data.DataStore[z][p]={}end return Data.DataStore[z][p]end function MockDataStoreManager.GetOrderedData(z,p)assert(type(z)=="\115\116\114\105\110\103")assert(type(p)=="\115\116\114\105\110\103")if not Data.OrderedDataStore[z]then Data.OrderedDataStore[z]={}end if not Data.OrderedDataStore[z][p]then Data.OrderedDataStore[z][p]={}end return Data.OrderedDataStore[z][p]end function MockDataStoreManager.GetDataInterface(z)return Interfaces[z]end function MockDataStoreManager.SetDataInterface(z,p)assert(type(z)=="\116\097\098\108\101")assert(type(p)=="\116\097\098\108\101")Interfaces[z]=p end function MockDataStoreManager.GetBudget(p)if Constants.BUDGETING_ENABLED then return math.floor(z[p]or 0)else return math.huge end end function MockDataStoreManager.SetBudget(p,u)assert(type(u)=="\110\117\109\098\101\114")u=math.max(u,0)if p==Enum.DataStoreRequestType.UpdateAsync then z[Enum.DataStoreRequestType.SetIncrementAsync]=u z[Enum.DataStoreRequestType.GetAsync]=u end if z[p]then z[p]=u end end function MockDataStoreManager.ResetBudget()u()end function MockDataStoreManager.FreezeBudgetUpdates()T=true end function MockDataStoreManager.ThawBudgetUpdates()T=false end function MockDataStoreManager.YieldForWriteLockAndBudget(z,u,P,U,d)assert(type(z)=="\102\117\110\099\116\105\111\110")assert(type(u)=="\115\116\114\105\110\103")assert(type(P)=="\116\097\098\108\101")assert(type(U)=="\116\097\098\108\101")assert(#d>0)local T=d[1]if#p[T]>=Constants.THROTTLE_QUEUE_SIZE then return false end z()table.insert(p[T],1,{Key=u,Lock=P;Cache=U;Thread=coroutine.running();Budget=d})coroutine.yield()return true end function MockDataStoreManager.YieldForBudget(z,u)assert(type(z)=="\102\117\110\099\116\105\111\110")assert(#u>0)local P=u[1]if d(u)then U(u)elseif#p[P]>=Constants.THROTTLE_QUEUE_SIZE then return false else z()table.insert(p[P],1,{After=0,Thread=coroutine.running(),Budget=u})coroutine.yield()end return true end function MockDataStoreManager.ExportToJSON()local z={}if next(Data.GlobalDataStore)~=nil then z.GlobalDataStore=Data.GlobalDataStore end z.DataStore=Utils.prepareDataStoresForExport(Data.DataStore)z.OrderedDataStore=Utils.prepareDataStoresForExport(Data.OrderedDataStore)return HttpService:JSONEncode(z)end

local Budgets = {}

local budgetRequestQueues = {
	[Enum.DataStoreRequestType.GetAsync] = {};
	[Enum.DataStoreRequestType.GetSortedAsync] = {};
	[Enum.DataStoreRequestType.OnUpdate] = {};
	[Enum.DataStoreRequestType.SetIncrementAsync] = {};
	[Enum.DataStoreRequestType.SetIncrementSortedAsync] = {};
}

local function initBudget()
	for requestType, const in pairs(ConstantsMapping) do
		Budgets[requestType] = const.START
	end
	Budgets[Enum.DataStoreRequestType.UpdateAsync] = math.min(
		Budgets[Enum.DataStoreRequestType.GetAsync],
		Budgets[Enum.DataStoreRequestType.SetIncrementAsync]
	)
end

local function updateBudget(req, const, dt, n)
	if not Constants.BUDGETING_ENABLED then
		return
	end
	local rate = const.RATE + n * const.RATE_PLR
	Budgets[req] = math.min(
		Budgets[req] + dt * rate,
		const.MAX_FACTOR * rate
	)
end

local function stealBudget(budget)
	if not Constants.BUDGETING_ENABLED then
		return
	end
	for _, requestType in pairs(budget) do
		if Budgets[requestType] then
			Budgets[requestType] = math.max(0, Budgets[requestType] - 1)
		end
	end
	Budgets[Enum.DataStoreRequestType.UpdateAsync] = math.min(
		Budgets[Enum.DataStoreRequestType.GetAsync],
		Budgets[Enum.DataStoreRequestType.SetIncrementAsync]
	)
end

local function checkBudget(budget)
	if not Constants.BUDGETING_ENABLED then
		return true
	end
	for _, requestType in pairs(budget) do
		if Budgets[requestType] and Budgets[requestType] < 1 then
			return false
		end
	end
	return true
end

local isFrozen = false

if RunService:IsServer() then
	-- Only do budget/throttle updating on server (in case package required on client)

	initBudget()

	task.spawn(function() -- Thread that increases budgets and de-throttles requests periodically
		local lastCheck = tick()
		while task.wait(Constants.BUDGET_UPDATE_INTERVAL) do
			local now = tick()
			local dt = (now - lastCheck) / 60
			lastCheck = now
			local n = #Players:GetPlayers()

			if not isFrozen then
				for requestType, const in pairs(ConstantsMapping) do
					updateBudget(requestType, const, dt, n)
				end
				Budgets[Enum.DataStoreRequestType.UpdateAsync] = math.min(
					Budgets[Enum.DataStoreRequestType.GetAsync],
					Budgets[Enum.DataStoreRequestType.SetIncrementAsync]
				)
			end

			for _, budgetRequestQueue in pairs(budgetRequestQueues) do
				for i = #budgetRequestQueue, 1, -1 do
					local request = budgetRequestQueue[i]

					local thread = request.Thread
					local budget = request.Budget
					local key = request.Key
					local lock = request.Lock
					local cache = request.Cache

					if not (lock and (lock[key] or tick() - (cache[key] or 0) < Constants.WRITE_COOLDOWN)) and checkBudget(budget) then
						table.remove(budgetRequestQueue, i)
						stealBudget(budget)
						coroutine.resume(thread)
					end
				end
			end
		end
	end)

	game:BindToClose(function()
		for requestType, const in pairs(ConstantsMapping) do
			Budgets[requestType] = math.max(
				Budgets[requestType],
				Constants.BUDGET_ONCLOSE_BASE * (const.RATE / Constants.BUDGET_BASE)
			)
		end
		Budgets[Enum.DataStoreRequestType.UpdateAsync] = math.min(
			Budgets[Enum.DataStoreRequestType.GetAsync],
			Budgets[Enum.DataStoreRequestType.SetIncrementAsync]
		)
	end)

end

function MockDataStoreManager.GetGlobalData()
	return Data.GlobalDataStore
end

function MockDataStoreManager.GetData(name, scope)
	assert(type(name) == "string")
	assert(type(scope) == "string")

	if not Data.DataStore[name] then
		Data.DataStore[name] = {}
	end
	if not Data.DataStore[name][scope] then
		Data.DataStore[name][scope] = {}
	end

	return Data.DataStore[name][scope]
end

function MockDataStoreManager.GetOrderedData(name, scope)
	assert(type(name) == "string")
	assert(type(scope) == "string")

	if not Data.OrderedDataStore[name] then
		Data.OrderedDataStore[name] = {}
	end
	if not Data.OrderedDataStore[name][scope] then
		Data.OrderedDataStore[name][scope] = {}
	end

	return Data.OrderedDataStore[name][scope]
end

function MockDataStoreManager.GetDataInterface(data)
	return Interfaces[data]
end

function MockDataStoreManager.SetDataInterface(data, interface)
	assert(type(data) == "table")
	assert(type(interface) == "table")

	Interfaces[data] = interface
end

function MockDataStoreManager.GetBudget(requestType)
	if Constants.BUDGETING_ENABLED then
		return math.floor(Budgets[requestType] or 0)
	else
		return math.huge
	end
end

function MockDataStoreManager.SetBudget(requestType, budget)
	assert(type(budget) == "number")
	budget = math.max(budget, 0)

	if requestType == Enum.DataStoreRequestType.UpdateAsync then
		Budgets[Enum.DataStoreRequestType.SetIncrementAsync] = budget
		Budgets[Enum.DataStoreRequestType.GetAsync] = budget
	end

	if Budgets[requestType] then
		Budgets[requestType] = budget
	end
end

function MockDataStoreManager.ResetBudget()
	initBudget()
end

function MockDataStoreManager.FreezeBudgetUpdates()
	isFrozen = true
end

function MockDataStoreManager.ThawBudgetUpdates()
	isFrozen = false
end

function MockDataStoreManager.YieldForWriteLockAndBudget(callback, key, writeLock, writeCache, budget)
	assert(type(callback) == "function")
	assert(type(key) == "string")
	assert(type(writeLock) == "table")
	assert(type(writeCache) == "table")
	assert(#budget > 0)

	local mainRequestType = budget[1]

	if #budgetRequestQueues[mainRequestType] >= Constants.THROTTLE_QUEUE_SIZE then
		return false -- no room in throttle queue
	end

	callback() -- would i.e. trigger a warning in output

	table.insert(budgetRequestQueues[mainRequestType], 1, {
		Key = key;
		Lock = writeLock;
		Cache = writeCache;
		Thread = coroutine.running();
		Budget = budget;
	})
	coroutine.yield()

	return true
end

function MockDataStoreManager.YieldForBudget(callback, budget)
	assert(type(callback) == "function")
	assert(#budget > 0)

	local mainRequestType = budget[1]

	if checkBudget(budget) then
		stealBudget(budget)
	elseif #budgetRequestQueues[mainRequestType] >= Constants.THROTTLE_QUEUE_SIZE then
		return false -- no room in throttle queue
	else
		callback() -- would i.e. trigger a warning in output

		table.insert(budgetRequestQueues[mainRequestType], 1, {
			After = 0; -- no write lock
			Thread = coroutine.running();
			Budget = budget;
		})
		coroutine.yield()
	end

	return true
end

function MockDataStoreManager.ExportToJSON()
	local export = {}

	if next(Data.GlobalDataStore) ~= nil then -- GlobalDataStore not empty
		export.GlobalDataStore = Data.GlobalDataStore
	end
	export.DataStore = Utils.prepareDataStoresForExport(Data.DataStore) -- can be nil
	export.OrderedDataStore = Utils.prepareDataStoresForExport(Data.OrderedDataStore) -- can be nil

	return HttpService:JSONEncode(export)
end
