From 6e5b8f5ebf376ead99519887e184dbe79fc8ba9f Mon Sep 17 00:00:00 2001 From: Anton Vakhrushev Date: Sun, 29 Mar 2020 15:56:33 +0300 Subject: [PATCH] Add rescheduling --- src/Errors.ts | 6 ++++-- src/Scheduler.ts | 2 ++ src/Storage/ActionQueue.ts | 4 ++++ src/Storage/TaskQueue.ts | 19 +++++++++++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/Errors.ts b/src/Errors.ts index bbb27c6..d092f4c 100644 --- a/src/Errors.ts +++ b/src/Errors.ts @@ -1,7 +1,9 @@ export class TryLaterError extends Error { readonly seconds: number; - constructor(s: number) { - super(); + constructor(s: number, msg: string = '') { + super(msg); this.seconds = s; + // Set the prototype explicitly. + Object.setPrototypeOf(this, TryLaterError.prototype); } } diff --git a/src/Scheduler.ts b/src/Scheduler.ts index acc71ab..5ecc4ec 100644 --- a/src/Scheduler.ts +++ b/src/Scheduler.ts @@ -96,6 +96,8 @@ export default class Scheduler { console.warn('ACTION ERROR', e); if (e instanceof TryLaterError) { console.warn('TRY AFTER', e.seconds); + this.actionQueue.clear(); + this.taskQueue.postpone(e.seconds); } } } diff --git a/src/Storage/ActionQueue.ts b/src/Storage/ActionQueue.ts index d3208c4..80e0fe4 100644 --- a/src/Storage/ActionQueue.ts +++ b/src/Storage/ActionQueue.ts @@ -35,6 +35,10 @@ export default class ActionQueue { this.flushState(new State(items)); } + clear(): void { + this.flushState(new State([])); + } + private getState(): State { const serialized = localStorage.getItem(QUEUE_NAME); if (serialized === null) { diff --git a/src/Storage/TaskQueue.ts b/src/Storage/TaskQueue.ts index 154121a..3dae52d 100644 --- a/src/Storage/TaskQueue.ts +++ b/src/Storage/TaskQueue.ts @@ -37,6 +37,16 @@ class State { } return new State(first, items); } + + postpone(ds: number): State { + const current = this.current; + let items = this.items.slice(); + if (current) { + const cmd = new CommandWithTime(current.cmd, current.ts + ds); + items.push(cmd); + } + return new State(null, items); + } } export default class TaskQueue { @@ -58,6 +68,15 @@ export default class TaskQueue { return current; } + postpone(ds: number) { + const state = this.getState().postpone(ds); + this.flushState(state); + } + + state(): State { + return this.getState(); + } + private defaultTs(): number { return Math.floor(Date.now() / 1000); }