Repository navigation
Expand file tree
/
Copy pathserver.lua
More file actions
395 lines (342 loc) · 11 KB
/
Copy pathserver.lua
File metadata and controls
395 lines (342 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
local runService = game:GetService('RunService')
local players = game:GetService('Players')
local network = game.ReplicatedStorage.Network
local modules = network.Modules
local codec = require(modules.Codec)
local bufferWriter = require(modules.Writer)
local bufferReader = require(modules.Reader)
local signalModule = require(modules.Signal)
local net = {}
local registeredEvents = {}
local idByName = {}
local nameById = {}
local nextEventId = 1
local nextRequestId = 1
local pendingRequests = {}
local reliableQueueByPlayer = {}
local unreliableQueueByPlayer = {}
local unsyncedIdsByPlayer = {}
local rateLimitState = {}
local statsSent = { bytes = 0, messages = 0 }
local statsReceived = { bytes = 0, messages = 0 }
local kindEvent = 0
local kindRequest = 1
local kindResponse = 2
local reliableFlushThreshold = 24
local unreliableFlushThreshold = 32
local maxQueuedPerPlayer = 512
local masterRemote = network.__Master
local masterUnreliableRemote = network.__MasterUnreliable
local function initializePlayerState(player)
reliableQueueByPlayer[player] = {}
unreliableQueueByPlayer[player] = {}
local pending = {}
for eventId in pairs(nameById) do
table.insert(pending, eventId)
end
unsyncedIdsByPlayer[player] = pending
end
for _, player in ipairs(players:GetPlayers()) do
initializePlayerState(player)
end
players.PlayerAdded:Connect(initializePlayerState)
players.PlayerRemoving:Connect(function(player)
reliableQueueByPlayer[player] = nil
unreliableQueueByPlayer[player] = nil
unsyncedIdsByPlayer[player] = nil
end)
local function getOrCreateEventId(eventName)
local eventId = idByName[eventName]
if eventId then
return eventId
end
eventId = nextEventId
nextEventId += 1
idByName[eventName] = eventId
nameById[eventId] = eventName
for _, player in ipairs(players:GetPlayers()) do
if unsyncedIdsByPlayer[player] then
table.insert(unsyncedIdsByPlayer[player], eventId)
end
end
return eventId
end
local function writeMessageWithId(writer, message)
writer:writeUInt8(message.kind)
if message.kind == kindResponse then
writer:writeVarUInt(message.requestId)
writer:writeUInt8(message.success and 1 or 0)
writer:writeBuffer(message.payload)
elseif message.kind == kindRequest then
writer:writeVarUInt(message.id)
writer:writeVarUInt(message.requestId)
writer:writeBuffer(message.payload)
else
writer:writeVarUInt(message.id)
writer:writeBuffer(message.payload)
end
end
local function flushPlayerReliable(player)
local queue = reliableQueueByPlayer[player]
local pendingIds = unsyncedIdsByPlayer[player]
if not queue or not pendingIds then
return
end
if #queue == 0 and #pendingIds == 0 then
return
end
local writer = bufferWriter.new()
writer:writeVarUInt(#pendingIds)
for _, eventId in ipairs(pendingIds) do
writer:writeVarUInt(eventId)
writer:writeString(nameById[eventId])
end
table.clear(pendingIds)
writer:writeVarUInt(#queue)
for _, message in ipairs(queue) do
writeMessageWithId(writer, message)
end
statsSent.messages += #queue
table.clear(queue)
local outgoingBuffer = writer:toBuffer()
statsSent.bytes += buffer.len(outgoingBuffer)
masterRemote:FireClient(player, outgoingBuffer)
end
local function flushPlayerUnreliable(player)
local queue = unreliableQueueByPlayer[player]
if not queue or #queue == 0 then
return
end
local writer = bufferWriter.new()
writer:writeVarUInt(#queue)
for _, message in ipairs(queue) do
writeMessageWithId(writer, message)
end
statsSent.messages += #queue
table.clear(queue)
local outgoingBuffer = writer:toBuffer()
statsSent.bytes += buffer.len(outgoingBuffer)
masterUnreliableRemote:FireClient(player, outgoingBuffer)
end
local function queueReliable(player, message)
local queue = reliableQueueByPlayer[player]
if not queue then
initializePlayerState(player)
queue = reliableQueueByPlayer[player]
end
if #queue >= maxQueuedPerPlayer then
warn('network reliable queue overflow for ' .. player.Name .. ', forcing flush')
flushPlayerReliable(player)
end
table.insert(queue, message)
if #queue >= reliableFlushThreshold then
flushPlayerReliable(player)
end
end
local function queueUnreliable(player, message)
local queue = unreliableQueueByPlayer[player]
if not queue then
initializePlayerState(player)
queue = unreliableQueueByPlayer[player]
end
if #queue >= maxQueuedPerPlayer then
warn('network unreliable queue overflow for ' .. player.Name .. ', dropping oldest')
table.remove(queue, 1)
end
table.insert(queue, message)
if #queue >= unreliableFlushThreshold then
flushPlayerUnreliable(player)
end
end
local function queueForPlayer(player, eventId, payload, unreliable)
local message = { kind = kindEvent, id = eventId, payload = payload }
if unreliable then
queueUnreliable(player, message)
else
queueReliable(player, message)
end
end
local function queueForAll(eventId, payload, unreliable)
for _, player in ipairs(players:GetPlayers()) do
queueForPlayer(player, eventId, payload, unreliable)
end
end
local function queueForExcept(excludedPlayer, eventId, payload, unreliable)
for _, player in ipairs(players:GetPlayers()) do
if player ~= excludedPlayer then
queueForPlayer(player, eventId, payload, unreliable)
end
end
end
local function queueForList(players, eventId, payload, unreliable)
for _, player in ipairs(players) do
queueForPlayer(player, eventId, payload, unreliable)
end
end
runService.Heartbeat:Connect(function()
for _, player in ipairs(players:GetPlayers()) do
flushPlayerReliable(player)
flushPlayerUnreliable(player)
end
end)
local function checkRateLimit(eventName, player, maxPerSecond)
if not maxPerSecond then
return true
end
local perEvent = rateLimitState[eventName]
if not perEvent then
perEvent = {}
rateLimitState[eventName] = perEvent
end
local state = perEvent[player]
local now = os.clock()
if not state or now - state.windowStart >= 1 then
state = { count = 0, windowStart = now, violations = state and state.violations or 0 }
perEvent[player] = state
end
state.count += 1
if state.count > maxPerSecond then
state.violations += 1
if state.violations >= 10 then
warn('network rate limit repeatedly exceeded by ' .. player.Name .. ' on "' .. eventName .. '"')
end
return false
end
return true
end
local function processIncoming(player, packedBuffer)
local reader = bufferReader.new(packedBuffer)
statsReceived.bytes += buffer.len(packedBuffer)
local messageCount = reader:readVarUInt()
statsReceived.messages += messageCount
for _ = 1, messageCount do
local kind = reader:readUInt8()
if kind == kindEvent then
local eventId = reader:readVarUInt()
local payload = reader:readBuffer()
local eventName = nameById[eventId]
local eventObject = eventName and registeredEvents[eventName]
if eventObject and eventObject.onServerFire then
if checkRateLimit(eventName, player, eventObject.rateLimit) then
local unpackedPayload = codec.unpack(payload)
eventObject.onServerFire:fire(player, table.unpack(unpackedPayload))
end
end
elseif kind == kindRequest then
local eventId = reader:readVarUInt()
local requestId = reader:readVarUInt()
local payload = reader:readBuffer()
local eventName = nameById[eventId]
local eventObject = eventName and registeredEvents[eventName]
if eventObject and eventObject.onServerInvoke then
task.spawn(function()
local success, result = pcall(eventObject.onServerInvoke, player, codec.unpack(payload))
queueReliable(player, {
kind = kindResponse,
requestId = requestId,
success = success,
payload = codec.pack(result),
})
end)
end
elseif kind == kindResponse then
local requestId = reader:readVarUInt()
local success = reader:readUInt8() == 1
local payload = reader:readBuffer()
local thread = pendingRequests[requestId]
if thread then
pendingRequests[requestId] = nil
task.spawn(thread, success, codec.unpack(payload))
end
end
end
end
export type ServerEventApi = {
FireClient: (self: ServerEventApi, player: Player, data: any) -> (),
FireAll: (self: ServerEventApi, data: any) -> (),
FireExcept: (self: ServerEventApi, excludedPlayer: Player, data: any) -> (),
FireList: (self: ServerEventApi, players: { Player }, data: any) -> (),
Connect: (self: ServerEventApi, callback: (Player, any) -> ()) -> any,
Once: (self: ServerEventApi, callback: (Player, any) -> ()) -> any,
}
function net.loadEvent(eventName: string, options: { unreliable: boolean?, rateLimit: number? }?): ServerEventApi
if registeredEvents[eventName] then
return registeredEvents[eventName]
end
local eventId = getOrCreateEventId(eventName)
local unreliable = options and options.unreliable or false
local rateLimit = options and options.rateLimit or 5
local eventApi = {} :: any
eventApi.onServerFire = signalModule.new()
eventApi.rateLimit = rateLimit
function eventApi:FireClient(player, ...)
local args = {...}
queueForPlayer(player, eventId, codec.pack(args), unreliable)
end
function eventApi:FireAll(...)
local args = {...}
queueForAll(eventId, codec.pack(args), unreliable)
end
function eventApi:FireExcept(excludedPlayer, ...)
local args = {...}
queueForExcept(excludedPlayer, eventId, codec.pack(args), unreliable)
end
function eventApi:FireList(players, ...)
local args = {...}
queueForList(players, eventId, codec.pack(args), unreliable)
end
function eventApi:Connect(callback)
return eventApi.onServerFire:connect(callback)
end
function eventApi:Once(callback)
return eventApi.onServerFire:once(callback)
end
registeredEvents[eventName] = eventApi
return eventApi
end
export type ServerFunctionApi = {
OnInvoke: (self: ServerFunctionApi, callback: (Player, any) -> any) -> (),
InvokeClient: (self: ServerFunctionApi, player: Player, data: any) -> (boolean, any),
}
function net.loadFunction(eventName: string): ServerFunctionApi
if registeredEvents[eventName] then
return registeredEvents[eventName]
end
local eventId = getOrCreateEventId(eventName)
local eventApi = {} :: any
function eventApi:OnInvoke(callback)
eventApi.onServerInvoke = callback
end
function eventApi:InvokeClient(player, ...)
local args = {...}
local timeoutSeconds = 5
local requestId = nextRequestId
nextRequestId += 1
local thread = coroutine.running()
pendingRequests[requestId] = thread
queueReliable(player, { kind = kindRequest, id = eventId, requestId = requestId, payload = codec.pack(args) })
flushPlayerReliable(player)
local timeoutHandle = task.delay(timeoutSeconds, function()
if pendingRequests[requestId] then
pendingRequests[requestId] = nil
task.spawn(thread, false, 'timeout')
end
end)
local success, result = coroutine.yield()
task.cancel(timeoutHandle)
return success, result
end
registeredEvents[eventName] = eventApi
return eventApi
end
function net.getStats()
return {
sentBytes = statsSent.bytes,
sentMessages = statsSent.messages,
receivedBytes = statsReceived.bytes,
receivedMessages = statsReceived.messages,
}
end
masterRemote.OnServerEvent:Connect(processIncoming)
masterUnreliableRemote.OnServerEvent:Connect(processIncoming)
return net