fix: retry requests to collaborator in case of failure (#6468)

Signed-off-by: Alexander Onnikov <Alexander.Onnikov@xored.com>
This commit is contained in:
Alexander Onnikov 2024-09-03 17:07:24 +07:00 committed by GitHub
parent a99d420011
commit e7a893cd4b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -69,6 +69,10 @@ class CollaboratorClientImpl implements CollaboratorClient {
body: JSON.stringify({ method, documentId, payload })
})
if (!res.ok) {
throw new Error('HTTP error ' + res.status)
}
const result = await res.json()
if (result.error != null) {
@ -79,12 +83,24 @@ class CollaboratorClientImpl implements CollaboratorClient {
}
async getContent (document: CollaborativeDoc): Promise<Record<string, Markup>> {
const res = (await this.rpc(document, 'getContent', {})) as GetContentResponse
const res = await retry(
3,
async () => {
return (await this.rpc(document, 'getContent', {})) as GetContentResponse
},
50
)
return res.content ?? {}
}
async updateContent (document: CollaborativeDoc, content: Record<string, Markup>): Promise<void> {
await retry(
3,
async () => {
await this.rpc(document, 'updateContent', { content })
},
50
)
}
async copyContent (source: CollaborativeDoc, target: CollaborativeDoc): Promise<void> {
@ -92,3 +108,19 @@ class CollaboratorClientImpl implements CollaboratorClient {
await this.updateContent(target, content)
}
}
async function retry<T> (retries: number, op: () => Promise<T>, delay: number = 100): Promise<T> {
let error: any
while (retries > 0) {
retries--
try {
return await op()
} catch (err: any) {
error = err
if (retries !== 0) {
await new Promise((resolve) => setTimeout(resolve, delay))
}
}
}
throw error
}