11package  workers
22
33import  (
4- 	"context" 
4+ 	gocontext "context" 
5+ 	"errors" 
56	"fmt" 
67	"time" 
78
@@ -11,7 +12,7 @@ import (
1112	"github.com/sentinel-official/sentinel-go-sdk/libs/cron" 
1213	logger "github.com/sentinel-official/sentinel-go-sdk/libs/log" 
1314
14- 	nodecontext  "github.com/sentinel-official/dvpn-node/context" 
15+ 	"github.com/sentinel-official/dvpn-node/context" 
1516	"github.com/sentinel-official/dvpn-node/database/operations" 
1617)
1718
@@ -25,7 +26,7 @@ const (
2526// NewSessionUsageSyncWithBlockchainWorker creates a worker that synchronizes session usage with the blockchain. 
2627// This worker retrieves session data from the database, validates it against the blockchain, 
2728// and broadcasts any updates as transactions. 
28- func  NewSessionUsageSyncWithBlockchainWorker (c  * nodecontext .Context , interval  time.Duration ) cron.Worker  {
29+ func  NewSessionUsageSyncWithBlockchainWorker (c  * context .Context , interval  time.Duration ) cron.Worker  {
2930	log  :=  logger .With ("name" , nameSessionUsageSyncWithBlockchain )
3031
3132	handlerFunc  :=  func () error  {
@@ -34,7 +35,7 @@ func NewSessionUsageSyncWithBlockchainWorker(c *nodecontext.Context, interval ti
3435		// Retrieve session records from the database. 
3536		items , err  :=  operations .SessionFind (c .Database (), nil )
3637		if  err  !=  nil  {
37- 			return  fmt .Errorf ("failed to retrieve sessions from database: %w" , err )
38+ 			return  fmt .Errorf ("failed to retrieve sessions from the  database: %w" , err )
3839		}
3940		if  len (items ) ==  0  {
4041			return  nil 
@@ -43,9 +44,9 @@ func NewSessionUsageSyncWithBlockchainWorker(c *nodecontext.Context, interval ti
4344		var  msgs  []types.Msg 
4445		// Iterate over sessions and prepare messages for updates. 
4546		for  _ , item  :=  range  items  {
46- 			session , err  :=  c .Client ().Session (context .TODO (), item .GetID ())
47+ 			session , err  :=  c .Client ().Session (gocontext .TODO (), item .GetID ())
4748			if  err  !=  nil  {
48- 				return  fmt .Errorf ("failed to query session: %w" , err )
49+ 				return  fmt .Errorf ("failed to query session from the blockchain : %w" , err )
4950			}
5051
5152			if  session  !=  nil  {
@@ -56,12 +57,13 @@ func NewSessionUsageSyncWithBlockchainWorker(c *nodecontext.Context, interval ti
5657		}
5758
5859		// Broadcast the prepared messages as a transaction. 
59- 		res , err  :=  c .BroadcastTx (context .TODO (), msgs ... )
60+ 		res , err  :=  c .BroadcastTx (gocontext .TODO (), msgs ... )
6061		if  err  !=  nil  {
61- 			return  fmt .Errorf ("failed to broadcast update session details  tx: %w" , err )
62+ 			return  fmt .Errorf ("failed to broadcast update session tx: %w" , err )
6263		}
6364		if  ! res .TxResult .IsOK () {
64- 			return  fmt .Errorf ("update session details tx failed with code %d: %s" , res .TxResult .Code , res .TxResult .Log )
65+ 			err  :=  errors .New (res .TxResult .Log )
66+ 			return  fmt .Errorf ("update session tx failed with code %d: %w" , res .TxResult .Code , err )
6567		}
6668
6769		return  nil 
@@ -83,13 +85,14 @@ func NewSessionUsageSyncWithBlockchainWorker(c *nodecontext.Context, interval ti
8385
8486// NewSessionUsageSyncWithDatabaseWorker creates a worker that updates session usage in the database. 
8587// This worker fetches usage data from the peer service and updates the corresponding database records. 
86- func  NewSessionUsageSyncWithDatabaseWorker (c  * nodecontext .Context , interval  time.Duration ) cron.Worker  {
88+ func  NewSessionUsageSyncWithDatabaseWorker (c  * context .Context , interval  time.Duration ) cron.Worker  {
8789	log  :=  logger .With ("name" , nameSessionUsageSyncWithDatabase )
8890
8991	handlerFunc  :=  func () error  {
9092		log .Info ("Running scheduler worker" )
9193
92- 		ctx , cancel  :=  context .WithTimeout (context .Background (), 5 * time .Second )
94+ 		// Create a context with a timeout to fetch peer statistics. 
95+ 		ctx , cancel  :=  gocontext .WithTimeout (gocontext .TODO (), 5 * time .Second )
9396		defer  cancel ()
9497
9598		// Fetch peer usage statistics from the service. 
@@ -103,19 +106,24 @@ func NewSessionUsageSyncWithDatabaseWorker(c *nodecontext.Context, interval time
103106
104107		// Update the database with the fetched statistics. 
105108		for  _ , item  :=  range  items  {
109+ 			// Convert usage statistics to strings for database storage. 
106110			downloadBytes  :=  math .NewInt (item .DownloadBytes ).String ()
107111			uploadBytes  :=  math .NewInt (item .UploadBytes ).String ()
108112
113+ 			// Define query to find the session by peer key. 
109114			query  :=  map [string ]interface {}{
110115				"peer_key" : item .Key ,
111116			}
117+ 
118+ 			// Define updates to apply to the session record. 
112119			updates  :=  map [string ]interface {}{
113120				"download_bytes" : downloadBytes ,
114121				"upload_bytes" :   uploadBytes ,
115122			}
116123
124+ 			// Update the session in the database. 
117125			if  _ , err  :=  operations .SessionFindOneAndUpdate (c .Database (), query , updates ); err  !=  nil  {
118- 				return  fmt .Errorf ("failed to update session: %w" , err )
126+ 				return  fmt .Errorf ("failed to update session with peer key %s : %w" ,  item . Key , err )
119127			}
120128		}
121129
@@ -138,7 +146,7 @@ func NewSessionUsageSyncWithDatabaseWorker(c *nodecontext.Context, interval time
138146
139147// NewSessionUsageValidateWorker creates a worker that validates session usage limits and removes peers if necessary. 
140148// This worker checks if sessions exceed their maximum byte or duration limits and removes peers accordingly. 
141- func  NewSessionUsageValidateWorker (c  * nodecontext .Context , interval  time.Duration ) cron.Worker  {
149+ func  NewSessionUsageValidateWorker (c  * context .Context , interval  time.Duration ) cron.Worker  {
142150	log  :=  logger .With ("name" , nameSessionUsageValidate )
143151
144152	handlerFunc  :=  func () error  {
@@ -147,7 +155,7 @@ func NewSessionUsageValidateWorker(c *nodecontext.Context, interval time.Duratio
147155		// Retrieve session records from the database. 
148156		items , err  :=  operations .SessionFind (c .Database (), nil )
149157		if  err  !=  nil  {
150- 			return  fmt .Errorf ("failed to retrieve sessions from database: %w" , err )
158+ 			return  fmt .Errorf ("failed to retrieve sessions from the  database: %w" , err )
151159		}
152160		if  len (items ) ==  0  {
153161			return  nil 
@@ -157,16 +165,22 @@ func NewSessionUsageValidateWorker(c *nodecontext.Context, interval time.Duratio
157165		for  _ , item  :=  range  items  {
158166			removePeer  :=  false 
159167
160- 			if  item .GetBytes ().GTE (item .GetMaxBytes ()) {
168+ 			// Check if the session exceeds the maximum allowed bytes. 
169+ 			maxBytes  :=  item .GetMaxBytes ()
170+ 			if  ! maxBytes .IsZero () &&  item .GetBytes ().GTE (maxBytes ) {
161171				removePeer  =  true 
162172			}
163- 			if  item .GetDuration () >=  item .GetMaxDuration () {
173+ 
174+ 			// Check if the session exceeds the maximum allowed duration. 
175+ 			maxDuration  :=  item .GetMaxDuration ()
176+ 			if  maxDuration  !=  0  &&  item .GetDuration () >=  maxDuration  {
164177				removePeer  =  true 
165178			}
166179
180+ 			// Remove the peer if validation fails. 
167181			if  removePeer  {
168- 				if  err  :=  c .RemovePeerIfExistsForKey (context .TODO (), item .PeerKey ); err  !=  nil  {
169- 					return  fmt .Errorf ("failed to remove peer: %w" , err )
182+ 				if  err  :=  c .RemovePeerIfExistsForKey (gocontext .TODO (), item .PeerKey ); err  !=  nil  {
183+ 					return  fmt .Errorf ("failed to remove peer with key %s : %w" ,  item . PeerKey , err )
170184				}
171185			}
172186		}
@@ -190,7 +204,7 @@ func NewSessionUsageValidateWorker(c *nodecontext.Context, interval time.Duratio
190204
191205// NewSessionValidateWorker creates a worker that validates session status and removes peers if necessary. 
192206// This worker ensures sessions are active and consistent between the database and blockchain. 
193- func  NewSessionValidateWorker (c  * nodecontext .Context , interval  time.Duration ) cron.Worker  {
207+ func  NewSessionValidateWorker (c  * context .Context , interval  time.Duration ) cron.Worker  {
194208	log  :=  logger .With ("name" , nameSessionValidate )
195209
196210	handlerFunc  :=  func () error  {
@@ -199,23 +213,23 @@ func NewSessionValidateWorker(c *nodecontext.Context, interval time.Duration) cr
199213		// Retrieve session records from the database. 
200214		items , err  :=  operations .SessionFind (c .Database (), nil )
201215		if  err  !=  nil  {
202- 			return  fmt .Errorf ("failed to retrieve sessions from database: %w" , err )
216+ 			return  fmt .Errorf ("failed to retrieve sessions from the  database: %w" , err )
203217		}
204218		if  len (items ) ==  0  {
205219			return  nil 
206220		}
207221
208222		// Validate session status and consistency. 
209223		for  _ , item  :=  range  items  {
210- 			session , err  :=  c .Client ().Session (context .TODO (), item .GetID ())
224+ 			session , err  :=  c .Client ().Session (gocontext .TODO (), item .GetID ())
211225			if  err  !=  nil  {
212- 				return  fmt .Errorf ("failed to query session: %w" , err )
226+ 				return  fmt .Errorf ("failed to query session from the blockchain : %w" , err )
213227			}
214228
215229			// Remove peers if sessions are inactive or missing on the blockchain. 
216230			if  session  ==  nil  ||  ! session .GetStatus ().Equal (v1 .StatusActive ) {
217- 				if  err  :=  c .RemovePeerIfExistsForKey (context .TODO (), item .PeerKey ); err  !=  nil  {
218- 					return  fmt .Errorf ("failed to remove peer: %w" , err )
231+ 				if  err  :=  c .RemovePeerIfExistsForKey (gocontext .TODO (), item .PeerKey ); err  !=  nil  {
232+ 					return  fmt .Errorf ("failed to remove peer with key %s : %w" ,  item . PeerKey , err )
219233				}
220234			}
221235
@@ -224,8 +238,9 @@ func NewSessionValidateWorker(c *nodecontext.Context, interval time.Duration) cr
224238				query  :=  map [string ]interface {}{
225239					"id" : item .ID ,
226240				}
241+ 
227242				if  _ , err  :=  operations .SessionFindOneAndDelete (c .Database (), query ); err  !=  nil  {
228- 					return  fmt .Errorf ("failed to delete session: %w" , err )
243+ 					return  fmt .Errorf ("failed to delete session %d : %w" ,  item . ID , err )
229244				}
230245			}
231246		}
0 commit comments