-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInternalDefaultLiveCounter.swift
More file actions
498 lines (431 loc) · 19.2 KB
/
InternalDefaultLiveCounter.swift
File metadata and controls
498 lines (431 loc) · 19.2 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
internal import _AblyPluginSupportPrivate
import Ably
import Foundation
/// This provides the implementation behind ``PublicDefaultLiveCounter``, via internal versions of the ``LiveCounter`` API.
internal final class InternalDefaultLiveCounter: Sendable {
private let mutableStateMutex: DispatchQueueMutex<MutableState>
internal var testsOnly_siteTimeserials: [String: String] {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.siteTimeserials
}
}
internal var testsOnly_createOperationIsMerged: Bool {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.createOperationIsMerged
}
}
private let logger: Logger
private let userCallbackQueue: DispatchQueue
private let clock: SimpleClock
// MARK: - Initialization
internal convenience init(
testsOnly_data data: Double,
objectID: String,
logger: Logger,
internalQueue: DispatchQueue,
userCallbackQueue: DispatchQueue,
clock: SimpleClock
) {
self.init(
data: data,
objectID: objectID,
logger: logger,
internalQueue: internalQueue,
userCallbackQueue: userCallbackQueue,
clock: clock,
)
}
private init(
data: Double,
objectID: String,
logger: Logger,
internalQueue: DispatchQueue,
userCallbackQueue: DispatchQueue,
clock: SimpleClock
) {
mutableStateMutex = .init(
dispatchQueue: internalQueue,
initialValue: .init(liveObjectMutableState: .init(objectID: objectID), data: data),
)
self.logger = logger
self.userCallbackQueue = userCallbackQueue
self.clock = clock
}
/// Creates a "zero-value LiveCounter", per RTLC4.
///
/// - Parameters:
/// - objectID: The value for the "private objectId field" of RTO5c1b1a.
internal static func createZeroValued(
objectID: String,
logger: Logger,
internalQueue: DispatchQueue,
userCallbackQueue: DispatchQueue,
clock: SimpleClock,
) -> Self {
.init(
data: 0,
objectID: objectID,
logger: logger,
internalQueue: internalQueue,
userCallbackQueue: userCallbackQueue,
clock: clock,
)
}
// MARK: - Data access
internal var nosync_objectID: String {
mutableStateMutex.withoutSync { mutableState in
mutableState.liveObjectMutableState.objectID
}
}
/// Test-only accessor for objectID that handles locking internally.
internal var testsOnly_objectID: String {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.objectID
}
}
// MARK: - Internal methods that back LiveCounter conformance
internal func value(coreSDK: CoreSDK) throws(ARTErrorInfo) -> Double {
try mutableStateMutex.withSync { mutableState throws(ARTErrorInfo) in
try mutableState.nosync_value(coreSDK: coreSDK)
}
}
internal func increment(amount: Double, coreSDK: CoreSDK, realtimeObjects: any InternalRealtimeObjectsProtocol) async throws(ARTErrorInfo) {
try await withCheckedContinuation { (continuation: CheckedContinuation<Result<Void, ARTErrorInfo>, _>) in
do throws(ARTErrorInfo) {
try mutableStateMutex.withSync { mutableState throws(ARTErrorInfo) in
// RTLC12e1
if !amount.isFinite {
throw LiveObjectsError.counterIncrementAmountInvalid(amount: amount).toARTErrorInfo()
}
// RTLC12c
try coreSDK.nosync_validateChannelState(
notIn: [.detached, .failed, .suspended],
operationDescription: "LiveCounter.increment",
)
let objectMessage = OutboundObjectMessage(
operation: .init(
// RTLC12e2
action: .known(.counterInc),
// RTLC12e3
objectId: mutableState.liveObjectMutableState.objectID,
counterOp: .init(
// RTLC12e4
amount: .init(value: amount),
),
),
)
// RTLC12g
realtimeObjects.nosync_publishAndApply(objectMessages: [objectMessage], coreSDK: coreSDK) { result in
continuation.resume(returning: result)
}
}
} catch {
continuation.resume(returning: .failure(error))
}
}.get()
}
internal func decrement(amount: Double, coreSDK: CoreSDK, realtimeObjects: any InternalRealtimeObjectsProtocol) async throws(ARTErrorInfo) {
// RTLC13b
try await increment(amount: -amount, coreSDK: coreSDK, realtimeObjects: realtimeObjects)
}
@discardableResult
internal func subscribe(listener: @escaping LiveObjectUpdateCallback<DefaultLiveCounterUpdate>, coreSDK: CoreSDK) throws(ARTErrorInfo) -> any SubscribeResponse {
try mutableStateMutex.withSync { mutableState throws(ARTErrorInfo) in
// swiftlint:disable:next trailing_closure
try mutableState.liveObjectMutableState.nosync_subscribe(listener: listener, coreSDK: coreSDK, updateSelfLater: { [weak self] action in
guard let self else {
return
}
mutableStateMutex.withSync { mutableState in
action(&mutableState.liveObjectMutableState)
}
})
}
}
internal func unsubscribeAll() {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.unsubscribeAll()
}
}
@discardableResult
internal func on(event: LiveObjectLifecycleEvent, callback: @escaping LiveObjectLifecycleEventCallback) -> any OnLiveObjectLifecycleEventResponse {
mutableStateMutex.withSync { mutableState in
// swiftlint:disable:next trailing_closure
mutableState.liveObjectMutableState.on(event: event, callback: callback, updateSelfLater: { [weak self] action in
guard let self else {
return
}
mutableStateMutex.withSync { mutableState in
action(&mutableState.liveObjectMutableState)
}
})
}
}
internal func offAll() {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.offAll()
}
}
// MARK: - Emitting update from external sources
/// Emit an event from this `LiveCounter`.
///
/// This is used to instruct this counter to emit updates during an `OBJECT_SYNC`.
internal func nosync_emit(_ update: LiveObjectUpdate<DefaultLiveCounterUpdate>) {
mutableStateMutex.withoutSync { mutableState in
mutableState.liveObjectMutableState.emit(update, on: userCallbackQueue)
}
}
// MARK: - Data manipulation
/// Replaces the internal data of this counter with the provided ObjectState, per RTLC6.
///
/// - Parameters:
/// - objectMessageSerialTimestamp: The `serialTimestamp` of the containing `ObjectMessage`. Used if we need to tombstone this counter.
internal func nosync_replaceData(
using state: ObjectState,
objectMessageSerialTimestamp: Date?,
) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
mutableStateMutex.withoutSync { mutableState in
mutableState.replaceData(
using: state,
objectMessageSerialTimestamp: objectMessageSerialTimestamp,
logger: logger,
clock: clock,
userCallbackQueue: userCallbackQueue,
)
}
}
/// Merges the initial value from an ObjectOperation into this LiveCounter, per RTLC10.
internal func nosync_mergeInitialValue(from operation: ObjectOperation) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
mutableStateMutex.withoutSync { mutableState in
mutableState.mergeInitialValue(from: operation)
}
}
/// Test-only method to apply a COUNTER_CREATE operation, per RTLC8.
internal func testsOnly_applyCounterCreateOperation(_ operation: ObjectOperation) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
mutableStateMutex.withSync { mutableState in
mutableState.applyCounterCreateOperation(operation, logger: logger)
}
}
/// Test-only method to apply a COUNTER_INC operation, per RTLC9.
internal func testsOnly_applyCounterIncOperation(_ operation: WireObjectsCounterOp?) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
mutableStateMutex.withSync { mutableState in
mutableState.applyCounterIncOperation(operation)
}
}
/// Attempts to apply an operation from an inbound `ObjectMessage`, per RTLC7.
///
/// - Returns: `true` if the operation was applied, `false` if it was skipped (RTLC7g).
internal func nosync_apply(
_ operation: ObjectOperation,
source: ObjectsOperationSource,
objectMessageSerial: String?,
objectMessageSiteCode: String?,
objectMessageSerialTimestamp: Date?,
objectsPool: inout ObjectsPool,
) -> Bool {
mutableStateMutex.withoutSync { mutableState in
mutableState.apply(
operation,
source: source,
objectMessageSerial: objectMessageSerial,
objectMessageSiteCode: objectMessageSiteCode,
objectMessageSerialTimestamp: objectMessageSerialTimestamp,
objectsPool: &objectsPool,
logger: logger,
clock: clock,
userCallbackQueue: userCallbackQueue,
)
}
}
// MARK: - LiveObject
/// Returns the object's RTLO3d `isTombstone` property.
internal var nosync_isTombstone: Bool {
mutableStateMutex.withoutSync { mutableState in
mutableState.liveObjectMutableState.isTombstone
}
}
/// Test-only accessor for isTombstone that handles locking internally.
internal var testsOnly_isTombstone: Bool {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.isTombstone
}
}
/// Returns the object's RTLO3e `tombstonedAt` property.
internal var nosync_tombstonedAt: Date? {
mutableStateMutex.withoutSync { mutableState in
mutableState.liveObjectMutableState.tombstonedAt
}
}
/// Test-only accessor for tombstonedAt that handles locking internally.
internal var testsOnly_tombstonedAt: Date? {
mutableStateMutex.withSync { mutableState in
mutableState.liveObjectMutableState.tombstonedAt
}
}
// MARK: - Mutable state and the operations that affect it
private struct MutableState: InternalLiveObject {
/// The mutable state common to all LiveObjects.
internal var liveObjectMutableState: LiveObjectMutableState<DefaultLiveCounterUpdate>
/// The internal data that this map holds, per RTLC3.
internal var data: Double
/// Replaces the internal data of this counter with the provided ObjectState, per RTLC6.
///
/// - Parameters:
/// - objectMessageSerialTimestamp: The `serialTimestamp` of the containing `ObjectMessage`. Used if we need to tombstone this counter.
internal mutating func replaceData(
using state: ObjectState,
objectMessageSerialTimestamp: Date?,
logger: Logger,
clock: SimpleClock,
userCallbackQueue: DispatchQueue,
) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
// RTLC6a: Replace the private siteTimeserials with the value from ObjectState.siteTimeserials
liveObjectMutableState.siteTimeserials = state.siteTimeserials
// RTLC6e, RTLC6e1: No-op if we're already tombstone
if liveObjectMutableState.isTombstone {
return .noop
}
// RTLC6f: Tombstone if state indicates tombstoned
if state.tombstone {
let dataBeforeTombstoning = data
tombstone(
objectMessageSerialTimestamp: objectMessageSerialTimestamp,
logger: logger,
clock: clock,
userCallbackQueue: userCallbackQueue,
)
// RTLC6f1
return .update(.init(amount: -dataBeforeTombstoning))
}
// RTLC6g: Store the current data value as previousData for use in RTLC6h
let previousData = data
// RTLC6b: Set the private flag createOperationIsMerged to false
liveObjectMutableState.createOperationIsMerged = false
// RTLC6c: Set data to the value of ObjectState.counter.count, or to 0 if it does not exist
data = state.counter?.count?.doubleValue ?? 0
// RTLC6d: If ObjectState.createOp is present, merge the initial value into the LiveCounter as described in RTLC10
// Discard the LiveCounterUpdate object returned by the merge operation
if let createOp = state.createOp {
_ = mergeInitialValue(from: createOp)
}
// RTLC6h: Calculate the diff between previousData and the current data per RTLC14
return ObjectDiffHelpers.calculateCounterDiff(previousData: previousData, newData: data)
}
/// Merges the initial value from an ObjectOperation into this LiveCounter, per RTLC10.
internal mutating func mergeInitialValue(from operation: ObjectOperation) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
let update: LiveObjectUpdate<DefaultLiveCounterUpdate>
// RTLC10a: Add ObjectOperation.counter.count to data, if it exists
if let operationCount = operation.counter?.count?.doubleValue {
data += operationCount
// RTLC10c
update = .update(DefaultLiveCounterUpdate(amount: operationCount))
} else {
// RTLC10d
update = .noop
}
// RTLC10b: Set the private flag createOperationIsMerged to true
liveObjectMutableState.createOperationIsMerged = true
return update
}
/// Attempts to apply an operation from an inbound `ObjectMessage`, per RTLC7.
///
/// - Returns: `true` if the operation was applied, `false` if skipped (RTLC7g).
internal mutating func apply(
_ operation: ObjectOperation,
source: ObjectsOperationSource,
objectMessageSerial: String?,
objectMessageSiteCode: String?,
objectMessageSerialTimestamp: Date?,
objectsPool: inout ObjectsPool,
logger: Logger,
clock: SimpleClock,
userCallbackQueue: DispatchQueue,
) -> Bool {
guard let applicableOperation = liveObjectMutableState.canApplyOperation(objectMessageSerial: objectMessageSerial, objectMessageSiteCode: objectMessageSiteCode, logger: logger) else {
// RTLC7b
logger.log("Operation \(operation) (serial: \(String(describing: objectMessageSerial)), siteCode: \(String(describing: objectMessageSiteCode))) should not be applied; discarding", level: .debug)
return false
}
// RTLC7c
if source == .channel {
liveObjectMutableState.siteTimeserials[applicableOperation.objectMessageSiteCode] = applicableOperation.objectMessageSerial
}
// RTLC7e
// TODO: are we still meant to update siteTimeserials? https://github.com/ably/specification/pull/350/files#r2218718854
if liveObjectMutableState.isTombstone {
return false
}
switch operation.action {
case .known(.counterCreate):
// RTLC7d1
let update = applyCounterCreateOperation(
operation,
logger: logger,
)
// RTLC7d1a
liveObjectMutableState.emit(update, on: userCallbackQueue)
// RTLC7d1b
return true
case .known(.counterInc):
// RTLC7d2
let update = applyCounterIncOperation(operation.counterOp)
// RTLC7d2a
liveObjectMutableState.emit(update, on: userCallbackQueue)
// RTLC7d2b
return true
case .known(.objectDelete):
let dataBeforeApplyingOperation = data
// RTLC7d4
applyObjectDeleteOperation(
objectMessageSerialTimestamp: objectMessageSerialTimestamp,
logger: logger,
clock: clock,
userCallbackQueue: userCallbackQueue,
)
// RTLC7d4a
liveObjectMutableState.emit(.update(.init(amount: -dataBeforeApplyingOperation)), on: userCallbackQueue)
// RTLC7d4b
return true
default:
// RTLC7d3
logger.log("Operation \(operation) has unsupported action for LiveCounter; discarding", level: .warn)
return false
}
}
/// Applies a `COUNTER_CREATE` operation, per RTLC8.
internal mutating func applyCounterCreateOperation(
_ operation: ObjectOperation,
logger: Logger,
) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
if liveObjectMutableState.createOperationIsMerged {
// RTLC8b
logger.log("Not applying COUNTER_CREATE because a COUNTER_CREATE has already been applied", level: .warn)
return .noop
}
// RTLC8c, RTLC8e
return mergeInitialValue(from: operation)
}
/// Applies a `COUNTER_INC` operation, per RTLC9.
internal mutating func applyCounterIncOperation(_ operation: WireObjectsCounterOp?) -> LiveObjectUpdate<DefaultLiveCounterUpdate> {
guard let operation else {
// RTL9e
return .noop
}
// RTLC9b, RTLC9d
let amount = operation.amount.doubleValue
data += amount
return .update(DefaultLiveCounterUpdate(amount: amount))
}
/// Needed for ``InternalLiveObject`` conformance.
mutating func resetDataToZeroValued() {
// RTLC4
data = 0
}
internal func nosync_value(coreSDK: CoreSDK) throws(ARTErrorInfo) -> Double {
// RTLC5b: If the channel is in the DETACHED or FAILED state, the library should indicate an error with code 90001
try coreSDK.nosync_validateChannelState(notIn: [.detached, .failed], operationDescription: "LiveCounter.value")
// RTLC5c
return data
}
}
}