2024-01-04 14:10:08 +01:00
|
|
|
// automerge: automerge is a CRDT library. Defines a CRDT
|
|
|
|
// datastore and methods to resolve conflicts
|
2023-11-30 03:02:38 +01:00
|
|
|
package automerge
|
2023-10-23 19:13:08 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/automerge/automerge-go"
|
2024-01-02 00:55:50 +01:00
|
|
|
logging "github.com/tim-beatham/smegmesh/pkg/log"
|
2023-10-23 19:13:08 +02:00
|
|
|
)
|
|
|
|
|
2024-01-04 14:10:08 +01:00
|
|
|
// AutomergeSync: defines a synchroniser to bi-directionally synchronise the
|
|
|
|
// two states
|
2023-10-23 19:13:08 +02:00
|
|
|
type AutomergeSync struct {
|
2024-01-04 14:10:08 +01:00
|
|
|
// state: the automerge sync state to use
|
|
|
|
state *automerge.SyncState
|
|
|
|
// manager: the corresponding data store that we are merging
|
2023-10-26 17:53:12 +02:00
|
|
|
manager *CrdtMeshManager
|
2023-10-23 19:13:08 +02:00
|
|
|
}
|
|
|
|
|
2024-01-04 14:10:08 +01:00
|
|
|
// GenerateMessage: geenrate a new automerge message to synchronise
|
|
|
|
// returns a byte of the message and a boolean of whether or not there
|
|
|
|
// are more messages in the sequence
|
2023-10-23 19:13:08 +02:00
|
|
|
func (a *AutomergeSync) GenerateMessage() ([]byte, bool) {
|
|
|
|
msg, valid := a.state.GenerateMessage()
|
|
|
|
|
|
|
|
if !valid {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
return msg.Bytes(), true
|
|
|
|
}
|
|
|
|
|
2024-01-04 14:10:08 +01:00
|
|
|
// RecvMessage: receive an automerge message to merge in the datastore
|
|
|
|
// returns an error if unsuccessful
|
2023-10-23 19:13:08 +02:00
|
|
|
func (a *AutomergeSync) RecvMessage(msg []byte) error {
|
|
|
|
_, err := a.state.ReceiveMessage(msg)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-01-04 14:10:08 +01:00
|
|
|
// Complete: complete the synchronisation process
|
2023-10-24 17:00:46 +02:00
|
|
|
func (a *AutomergeSync) Complete() {
|
2024-01-04 14:10:08 +01:00
|
|
|
logging.Log.WriteInfof("sync completed")
|
2023-11-30 03:02:38 +01:00
|
|
|
a.manager.SaveChanges()
|
2023-10-24 17:00:46 +02:00
|
|
|
}
|
|
|
|
|
2024-01-04 14:10:08 +01:00
|
|
|
// NewAutomergeSync: instantiates a new automerge syncer
|
2023-10-26 17:53:12 +02:00
|
|
|
func NewAutomergeSync(manager *CrdtMeshManager) *AutomergeSync {
|
2023-10-24 17:00:46 +02:00
|
|
|
return &AutomergeSync{
|
|
|
|
state: automerge.NewSyncState(manager.doc),
|
|
|
|
manager: manager,
|
|
|
|
}
|
2023-10-23 19:13:08 +02:00
|
|
|
}
|