|
1 | 1 | package io.ably.lib.objects |
2 | 2 |
|
| 3 | +import io.ably.lib.realtime.ChannelState |
3 | 4 | import io.ably.lib.types.Callback |
4 | 5 | import io.ably.lib.types.ProtocolMessage |
5 | 6 | import io.ably.lib.util.Log |
| 7 | +import kotlinx.coroutines.* |
| 8 | +import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED |
| 9 | +import kotlinx.coroutines.flow.MutableSharedFlow |
6 | 10 |
|
7 | | -internal class DefaultLiveObjects(private val channelName: String, private val adapter: LiveObjectsAdapter): LiveObjects { |
8 | | - private val tag = DefaultLiveObjects::class.simpleName |
| 11 | +/** |
| 12 | + * @spec RTO2 - enum representing objects state |
| 13 | + */ |
| 14 | +internal enum class ObjectsState { |
| 15 | + INITIALIZED, |
| 16 | + SYNCING, |
| 17 | + SYNCED |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Default implementation of LiveObjects interface. |
| 22 | + * Provides the core functionality for managing live objects on a channel. |
| 23 | + */ |
| 24 | +internal class DefaultLiveObjects(internal val channelName: String, internal val adapter: LiveObjectsAdapter): LiveObjects { |
| 25 | + private val tag = "DefaultLiveObjects" |
| 26 | + /** |
| 27 | + * @spec RTO3 - Objects pool storing all live objects by object ID |
| 28 | + */ |
| 29 | + internal val objectsPool = ObjectsPool(this) |
| 30 | + |
| 31 | + internal var state = ObjectsState.INITIALIZED |
| 32 | + |
| 33 | + /** |
| 34 | + * @spec RTO4 - Used for handling object messages and object sync messages |
| 35 | + */ |
| 36 | + private val objectsManager = ObjectsManager(this) |
9 | 37 |
|
| 38 | + /** |
| 39 | + * Coroutine scope for running sequential operations on a single thread, used to avoid concurrency issues. |
| 40 | + */ |
| 41 | + private val sequentialScope = |
| 42 | + CoroutineScope(Dispatchers.Default.limitedParallelism(1) + CoroutineName(channelName) + SupervisorJob()) |
| 43 | + |
| 44 | + /** |
| 45 | + * Event bus for handling incoming object messages sequentially. |
| 46 | + */ |
| 47 | + private val objectsEventBus = MutableSharedFlow<ProtocolMessage>(extraBufferCapacity = UNLIMITED) |
| 48 | + private val incomingObjectsHandler: Job |
| 49 | + |
| 50 | + init { |
| 51 | + incomingObjectsHandler = initializeHandlerForIncomingObjectMessages() |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @spec RTO1 - Returns the root LiveMap object with proper validation and sync waiting |
| 56 | + */ |
10 | 57 | override fun getRoot(): LiveMap { |
11 | 58 | TODO("Not yet implemented") |
12 | 59 | } |
@@ -47,18 +94,121 @@ internal class DefaultLiveObjects(private val channelName: String, private val a |
47 | 94 | TODO("Not yet implemented") |
48 | 95 | } |
49 | 96 |
|
50 | | - fun handle(msg: ProtocolMessage) { |
51 | | - // RTL15b |
52 | | - msg.channelSerial?.let { |
53 | | - if (msg.action === ProtocolMessage.Action.`object`) { |
54 | | - Log.v(tag, "Setting channel serial for channelName: $channelName, value: ${msg.channelSerial}") |
55 | | - adapter.setChannelSerial(channelName, msg.channelSerial) |
| 97 | + /** |
| 98 | + * Handles a ProtocolMessage containing proto action as `object` or `object_sync`. |
| 99 | + * @spec RTL1 - Processes incoming object messages and object sync messages |
| 100 | + */ |
| 101 | + internal fun handle(protocolMessage: ProtocolMessage) { |
| 102 | + // RTL15b - Set channel serial for OBJECT messages |
| 103 | + adapter.setChannelSerial(channelName, protocolMessage) |
| 104 | + |
| 105 | + if (protocolMessage.state == null || protocolMessage.state.isEmpty()) { |
| 106 | + Log.w(tag, "Received ProtocolMessage with null or empty objects, ignoring") |
| 107 | + return |
| 108 | + } |
| 109 | + |
| 110 | + objectsEventBus.tryEmit(protocolMessage) |
| 111 | + } |
| 112 | + |
| 113 | + /** |
| 114 | + * Initializes the handler for incoming object messages and object sync messages. |
| 115 | + * Processes the messages sequentially to ensure thread safety and correct order of operations. |
| 116 | + * |
| 117 | + * @spec OM2 - Populates missing fields from parent protocol message |
| 118 | + */ |
| 119 | + private fun initializeHandlerForIncomingObjectMessages(): Job { |
| 120 | + return sequentialScope.launch { |
| 121 | + objectsEventBus.collect { protocolMessage -> |
| 122 | + // OM2 - Populate missing fields from parent |
| 123 | + val objects = protocolMessage.state.filterIsInstance<ObjectMessage>() |
| 124 | + .mapIndexed { index, objMsg -> |
| 125 | + objMsg.copy( |
| 126 | + connectionId = objMsg.connectionId ?: protocolMessage.connectionId, // OM2c |
| 127 | + timestamp = objMsg.timestamp ?: protocolMessage.timestamp, // OM2e |
| 128 | + id = objMsg.id ?: (protocolMessage.id + ':' + index) // OM2a |
| 129 | + ) |
| 130 | + } |
| 131 | + |
| 132 | + try { |
| 133 | + when (protocolMessage.action) { |
| 134 | + ProtocolMessage.Action.`object` -> objectsManager.handleObjectMessages(objects) |
| 135 | + ProtocolMessage.Action.object_sync -> objectsManager.handleObjectSyncMessages( |
| 136 | + objects, |
| 137 | + protocolMessage.channelSerial |
| 138 | + ) |
| 139 | + else -> Log.w(tag, "Ignoring protocol message with unhandled action: ${protocolMessage.action}") |
| 140 | + } |
| 141 | + } catch (exception: Exception) { |
| 142 | + // Skip current message if an error occurs, don't rethrow to avoid crashing the collector |
| 143 | + Log.e(tag, "Error handling objects message with protocolMsg id ${protocolMessage.id}", exception) |
| 144 | + } |
56 | 145 | } |
57 | 146 | } |
58 | 147 | } |
59 | 148 |
|
60 | | - fun dispose() { |
61 | | - // Dispose of any resources associated with this LiveObjects instance |
62 | | - // For example, close any open connections or clean up references |
| 149 | + internal fun handleStateChange(state: ChannelState, hasObjects: Boolean) { |
| 150 | + sequentialScope.launch { |
| 151 | + when (state) { |
| 152 | + ChannelState.attached -> { |
| 153 | + Log.v(tag, "Objects.onAttached() channel=$channelName, hasObjects=$hasObjects") |
| 154 | + |
| 155 | + // RTO4a |
| 156 | + val fromInitializedState = this@DefaultLiveObjects.state == ObjectsState.INITIALIZED |
| 157 | + if (hasObjects || fromInitializedState) { |
| 158 | + // should always start a new sync sequence if we're in the initialized state, no matter the HAS_OBJECTS flag value. |
| 159 | + // this guarantees we emit both "syncing" -> "synced" events in that order. |
| 160 | + objectsManager.startNewSync(null) |
| 161 | + } |
| 162 | + |
| 163 | + // RTO4b |
| 164 | + if (!hasObjects) { |
| 165 | + // if no HAS_OBJECTS flag received on attach, we can end sync sequence immediately and treat it as no objects on a channel. |
| 166 | + // reset the objects pool to its initial state, and emit update events so subscribers to root object get notified about changes. |
| 167 | + objectsPool.resetToInitialPool(true) // RTO4b1, RTO4b2 |
| 168 | + objectsManager.clearSyncObjectsDataPool() // RTO4b3 |
| 169 | + objectsManager.clearBufferedObjectOperations() // RTO4b5 |
| 170 | + // defer the state change event until the next tick if we started a new sequence just now due to being in initialized state. |
| 171 | + // this allows any event listeners to process the start of the new sequence event that was emitted earlier during this event loop. |
| 172 | + objectsManager.endSync(fromInitializedState) // RTO4b4 |
| 173 | + } |
| 174 | + } |
| 175 | + ChannelState.detached, |
| 176 | + ChannelState.failed -> { |
| 177 | + // do not emit data update events as the actual current state of Objects data is unknown when we're in these channel states |
| 178 | + objectsPool.clearObjectsData(false) |
| 179 | + objectsManager.clearSyncObjectsDataPool() |
| 180 | + } |
| 181 | + |
| 182 | + else -> { |
| 183 | + // No action needed for other states |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + /** |
| 190 | + * Changes the state and emits events. |
| 191 | + * |
| 192 | + * @spec RTO2 - Emits state change events for syncing and synced states |
| 193 | + */ |
| 194 | + internal fun stateChange(newState: ObjectsState, deferEvent: Boolean) { |
| 195 | + if (state == newState) { |
| 196 | + return |
| 197 | + } |
| 198 | + |
| 199 | + state = newState |
| 200 | + Log.v(tag, "Objects state changed to: $newState") |
| 201 | + |
| 202 | + // TODO: Emit state change events |
| 203 | + } |
| 204 | + |
| 205 | + // Dispose of any resources associated with this LiveObjects instance |
| 206 | + fun dispose(reason: String) { |
| 207 | + val cancellationError = CancellationException("Objects disposed for channel $channelName, reason: $reason") |
| 208 | + incomingObjectsHandler.cancel(cancellationError) // objectsEventBus automatically garbage collected when collector is cancelled |
| 209 | + objectsPool.dispose() |
| 210 | + objectsManager.dispose() |
| 211 | + // Don't cancel sequentialScope (needed in public methods), just cancel ongoing coroutines |
| 212 | + sequentialScope.coroutineContext.cancelChildren(cancellationError) |
63 | 213 | } |
64 | 214 | } |
0 commit comments