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

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

	initBudget()

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

			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]
			)

			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.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
