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

	coroutine.wrap(function() -- Thread that increases budgets and de-throttles requests periodically
		local lastCheck = tick()
		while Utils.accurateWait(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
