@@ -3,23 +3,26 @@ package db
33
44import (
55 "context"
6+ "errors"
67 "fmt"
78 "time"
89
910 "github.com/anyproto/any-sync/app"
1011 "github.com/anyproto/any-sync/app/logger"
1112 "github.com/anyproto/any-sync/consensus/consensusproto/consensuserr"
13+ "go.mongodb.org/mongo-driver/bson"
1214 "go.mongodb.org/mongo-driver/mongo"
1315 "go.mongodb.org/mongo-driver/mongo/options"
1416 "go.mongodb.org/mongo-driver/mongo/readpref"
1517 "go.uber.org/zap"
1618
1719 consensus "github.com/anyproto/any-sync-consensusnode"
18- "github.com/anyproto/any-sync-consensusnode/config"
1920)
2021
2122const CName = "consensus.db"
2223
24+ const settingsColl = "settings"
25+
2326var log = logger .NewNamed (CName )
2427
2528func New () Service {
@@ -40,12 +43,17 @@ type Service interface {
4043 FetchLog (ctx context.Context , logId string ) (log consensus.Log , err error )
4144 // SetChangeReceiver sets the receiver for updates, it must be called before app.Run stage
4245 SetChangeReceiver (receiver ChangeReceiver ) (err error )
46+ // SetDeletionId sets the last deleted log id
47+ SetDeletionId (ctx context.Context , lastId string ) (err error )
48+ // GetDeletionId gets the last deletion log id
49+ GetDeletionId (ctx context.Context ) (lastId string , err error )
4350 app.ComponentRunnable
4451}
4552
4653type service struct {
47- conf config. Mongo
54+ conf Config
4855 logColl * mongo.Collection
56+ settingsColl * mongo.Collection
4957 running bool
5058 changeReceiver ChangeReceiver
5159
@@ -55,7 +63,7 @@ type service struct {
5563}
5664
5765func (s * service ) Init (a * app.App ) (err error ) {
58- s .conf = a .MustComponent (config . CName ).(* config. Config ). Mongo
66+ s .conf = a .MustComponent (" config" ).(configGetter ). GetDB ()
5967 return nil
6068}
6169
@@ -80,6 +88,7 @@ func (s *service) Run(ctx context.Context) (err error) {
8088 return err
8189 }
8290 }
91+ s .settingsColl = client .Database (s .conf .Database ).Collection (settingsColl )
8392 return
8493}
8594
@@ -200,6 +209,23 @@ func (s *service) streamListener(stream *mongo.ChangeStream) {
200209 }
201210}
202211
212+ func (s * service ) SetDeletionId (ctx context.Context , lastId string ) (err error ) {
213+ updateOpts := options .Update ().SetUpsert (true )
214+ _ , err = s .settingsColl .UpdateOne (ctx , bson.D {{"_id" , "settings" }}, bson.D {{"$set" , bson.D {{"logId" , lastId }}}}, updateOpts )
215+ return
216+ }
217+
218+ func (s * service ) GetDeletionId (ctx context.Context ) (lastId string , err error ) {
219+ var res struct {
220+ LogId string `bson:"logId"`
221+ }
222+ err = s .settingsColl .FindOne (ctx , bson.D {{"_id" , "settings" }}).Decode (& res )
223+ if errors .Is (err , mongo .ErrNoDocuments ) {
224+ err = nil
225+ }
226+ return res .LogId , err
227+ }
228+
203229func (s * service ) Close (ctx context.Context ) (err error ) {
204230 if s .logColl != nil {
205231 err = s .logColl .Database ().Client ().Disconnect (ctx )
0 commit comments