Fix duplicated gmail sync on startup (#9590)

Signed-off-by: Artem Savchenko <armisav@gmail.com>
This commit is contained in:
Artyom Savchenko
2025-07-23 19:05:01 +07:00
committed by GitHub
parent f080dfbf66
commit fed9ef4e5a
2 changed files with 40 additions and 9 deletions
+34 -7
View File
@@ -102,6 +102,7 @@ export class GmailClient {
private readonly syncManager: SyncManager
private readonly integrationToken: string
private integration: Integration | undefined = undefined
private syncStarted: boolean = false
private constructor (
private readonly ctx: MeasureContext,
@@ -388,13 +389,34 @@ export class GmailClient {
}
async startSync (): Promise<void> {
this.ctx.info('Start sync', { workspaceUuid: this.user.workspace, userId: this.user.userId, email: this.email })
await this.syncManager.sync(this.socialId._id, { noNotify: true }, this.email)
await this.watch()
// recall every 24 hours https://developers.google.com/gmail/api/guides/push
this.watchTimer = setInterval(() => {
void this.watch()
}, 86400000)
if (this.syncStarted) {
this.ctx.info('Sync already started, skipping duplicate call', {
workspaceUuid: this.user.workspace,
userId: this.user.userId,
email: this.email
})
return
}
try {
this.syncStarted = true
this.ctx.info('Start sync', { workspaceUuid: this.user.workspace, userId: this.user.userId, email: this.email })
await this.syncManager.sync(this.socialId._id, { noNotify: true }, this.email)
await this.watch()
// recall every 24 hours https://developers.google.com/gmail/api/guides/push
if (this.watchTimer !== undefined) clearInterval(this.watchTimer)
this.watchTimer = setInterval(() => {
void this.watch()
}, 86400000)
} catch (err: any) {
this.ctx.error('Failed to start sync', {
workspaceUuid: this.user.workspace,
userId: this.user.userId,
email: this.email,
error: err.message
})
this.syncStarted = false
}
}
async sync (options: SyncOptions): Promise<void> {
@@ -533,6 +555,11 @@ export class GmailClient {
topicName: config.WATCH_TOPIC_NAME
}
})
this.ctx.info('Gmail watch established successfully', {
workspaceUuid: this.user.workspace,
userId: this.user.userId,
topicName: config.WATCH_TOPIC_NAME
})
} catch (err) {
this.ctx.error('Watch error', {
workspaceUuid: this.user.workspace,
@@ -70,8 +70,12 @@ export class WorkspaceClient {
async createGmailClient (user: User, authCode?: string): Promise<GmailClient> {
const current = user.socialId?._id !== undefined ? this.getGmailClient(user.socialId?._id) : undefined
if (current !== undefined) return current
this.ctx.info('Creating new gmail client', { workspaceUuid: this.workspace, userId: user.userId })
this.ctx.info('Creating new gmail user', { user })
this.ctx.info('Creating new gmail client', {
workspaceUuid: this.workspace,
userId: user.userId,
email: user.email,
socialId: user.socialId?._id
})
const newClient = await GmailClient.create(
this.ctx,
this.credentials,