@@ -8,31 +8,44 @@ import {
8
8
import type { Env } from "./Env"
9
9
import { GoogleKeepBot } from "./google-keep-bot"
10
10
11
- const SYNC_INTERVAL = 10_000
11
+ const SHORT_SYNC_INTERVAL = 1000 * 10 // Every 10 seconds
12
+ const LONG_SYNC_INTERVAL = 1000 * 60 * 3 // Every 3 minutes
12
13
13
14
export class TinyDO extends WsServerDurableObject < Env > {
14
15
tinybaseStore = createMergeableStore ( )
15
16
shoppingList = createTinybaseClient ( this . tinybaseStore )
16
- interval : ReturnType < typeof setInterval > | undefined
17
+
18
+ hasConnectedClients = false
19
+ get currentInterval ( ) {
20
+ return this . hasConnectedClients ? SHORT_SYNC_INTERVAL : LONG_SYNC_INTERVAL
21
+ }
22
+
23
+ createPersister ( ) {
24
+ return createDurableObjectStoragePersister ( this . tinybaseStore , this . ctx . storage )
25
+ }
17
26
18
27
onPathId ( pathId : Id , addedOrRemoved : IdAddedOrRemoved ) {
19
- if ( this . interval ) {
20
- clearInterval ( this . interval )
21
- this . interval = undefined
22
- }
28
+ if ( addedOrRemoved > 0 !== this . hasConnectedClients ) {
29
+ this . hasConnectedClients = addedOrRemoved > 0
30
+
31
+ const { shouldSyncImmediate, logLine } = this . hasConnectedClients
32
+ ? { shouldSyncImmediate : true , logLine : "Client connected" }
33
+ : { shouldSyncImmediate : false , logLine : "All clients disconnected" }
34
+
35
+ console . log ( `${ logLine } . Setting sync interval to ${ this . currentInterval / 1000 } s` )
36
+ this . ctx . storage . setAlarm ( Date . now ( ) + this . currentInterval )
23
37
24
- // Enable syncing on an interval when there are clients connectect
25
- if ( addedOrRemoved > 0 ) {
26
- this . interval = setInterval ( ( ) => this . sync ( ) , SYNC_INTERVAL )
27
- this . sync ( )
38
+ if ( shouldSyncImmediate ) this . sync ( )
28
39
}
29
40
}
30
41
31
- createPersister ( ) {
32
- return createDurableObjectStoragePersister ( this . tinybaseStore , this . ctx . storage )
42
+ async alarm ( alarmInfo ?: AlarmInvocationInfo ) {
43
+ this . ctx . storage . setAlarm ( Date . now ( ) + this . currentInterval )
44
+ await this . sync ( )
33
45
}
34
46
35
47
async sync ( ) {
48
+ console . log ( "Sync initiated" )
36
49
const keepBot = new GoogleKeepBot ( this . env . KEEP_SHOPPING_LIST_ID )
37
50
await keepBot . authenticate ( { email : this . env . KEEP_EMAIL , masterKey : this . env . KEEP_MASTER_KEY } )
38
51
0 commit comments