Notes/src/services/task_context.ts

81 lines
2.5 KiB
TypeScript
Raw Normal View History

"use strict";
import { TaskData } from './task_context_interface.js';
import ws from "./ws.js";
// taskId => TaskContext
const taskContexts: Record<string, TaskContext> = {};
class TaskContext {
private taskId: string;
private taskType: string | null;
private progressCount: number;
private lastSentCountTs: number;
2024-02-25 14:52:20 +02:00
data: TaskData | null;
2024-02-17 10:56:27 +02:00
noteDeletionHandlerTriggered: boolean;
constructor(taskId: string, taskType: string | null = null, data: {} | null = {}) {
this.taskId = taskId;
this.taskType = taskType;
this.data = data;
this.noteDeletionHandlerTriggered = false;
// progressCount is meant to represent just some progress - to indicate the task is not stuck
this.progressCount = -1; // we're incrementing immediately
2023-06-30 11:18:34 +02:00
this.lastSentCountTs = 0; // 0 will guarantee the first message will be sent
// just the fact this has been initialized is a progress which should be sent to clients
2023-06-30 11:18:34 +02:00
// this is esp. important when importing big files/images which take a long time to upload/process
// which means that first "real" increaseProgressCount() will be called quite late and user is without
// feedback until then
this.increaseProgressCount();
}
static getInstance(taskId: string, taskType: string, data: {} | null = null): TaskContext {
if (!taskContexts[taskId]) {
2019-10-18 23:19:16 +02:00
taskContexts[taskId] = new TaskContext(taskId, taskType, data);
}
return taskContexts[taskId];
}
2019-10-28 18:42:22 +01:00
increaseProgressCount() {
this.progressCount++;
2021-12-21 16:12:59 +01:00
if (Date.now() - this.lastSentCountTs >= 300 && this.taskId !== 'no-progress-reporting') {
this.lastSentCountTs = Date.now();
2019-10-28 18:42:22 +01:00
ws.sendMessageToAllClients({
2021-04-24 11:39:44 +02:00
type: 'taskProgressCount',
taskId: this.taskId,
taskType: this.taskType,
data: this.data,
progressCount: this.progressCount
});
}
}
reportError(message: string) {
2019-10-28 18:42:22 +01:00
ws.sendMessageToAllClients({
2021-04-24 11:39:44 +02:00
type: 'taskError',
taskId: this.taskId,
taskType: this.taskType,
data: this.data,
message: message
});
}
2024-04-06 21:30:27 +03:00
taskSucceeded(result?: string | Record<string, string | undefined>) {
2019-10-28 18:42:22 +01:00
ws.sendMessageToAllClients({
2021-04-24 11:39:44 +02:00
type: 'taskSucceeded',
taskId: this.taskId,
taskType: this.taskType,
data: this.data,
2019-10-19 00:11:07 +02:00
result: result
});
}
}
export default TaskContext;