@dcl/sdk 7.30.1 → 7.30.2-37807847179.commit-24c42ea
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/atom.d.ts +19 -0
- package/atom.js +83 -0
- package/future.d.ts +8 -0
- package/future.js +26 -0
- package/internal/transports/rendererTransport.js +5 -2
- package/network/binary-message-bus.d.ts +6 -3
- package/network/binary-message-bus.js +9 -5
- package/network/chunking.d.ts +5 -0
- package/network/chunking.js +38 -0
- package/network/events/implementation.d.ts +93 -0
- package/network/events/implementation.js +221 -0
- package/network/events/index.d.ts +42 -0
- package/network/events/index.js +43 -0
- package/network/events/protocol.d.ts +27 -0
- package/network/events/protocol.js +66 -0
- package/network/events/registry.d.ts +8 -0
- package/network/events/registry.js +3 -0
- package/network/index.d.ts +8 -2
- package/network/index.js +16 -3
- package/network/message-bus-sync.d.ts +16 -3
- package/network/message-bus-sync.js +164 -103
- package/network/server/index.d.ts +14 -0
- package/network/server/index.js +256 -0
- package/network/server/utils.d.ts +18 -0
- package/network/server/utils.js +135 -0
- package/network/state.js +3 -5
- package/package.json +6 -6
- package/server/env-var.d.ts +15 -0
- package/server/env-var.js +31 -0
- package/server/index.d.ts +2 -0
- package/server/index.js +3 -0
- package/server/storage/constants.d.ts +80 -0
- package/server/storage/constants.js +19 -0
- package/server/storage/error-message.d.ts +1 -0
- package/server/storage/error-message.js +9 -0
- package/server/storage/index.d.ts +54 -0
- package/server/storage/index.js +60 -0
- package/server/storage/player.d.ts +60 -0
- package/server/storage/player.js +244 -0
- package/server/storage/scene.d.ts +55 -0
- package/server/storage/scene.js +232 -0
- package/server/storage/serialize.d.ts +1 -0
- package/server/storage/serialize.js +135 -0
- package/server/storage/value-cache.d.ts +1 -0
- package/server/storage/value-cache.js +67 -0
- package/server/storage/write-queue.d.ts +1 -0
- package/server/storage/write-queue.js +113 -0
- package/server/storage-url.d.ts +13 -0
- package/server/storage-url.js +42 -0
- package/server/utils.d.ts +35 -0
- package/server/utils.js +69 -0
- package/src/atom.ts +98 -0
- package/src/future.ts +38 -0
- package/src/internal/transports/rendererTransport.ts +4 -1
- package/src/network/binary-message-bus.ts +9 -4
- package/src/network/chunking.ts +45 -0
- package/src/network/events/implementation.ts +271 -0
- package/src/network/events/index.ts +48 -0
- package/src/network/events/protocol.ts +94 -0
- package/src/network/events/registry.ts +18 -0
- package/src/network/index.ts +40 -3
- package/src/network/message-bus-sync.ts +180 -112
- package/src/network/server/index.ts +341 -0
- package/src/network/server/utils.ts +189 -0
- package/src/network/state.ts +3 -4
- package/src/server/env-var.ts +36 -0
- package/src/server/index.ts +12 -0
- package/src/server/storage/constants.ts +112 -0
- package/src/server/storage/error-message.ts +8 -0
- package/src/server/storage/index.ts +83 -0
- package/src/server/storage/player.ts +345 -0
- package/src/server/storage/scene.ts +324 -0
- package/src/server/storage/serialize.ts +132 -0
- package/src/server/storage/value-cache.ts +119 -0
- package/src/server/storage/write-queue.ts +174 -0
- package/src/server/storage-url.ts +49 -0
- package/src/server/utils.ts +83 -0
package/src/network/index.ts
CHANGED
|
@@ -2,9 +2,46 @@ import { sendBinary } from '~system/CommunicationsController'
|
|
|
2
2
|
import { engine } from '@dcl/ecs'
|
|
3
3
|
import { addSyncTransport } from './message-bus-sync'
|
|
4
4
|
import { getUserData } from '~system/UserIdentity'
|
|
5
|
+
import { isServer as isServerApi } from '~system/EngineApi'
|
|
6
|
+
import { Atom } from '../atom'
|
|
7
|
+
|
|
8
|
+
// Create isServer atom for consistent state
|
|
9
|
+
const isServerAtom = Atom<boolean>(false)
|
|
10
|
+
void isServerApi({}).then((response) => {
|
|
11
|
+
isServerAtom.swap(!!response.isServer)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
// Helper function to check if running on server
|
|
15
|
+
export function isServer(): boolean {
|
|
16
|
+
return isServerAtom.getOrNull() ?? false
|
|
17
|
+
}
|
|
5
18
|
|
|
6
19
|
// initialize sync transport for sdk engine
|
|
7
|
-
const {
|
|
8
|
-
|
|
20
|
+
const {
|
|
21
|
+
getChildren,
|
|
22
|
+
syncEntity,
|
|
23
|
+
parentEntity,
|
|
24
|
+
getParent,
|
|
25
|
+
myProfile,
|
|
26
|
+
removeParent,
|
|
27
|
+
getFirstChild,
|
|
28
|
+
isStateSyncronized,
|
|
29
|
+
binaryMessageBus,
|
|
30
|
+
eventBus
|
|
31
|
+
} = addSyncTransport(engine, sendBinary, getUserData, isServerApi, 'network')
|
|
32
|
+
|
|
33
|
+
// Re-export the room messaging system
|
|
34
|
+
export { registerMessages, getRoom } from './events'
|
|
9
35
|
|
|
10
|
-
export {
|
|
36
|
+
export {
|
|
37
|
+
getFirstChild,
|
|
38
|
+
getChildren,
|
|
39
|
+
syncEntity,
|
|
40
|
+
parentEntity,
|
|
41
|
+
getParent,
|
|
42
|
+
myProfile,
|
|
43
|
+
removeParent,
|
|
44
|
+
isStateSyncronized,
|
|
45
|
+
binaryMessageBus,
|
|
46
|
+
eventBus
|
|
47
|
+
}
|
|
@@ -1,27 +1,53 @@
|
|
|
1
|
-
import { IEngine, Transport, RealmInfo
|
|
2
|
-
import {
|
|
1
|
+
import { IEngine, Transport, RealmInfo } from '@dcl/ecs'
|
|
2
|
+
import type { SendBinaryRequest, SendBinaryResponse } from '~system/CommunicationsController'
|
|
3
3
|
|
|
4
4
|
import { syncFilter } from './filter'
|
|
5
5
|
import { engineToCrdt } from './state'
|
|
6
|
-
import { BinaryMessageBus, CommsMessage
|
|
6
|
+
import { BinaryMessageBus, CommsMessage } from './binary-message-bus'
|
|
7
7
|
import { fetchProfile } from './utils'
|
|
8
8
|
import { entityUtils } from './entities'
|
|
9
|
-
import {
|
|
9
|
+
import { createServerValidator } from './server'
|
|
10
|
+
import type { GetUserDataRequest, GetUserDataResponse } from '~system/UserIdentity'
|
|
10
11
|
import { definePlayerHelper } from '../players'
|
|
11
12
|
import { serializeCrdtMessages } from '../internal/transports/logger'
|
|
13
|
+
import { IsServerRequest, IsServerResponse } from '~system/EngineApi'
|
|
14
|
+
import { Atom } from '../atom'
|
|
15
|
+
import { setGlobalRoom, Room } from './events/implementation'
|
|
12
16
|
|
|
13
17
|
export type IProfile = { networkId: number; userId: string }
|
|
14
18
|
// user that we asked for the inital crdt state
|
|
19
|
+
export const AUTH_SERVER_PEER_ID = 'authoritative-server'
|
|
20
|
+
export const DEBUG_NETWORK_MESSAGES = () => (globalThis as any).DEBUG_NETWORK_MESSAGES ?? false
|
|
21
|
+
|
|
22
|
+
// Test environment detection without 'as any'
|
|
23
|
+
const isTestEnvironment = (): boolean => {
|
|
24
|
+
try {
|
|
25
|
+
if (typeof globalThis === 'undefined') return false
|
|
26
|
+
const globalWithProcess = globalThis as unknown as { process?: { env?: { NODE_ENV?: string } } }
|
|
27
|
+
return globalWithProcess.process?.env?.NODE_ENV === 'test'
|
|
28
|
+
} catch {
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
15
33
|
export function addSyncTransport(
|
|
16
34
|
engine: IEngine,
|
|
17
35
|
sendBinary: (msg: SendBinaryRequest) => Promise<SendBinaryResponse>,
|
|
18
|
-
getUserData: (value: GetUserDataRequest) => Promise<GetUserDataResponse
|
|
36
|
+
getUserData: (value: GetUserDataRequest) => Promise<GetUserDataResponse>,
|
|
37
|
+
isServerFn: (request: IsServerRequest) => Promise<IsServerResponse>,
|
|
38
|
+
name: string
|
|
19
39
|
) {
|
|
20
|
-
const DEBUG_NETWORK_MESSAGES = () => (globalThis as any).DEBUG_NETWORK_MESSAGES ?? false
|
|
21
40
|
// Profile Info
|
|
22
41
|
const myProfile: IProfile = {} as IProfile
|
|
23
42
|
fetchProfile(myProfile!, getUserData)
|
|
24
43
|
|
|
44
|
+
const isServerAtom = Atom<boolean>()
|
|
45
|
+
const isRoomReadyAtom = Atom<boolean>(false)
|
|
46
|
+
|
|
47
|
+
void isServerFn({}).then(($: IsServerResponse) => {
|
|
48
|
+
return isServerAtom.swap(!!$.isServer)
|
|
49
|
+
})
|
|
50
|
+
|
|
25
51
|
// Entity utils
|
|
26
52
|
const entityDefinitions = entityUtils(engine, myProfile)
|
|
27
53
|
|
|
@@ -40,108 +66,194 @@ export function addSyncTransport(
|
|
|
40
66
|
const players = definePlayerHelper(engine)
|
|
41
67
|
|
|
42
68
|
let stateIsSyncronized = false
|
|
43
|
-
let transportInitialzed = false
|
|
44
69
|
|
|
70
|
+
/**
|
|
71
|
+
* We need to wait till 2 ticks that is when the engine is ready to send new messages.
|
|
72
|
+
* The first tick is for the client engine processing the CRDT messages,
|
|
73
|
+
* and the second one are the messages created by the main() function.
|
|
74
|
+
* So to avoid sending those messages, that all the clients have, through the network we put this validation here.
|
|
75
|
+
*/
|
|
76
|
+
let tick = 0
|
|
77
|
+
const TRANSPORT_INITIALIZED_NUMBER = isTestEnvironment() ? 0 : 2
|
|
45
78
|
// Add Sync Transport
|
|
46
79
|
const transport: Transport = {
|
|
47
80
|
filter: syncFilter(engine),
|
|
48
81
|
send: async (messages) => {
|
|
49
|
-
|
|
50
|
-
|
|
82
|
+
if (tick <= TRANSPORT_INITIALIZED_NUMBER) tick++
|
|
83
|
+
for (const message of tick > TRANSPORT_INITIALIZED_NUMBER ? [messages].flat() : []) {
|
|
84
|
+
if (message.byteLength) {
|
|
51
85
|
DEBUG_NETWORK_MESSAGES() &&
|
|
52
86
|
console.log(...Array.from(serializeCrdtMessages('[NetworkMessage sent]:', message, engine)))
|
|
53
|
-
|
|
87
|
+
|
|
88
|
+
// Convert regular messages to network messages for broadcasting with chunking
|
|
89
|
+
for (const chunk of serverValidator.convertRegularToNetworkMessage(message)) {
|
|
90
|
+
binaryMessageBus.emit(CommsMessage.CRDT, chunk)
|
|
91
|
+
}
|
|
54
92
|
}
|
|
55
93
|
}
|
|
56
94
|
const peerMessages = getMessagesToSend()
|
|
57
|
-
let totalSize = 0
|
|
58
|
-
for (const message of peerMessages) {
|
|
59
|
-
for (const data of message.data) {
|
|
60
|
-
totalSize += data.byteLength
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
if (totalSize) {
|
|
64
|
-
DEBUG_NETWORK_MESSAGES() && console.log('Sending network messages: ', totalSize / 1024, 'KB')
|
|
65
|
-
}
|
|
66
95
|
const response = await sendBinary({ data: [], peerData: peerMessages })
|
|
67
96
|
binaryMessageBus.__processMessages(response.data)
|
|
68
|
-
transportInitialzed = true
|
|
69
97
|
},
|
|
70
|
-
type:
|
|
98
|
+
type: name
|
|
71
99
|
}
|
|
100
|
+
|
|
101
|
+
// Server validation setup
|
|
102
|
+
const serverValidator = createServerValidator({
|
|
103
|
+
engine,
|
|
104
|
+
binaryMessageBus
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
// Initialize Event Bus with registered schemas
|
|
108
|
+
const eventBus = new Room(engine, binaryMessageBus, isServerAtom, isRoomReadyAtom)
|
|
109
|
+
|
|
110
|
+
// Set global eventBus instance
|
|
111
|
+
setGlobalRoom(eventBus)
|
|
112
|
+
|
|
72
113
|
engine.addTransport(transport)
|
|
73
114
|
// End add sync transport
|
|
74
115
|
|
|
75
116
|
// Receive & Process CRDT_STATE
|
|
76
|
-
binaryMessageBus.on(CommsMessage.
|
|
77
|
-
|
|
78
|
-
if (
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
117
|
+
binaryMessageBus.on(CommsMessage.REQ_CRDT_STATE, async (data, sender) => {
|
|
118
|
+
// Requests arriving before role resolution are recovered by the requester's retry.
|
|
119
|
+
if (!isServerAtom.getOrNull()) return
|
|
120
|
+
|
|
121
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[REQ_CRDT_STATE]', sender, Date.now())
|
|
122
|
+
const chunks = engineToCrdt(engine)
|
|
123
|
+
if (chunks.length === 0) {
|
|
124
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[Emiting empty state:]', sender, Date.now())
|
|
125
|
+
binaryMessageBus.emit(CommsMessage.RES_CRDT_STATE, new Uint8Array(), [sender])
|
|
126
|
+
} else {
|
|
127
|
+
for (const chunk of chunks) {
|
|
128
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[Emiting:]', sender, Date.now())
|
|
129
|
+
binaryMessageBus.emit(CommsMessage.RES_CRDT_STATE, chunk, [sender])
|
|
130
|
+
}
|
|
131
|
+
}
|
|
82
132
|
})
|
|
133
|
+
binaryMessageBus.on(CommsMessage.RES_CRDT_STATE, async (data, sender) => {
|
|
134
|
+
if (isServerAtom.getOrNull() || sender !== AUTH_SERVER_PEER_ID) return
|
|
83
135
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
DEBUG_NETWORK_MESSAGES() && console.log(
|
|
136
|
+
requestingState = false
|
|
137
|
+
elapsedTimeSinceRequest = 0
|
|
138
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[Processing CRDT State]', data.byteLength / 1024, 'KB')
|
|
139
|
+
if (data.byteLength > 0) {
|
|
140
|
+
transport.onmessage!(serverValidator.processClientMessages(data, sender))
|
|
141
|
+
}
|
|
142
|
+
stateIsSyncronized = true
|
|
87
143
|
|
|
88
|
-
|
|
89
|
-
|
|
144
|
+
// IMPORTANT: Only mark room as ready AFTER state is synchronized
|
|
145
|
+
// This ensures comms is truly connected and working
|
|
146
|
+
const realmInfo = RealmInfo.getOrNull(engine.RootEntity)
|
|
147
|
+
if (realmInfo) {
|
|
148
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[isRoomReady] Marking room as ready after state sync')
|
|
149
|
+
isRoomReadyAtom.swap(true)
|
|
90
150
|
}
|
|
91
151
|
})
|
|
92
152
|
|
|
93
|
-
//
|
|
94
|
-
binaryMessageBus.on(CommsMessage.CRDT, (value) => {
|
|
153
|
+
// received message from the network
|
|
154
|
+
binaryMessageBus.on(CommsMessage.CRDT, (value, sender) => {
|
|
155
|
+
const isServer = isServerAtom.getOrNull()
|
|
95
156
|
DEBUG_NETWORK_MESSAGES() &&
|
|
96
|
-
console.log(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
return
|
|
157
|
+
console.log(
|
|
158
|
+
transport.type,
|
|
159
|
+
...Array.from(serializeCrdtMessages('[NetworkMessage received]:', value, engine)),
|
|
160
|
+
isServer
|
|
161
|
+
)
|
|
162
|
+
if (isServer) {
|
|
163
|
+
transport.onmessage!(serverValidator.processServerMessages(value, sender))
|
|
164
|
+
} else if (sender === AUTH_SERVER_PEER_ID) {
|
|
165
|
+
// Process network messages from server and convert to regular messages
|
|
166
|
+
transport.onmessage!(serverValidator.processClientMessages(value, sender))
|
|
107
167
|
}
|
|
168
|
+
})
|
|
108
169
|
|
|
109
|
-
|
|
170
|
+
// received authoritative message from server - force apply to fix invalid local state
|
|
171
|
+
binaryMessageBus.on(CommsMessage.CRDT_AUTHORITATIVE, (value, sender) => {
|
|
172
|
+
// Only accept authoritative messages from authoritative server
|
|
173
|
+
if (sender !== AUTH_SERVER_PEER_ID) return
|
|
110
174
|
|
|
111
|
-
//
|
|
112
|
-
|
|
175
|
+
// DEBUG_NETWORK_MESSAGES() &&
|
|
176
|
+
console.log('[AUTHORITATIVE] Received authoritative message from server:', value.byteLength, 'bytes')
|
|
113
177
|
|
|
114
|
-
|
|
178
|
+
// Process authoritative messages by forcing them through normal CRDT processing
|
|
179
|
+
// but with a timestamp that's guaranteed to be accepted
|
|
180
|
+
const authoritativeBuffer = serverValidator.processClientMessages(value, sender, true)
|
|
181
|
+
if (authoritativeBuffer.byteLength > 0) {
|
|
182
|
+
// Apply authoritative message through normal transport, but the server's messages
|
|
183
|
+
// should be processed as authoritative with special timestamp handling
|
|
184
|
+
transport.onmessage!(authoritativeBuffer)
|
|
115
185
|
|
|
116
|
-
|
|
117
|
-
if (players.length > 1 && retryCount <= 2) {
|
|
118
|
-
DEBUG_NETWORK_MESSAGES() &&
|
|
119
|
-
console.log(`Requesting state again ${retryCount} (no response). Players connected: ${players.length - 1}`)
|
|
120
|
-
void requestState(retryCount + 1)
|
|
121
|
-
} else {
|
|
122
|
-
DEBUG_NETWORK_MESSAGES() && console.log('No active players. State syncronized')
|
|
123
|
-
stateIsSyncronized = true
|
|
124
|
-
}
|
|
186
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[AUTHORITATIVE] Applied server authoritative message to local state')
|
|
125
187
|
}
|
|
126
|
-
}
|
|
188
|
+
})
|
|
127
189
|
|
|
128
190
|
players.onEnterScene((player) => {
|
|
129
191
|
DEBUG_NETWORK_MESSAGES() && console.log('[onEnterScene]', player.userId)
|
|
192
|
+
if (!isServerAtom.getOrNull() && myProfile.userId === player.userId) {
|
|
193
|
+
requestState()
|
|
194
|
+
}
|
|
130
195
|
})
|
|
131
196
|
|
|
132
197
|
// Asks for the REQ_CRDT_STATE when its connected to comms
|
|
133
198
|
RealmInfo.onChange(engine.RootEntity, (value) => {
|
|
199
|
+
const isServer = isServerAtom.getOrNull()
|
|
200
|
+
|
|
134
201
|
if (!value?.isConnectedSceneRoom) {
|
|
135
|
-
|
|
136
|
-
|
|
202
|
+
// Only react when actually transitioning from ready to not ready
|
|
203
|
+
if (isRoomReadyAtom.getOrNull() === true) {
|
|
204
|
+
DEBUG_NETWORK_MESSAGES() && console.log('Disconnected from comms')
|
|
205
|
+
isRoomReadyAtom.swap(false)
|
|
206
|
+
if (!isServer) {
|
|
207
|
+
stateIsSyncronized = false
|
|
208
|
+
}
|
|
209
|
+
}
|
|
137
210
|
}
|
|
138
211
|
|
|
139
212
|
if (value?.isConnectedSceneRoom) {
|
|
140
|
-
|
|
213
|
+
requestState()
|
|
214
|
+
|
|
215
|
+
// For servers, mark as ready immediately when connected
|
|
216
|
+
// (servers don't need to sync state from anyone)
|
|
217
|
+
if (isServer && isRoomReadyAtom.getOrNull() === false) {
|
|
218
|
+
DEBUG_NETWORK_MESSAGES() && console.log('[isRoomReady] Server marking room as ready')
|
|
219
|
+
isRoomReadyAtom.swap(true)
|
|
220
|
+
}
|
|
221
|
+
// For clients, room will be marked ready after receiving CRDT state (above)
|
|
141
222
|
}
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
let requestingState = false
|
|
226
|
+
let elapsedTimeSinceRequest = 0
|
|
227
|
+
const STATE_REQUEST_RETRY_INTERVAL = 2.0 // seconds
|
|
142
228
|
|
|
143
|
-
|
|
144
|
-
|
|
229
|
+
/**
|
|
230
|
+
* Why we have to request the state if we have a server that can send us the state when we joined?
|
|
231
|
+
* The thing is that when the server detects a new JOIN_PARTICIPANT on livekit room, it sends automatically the state to that peer.
|
|
232
|
+
* But in unity, it takes more time, so that message is not being delivered to the client.
|
|
233
|
+
* So instead, when we are finally connected to the room, we request the state, and then the server answers with the state :)
|
|
234
|
+
*
|
|
235
|
+
* If no response is received within 2 seconds, the request is automatically retried.
|
|
236
|
+
*/
|
|
237
|
+
function requestState() {
|
|
238
|
+
if (isServerAtom.getOrNull()) return
|
|
239
|
+
if (RealmInfo.getOrNull(engine.RootEntity)?.isConnectedSceneRoom && !requestingState) {
|
|
240
|
+
requestingState = true
|
|
241
|
+
elapsedTimeSinceRequest = 0
|
|
242
|
+
DEBUG_NETWORK_MESSAGES() && console.log('Requesting state...')
|
|
243
|
+
binaryMessageBus.emit(CommsMessage.REQ_CRDT_STATE, new Uint8Array())
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// System to retry state request if no response is received within the retry interval
|
|
248
|
+
engine.addSystem((dt: number) => {
|
|
249
|
+
if (requestingState && !stateIsSyncronized) {
|
|
250
|
+
elapsedTimeSinceRequest += dt
|
|
251
|
+
if (elapsedTimeSinceRequest >= STATE_REQUEST_RETRY_INTERVAL) {
|
|
252
|
+
DEBUG_NETWORK_MESSAGES() && console.log('State request timed out, retrying...')
|
|
253
|
+
elapsedTimeSinceRequest = 0
|
|
254
|
+
requestingState = false
|
|
255
|
+
requestState()
|
|
256
|
+
}
|
|
145
257
|
}
|
|
146
258
|
})
|
|
147
259
|
|
|
@@ -153,56 +265,12 @@ export function addSyncTransport(
|
|
|
153
265
|
return stateIsSyncronized
|
|
154
266
|
}
|
|
155
267
|
|
|
156
|
-
function sleep(ms: number) {
|
|
157
|
-
return new Promise<void>((resolve) => {
|
|
158
|
-
let timer = 0
|
|
159
|
-
function sleepSystem(dt: number) {
|
|
160
|
-
timer += dt
|
|
161
|
-
if (timer * 1000 >= ms) {
|
|
162
|
-
engine.removeSystem(sleepSystem)
|
|
163
|
-
resolve()
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
engine.addSystem(sleepSystem)
|
|
167
|
-
})
|
|
168
|
-
}
|
|
169
|
-
|
|
170
268
|
return {
|
|
171
269
|
...entityDefinitions,
|
|
172
270
|
myProfile,
|
|
173
|
-
isStateSyncronized
|
|
271
|
+
isStateSyncronized,
|
|
272
|
+
binaryMessageBus,
|
|
273
|
+
eventBus,
|
|
274
|
+
isRoomReadyAtom
|
|
174
275
|
}
|
|
175
276
|
}
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Messages Protocol Encoding
|
|
179
|
-
*
|
|
180
|
-
* CRDT: Plain Uint8Array
|
|
181
|
-
*
|
|
182
|
-
* CRDT_STATE_RES { sender: string, data: Uint8Array}
|
|
183
|
-
*/
|
|
184
|
-
function decodeCRDTState(data: Uint8Array) {
|
|
185
|
-
let offset = 0
|
|
186
|
-
const r = new Uint8Array(data)
|
|
187
|
-
const view = new DataView(r.buffer)
|
|
188
|
-
const senderLength = view.getUint8(offset)
|
|
189
|
-
offset += 1
|
|
190
|
-
const sender = decodeString(data.subarray(1, senderLength + 1))
|
|
191
|
-
offset += senderLength
|
|
192
|
-
const state = r.subarray(offset)
|
|
193
|
-
|
|
194
|
-
return { sender, data: state }
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function encodeCRDTState(address: string, data: Uint8Array) {
|
|
198
|
-
// address to uint8array
|
|
199
|
-
const addressBuffer = encodeString(address)
|
|
200
|
-
const addressOffset = 1
|
|
201
|
-
const messageLength = addressOffset + addressBuffer.byteLength + data.byteLength
|
|
202
|
-
|
|
203
|
-
const serializedMessage = new Uint8Array(messageLength)
|
|
204
|
-
serializedMessage.set(new Uint8Array([addressBuffer.byteLength]), 0)
|
|
205
|
-
serializedMessage.set(addressBuffer, 1)
|
|
206
|
-
serializedMessage.set(data, addressBuffer.byteLength + 1)
|
|
207
|
-
return serializedMessage
|
|
208
|
-
}
|