Skip to content

Commit e82e1da

Browse files
committed
Schedule syncs when no clients are connected
1 parent c8b37a7 commit e82e1da

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

packages/server/src/worker.ts

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,44 @@ import {
88
import type { Env } from "./Env"
99
import { GoogleKeepBot } from "./google-keep-bot"
1010

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
1213

1314
export class TinyDO extends WsServerDurableObject<Env> {
1415
tinybaseStore = createMergeableStore()
1516
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+
}
1726

1827
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)
2337

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()
2839
}
2940
}
3041

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()
3345
}
3446

3547
async sync() {
48+
console.log("Sync initiated")
3649
const keepBot = new GoogleKeepBot(this.env.KEEP_SHOPPING_LIST_ID)
3750
await keepBot.authenticate({ email: this.env.KEEP_EMAIL, masterKey: this.env.KEEP_MASTER_KEY })
3851

0 commit comments

Comments
 (0)