-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathEngineAPIImplementation.cs
More file actions
292 lines (237 loc) · 12.8 KB
/
Copy pathEngineAPIImplementation.cs
File metadata and controls
292 lines (237 loc) · 12.8 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
using CRDT.Deserializer;
using CRDT.Protocol;
using CRDT.Protocol.Factory;
using CRDT.Serializer;
using CrdtEcsBridge.OutgoingMessages;
using CrdtEcsBridge.PoolsProviders;
using CrdtEcsBridge.UpdateGate;
using CrdtEcsBridge.WorldSynchronizer;
using DCL.Diagnostics;
using DCL.Profiling;
using SceneRunner.Scene.ExceptionsHandling;
using SceneRuntime.Apis.Modules.EngineApi;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine.Profiling;
using Utility.Multithreading;
using Profiler = UnityEngine.Profiling.Profiler;
namespace CrdtEcsBridge.JsModulesImplementation
{
/// <summary>
/// Unique instance for each Scene Runtime
/// </summary>
public class EngineAPIImplementation : IEngineApi
{
protected readonly ISharedPoolsProvider sharedPoolsProvider;
private readonly CustomSampler applyBufferSampler;
private readonly ICRDTDeserializer crdtDeserializer;
private readonly CustomSampler crdtProcessMessagesSampler;
private readonly ICRDTProtocol crdtProtocol;
private readonly ICRDTSerializer crdtSerializer;
private readonly ICRDTWorldSynchronizer crdtWorldSynchronizer;
private readonly CustomSampler deserializeBatchSampler;
private readonly ISceneExceptionsHandler exceptionsHandler;
private readonly IInstancePoolsProvider instancePoolsProvider;
private readonly MultiThreadSync multiThreadSync;
private readonly MultiThreadSync.Owner syncOwner;
private readonly IOutgoingCRDTMessagesProvider outgoingCrtdMessagesProvider;
private readonly CustomSampler outgoingMessagesSampler;
private readonly ISystemGroupsUpdateGate systemGroupsUpdateGate;
private readonly CustomSampler worldSyncBufferSampler;
private readonly SceneRuntimeMetrics metrics;
private readonly Action<OutgoingCRDTMessagesProvider.PendingMessage> processPendingMessage;
public EngineAPIImplementation(
ISharedPoolsProvider poolsProvider,
IInstancePoolsProvider instancePoolsProvider,
ICRDTProtocol crdtProtocol,
ICRDTDeserializer crdtDeserializer,
ICRDTSerializer crdtSerializer,
ICRDTWorldSynchronizer crdtWorldSynchronizer,
IOutgoingCRDTMessagesProvider outgoingCrtdMessagesProvider,
ISystemGroupsUpdateGate systemGroupsUpdateGate,
ISceneExceptionsHandler exceptionsHandler,
MultiThreadSync multiThreadSync,
MultiThreadSync.Owner syncOwner,
SceneRuntimeMetrics metrics)
{
sharedPoolsProvider = poolsProvider;
this.instancePoolsProvider = instancePoolsProvider;
this.crdtProtocol = crdtProtocol;
this.crdtDeserializer = crdtDeserializer;
this.crdtSerializer = crdtSerializer;
this.crdtWorldSynchronizer = crdtWorldSynchronizer;
this.outgoingCrtdMessagesProvider = outgoingCrtdMessagesProvider;
this.multiThreadSync = multiThreadSync;
this.syncOwner = syncOwner;
this.systemGroupsUpdateGate = systemGroupsUpdateGate;
this.exceptionsHandler = exceptionsHandler;
this.metrics = metrics;
deserializeBatchSampler = CustomSampler.Create("DeserializeBatch");
worldSyncBufferSampler = CustomSampler.Create("WorldSyncBuffer");
outgoingMessagesSampler = CustomSampler.Create("OutgoingMessages");
crdtProcessMessagesSampler = CustomSampler.Create("CRDTProcessMessage");
applyBufferSampler = CustomSampler.Create(nameof(ApplySyncCommandBuffer));
processPendingMessage = ProcessPendingMessage;
}
public virtual void Dispose() { }
public PoolableByteArray CrdtSendToRenderer(ReadOnlyMemory<byte> dataMemory, bool returnData = true)
{
// Called on the thread where the Scene Runtime is running (background thread)
// Deserialize messages from the byte array
List<CRDTMessage> messages = instancePoolsProvider.GetDeserializationMessagesPool();
deserializeBatchSampler.Begin();
// TODO add metrics to understand bottlenecks better
crdtDeserializer.DeserializeBatch(ref dataMemory, messages);
deserializeBatchSampler.End();
metrics.MessagesFromScene.Add(messages.Count);
worldSyncBufferSampler.Begin();
// as we no longer wait for a buffer to apply the thread should be frozen
IWorldSyncCommandBuffer worldSyncBuffer = crdtWorldSynchronizer.GetSyncCommandBuffer();
// Reconcile CRDT state
for (var i = 0; i < messages.Count; i++)
{
CRDTMessage message = messages[i];
// Skip Creator Hub components leaked from main.composite (inspector::*,
// specific asset-packs:: tooling metadata, composite::root) and phantom
// Creator Hub tags (custom components with empty data, e.g. cube-id).
if (message.Type is CRDTMessageType.PUT_COMPONENT
or CRDTMessageType.DELETE_COMPONENT
or CRDTMessageType.APPEND_COMPONENT
&& CreatorHubComponentFilter.ShouldFilter(in message))
{
message.Data.Dispose();
continue;
}
crdtProcessMessagesSampler.Begin();
CRDTReconciliationResult reconciliationResult = crdtProtocol.ProcessMessage(in message);
crdtProcessMessagesSampler.End();
// TODO add metric to understand how many conflicts we have based on CRDTStateReconciliationResult
// Prepare the message to be synced with the ECS World
worldSyncBuffer.SyncCRDTMessage(in message, reconciliationResult.Effect);
}
// Deserialize messages
worldSyncBuffer.FinalizeAndDeserialize();
worldSyncBufferSampler.End();
ApplySyncCommandBuffer(worldSyncBuffer);
instancePoolsProvider.ReleaseDeserializationMessagesPool(messages);
return returnData ? SerializeOutgoingCRDTMessages() : PoolableByteArray.EMPTY;
}
public PoolableByteArray CrdtGetState()
{
Profiler.BeginThreadProfiling("SceneRuntime", "CrtdGetState");
// Invoked on the background thread
// this method is called rarely but the memory impact is significant
try
{
// Apply outgoing messages straight-away so they are reflected in the current CRDT state
using (OutgoingCRDTMessagesSyncBlock outgoingMessagesSyncBlock = GetSerializationSyncBlock())
SyncOutgoingCRDTMessages(outgoingMessagesSyncBlock.Messages);
// Create CRDT Messages from the current state
// we know exactly how big the array should be
int messagesCount = crdtProtocol.GetMessagesCount();
metrics.MessagesToScene.Add(messagesCount);
ProcessedCRDTMessage[] processedMessages = sharedPoolsProvider.GetSerializationCrdtMessagesPool(messagesCount);
int currentStatePayloadLength = crdtProtocol.CreateMessagesFromTheCurrentState(processedMessages);
// We know exactly how many bytes we need to serialize
PoolableByteArray serializationBufferPoolable = sharedPoolsProvider.GetSerializedStateBytesPool(currentStatePayloadLength);
Span<byte> currentStateSpan = serializationBufferPoolable.Span;
// Serialize the current state
for (var i = 0; i < messagesCount; i++)
crdtSerializer.Serialize(ref currentStateSpan, in processedMessages[i]);
// Messages are serialized, we no longer need them in the managed form
sharedPoolsProvider.ReleaseSerializationCrdtMessagesPool(processedMessages);
// Return the buffer to the caller
return serializationBufferPoolable;
}
catch (Exception e)
{
exceptionsHandler.OnEngineException(e, ReportCategory.CRDT);
return PoolableByteArray.EMPTY;
}
finally { Profiler.EndThreadProfiling(); }
}
private OutgoingCRDTMessagesSyncBlock GetSerializationSyncBlock() =>
outgoingCrtdMessagesProvider.GetSerializationSyncBlock(processPendingMessage);
protected virtual void ProcessPendingMessage(OutgoingCRDTMessagesProvider.PendingMessage pendingMessage) { }
private PoolableByteArray SerializeOutgoingCRDTMessages()
{
try
{
outgoingMessagesSampler.Begin();
PoolableByteArray serializationBufferPoolable;
using (OutgoingCRDTMessagesSyncBlock outgoingMessagesSyncBlock = GetSerializationSyncBlock())
{
serializationBufferPoolable =
sharedPoolsProvider.GetSerializedStateBytesPool(outgoingMessagesSyncBlock.PayloadLength);
SerializeOutgoingCRDTMessages(outgoingMessagesSyncBlock.Messages, serializationBufferPoolable.Span);
SyncOutgoingCRDTMessages(outgoingMessagesSyncBlock.Messages);
metrics.MessagesToScene.Add(outgoingMessagesSyncBlock.Messages.Count);
}
outgoingMessagesSampler.End();
return serializationBufferPoolable;
}
catch (Exception e)
{
exceptionsHandler.OnEngineException(e, ReportCategory.CRDT);
return PoolableByteArray.EMPTY;
}
}
/// <summary>
/// If local messages are not written in the local CRDT, the final state
/// including timestamp is incorrect. Subsequent creation of propagated messages will result in a wrong timestamp
/// </summary>
private void SyncOutgoingCRDTMessages(IReadOnlyList<ProcessedCRDTMessage> outgoingMessages)
{
for (var i = 0; i < outgoingMessages.Count; i++) { SyncCRDTMessage(outgoingMessages[i]); }
}
private void SyncCRDTMessage(ProcessedCRDTMessage message)
{
// We are interested in LWW messages only, in AUTHORITATIVE_PUT_COMPONENT we are not interested as it can't be originated from the client
switch (message.message.Type)
{
case CRDTMessageType.DELETE_COMPONENT:
case CRDTMessageType.PUT_COMPONENT:
// instead of processing via CRDTProtocol.ProcessMessage
// we can skip part of the logic as we guarantee that the local message is the final valid state (see OutgoingCRDTMessagesProvider.AddLwwMessage)
crdtProtocol.EnforceLWWState(message.message);
break;
default:
// as this data is not kept in CRDTProtocol it must be released immediately
message.message.Data.Dispose();
break;
}
}
// Use mutex to apply command buffer from the background thread instead of synchronizing by the main one
private void ApplySyncCommandBuffer(IWorldSyncCommandBuffer worldSyncBuffer)
{
try
{
if (worldSyncBuffer.IsEmpty)
{
// Nothing to apply to the World: skip acquiring the world mutex entirely,
// otherwise an idle scene blocks its runtime thread on the main thread every tick
crdtWorldSynchronizer.ReleaseSyncCommandBuffer(worldSyncBuffer);
}
else
{
using MultiThreadSync.Scope mutex = multiThreadSync.GetScope(syncOwner);
applyBufferSampler.Begin();
// Apply changes to the ECS World on the main thread
crdtWorldSynchronizer.ApplySyncCommandBuffer(worldSyncBuffer);
applyBufferSampler.End();
}
// Allow system for which throttling is enabled to process once
// If the scene is updated more frequently than Unity Loop the gate will be effectively open all the time
systemGroupsUpdateGate.Open();
}
catch (Exception e) { exceptionsHandler.OnEngineException(e, ReportCategory.CRDT_ECS_BRIDGE); }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SerializeOutgoingCRDTMessages(IReadOnlyCollection<ProcessedCRDTMessage> outgoingMessages, Span<byte> span)
{
if (outgoingMessages.Count == 0) return;
foreach (ProcessedCRDTMessage processedCRDTMessage in outgoingMessages) { crdtSerializer.Serialize(ref span, in processedCRDTMessage); }
}
}
}