Skip to content

Commit

Permalink
Add DisableGC option to document (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
humdrum authored Sep 25, 2023
1 parent eaab164 commit 3c8e311
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Sources/Document/Document.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@
import Combine
import Foundation

/**
* `DocumentOptions` are the options to create a new document.
*
* @public
*/
public struct DocumentOptions {
/**
* `disableGC` disables garbage collection if true.
*/
var disableGC: Bool
}

/**
* `DocumentStatus` represents the status of the document.
*/
Expand Down Expand Up @@ -59,6 +71,7 @@ public actor Document {

private let key: DocumentKey
private(set) var status: DocumentStatus
private let opts: DocumentOptions
private var changeID: ChangeID
var checkpoint: Checkpoint
private var localChanges: [Change]
Expand All @@ -81,8 +94,13 @@ public actor Document {
private var presences: [ActorID: StringValueTypeDictionary]

public init(key: String) {
self.init(key: key, opts: DocumentOptions(disableGC: false))
}

public init(key: String, opts: DocumentOptions) {
self.key = key
self.status = .detached
self.opts = opts
self.root = CRDTRoot()
self.changeID = ChangeID.initial
self.checkpoint = Checkpoint.initial
Expand Down Expand Up @@ -300,6 +318,10 @@ public actor Document {
*/
@discardableResult
func garbageCollect(lessThanOrEqualTo ticket: TimeTicket) -> Int {
if self.opts.disableGC {
return 0
}

if let clone = self.clone {
clone.root.garbageCollect(lessThanOrEqualTo: ticket)
}
Expand Down
27 changes: 27 additions & 0 deletions Tests/Integration/GCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,33 @@ class GCTests: XCTestCase {
XCTAssertEqual(0, len)
}

func test_disable_GC_test() async throws {
let doc = Document(key: "test-doc", opts: DocumentOptions(disableGC: true))

try await doc.update({ root, _ in
root["1"] = Int64(1)
root["2"] = [Int64(1), Int64(2), Int64(3)]
root["3"] = Int64(3)
}, "set 1, 2, 3")

var result = await doc.toSortedJSON()
XCTAssertEqual("{\"1\":1,\"2\":[1,2,3],\"3\":3}", result)

try await doc.update({ root, _ in
root.remove(key: "2")
}, "deletes 2")

result = await doc.toSortedJSON()
XCTAssertEqual("{\"1\":1,\"3\":3}", result)

var len = await doc.getGarbageLength()
XCTAssertEqual(4, len)
len = await doc.garbageCollect(lessThanOrEqualTo: TimeTicket.max)
XCTAssertEqual(0, len)
len = await doc.getGarbageLength()
XCTAssertEqual(4, len)
}

func test_garbage_collection_test2() async throws {
let size = 10000
let doc = Document(key: "test-doc")
Expand Down

0 comments on commit 3c8e311

Please sign in to comment.