Compare commits

...
13 Commits
Author SHA1 Message Date
Zaid Abdulla 91d7152ca7 1.2.2 2020-10-03 00:37:35 -07:00
Zaid Abdulla 3fccc1d8a4 Changelog for v1.2.2 2020-10-03 00:36:59 -07:00
Zaid Abdulla 5bb6f60c4d Update dependencies and fix new lint errors 2020-10-02 23:21:07 -07:00
Zaid Abdulla c2f002b95a Better ordering of config YAML 2020-10-02 14:50:17 -07:00
Zaid Abdulla c55a256d52 Show proper login failure message 2020-09-30 15:43:55 -07:00
Zaid Abdulla 3fc0b1740d Limit max page size 2020-09-28 12:47:56 -07:00
Zaid Abdulla 1956441d52 Limit number of tasks in queue 2020-09-28 12:47:15 -07:00
Zaid Abdulla 01e01dae69 Set max height for task queue 2020-09-28 12:40:55 -07:00
Zaid Abdulla f14e6ceb97 Bulk push file from device list page 2020-09-27 11:20:30 -07:00
Zaid Abdulla 82124d471e Fix invalid arguments fault in refresh preset
Happens when upgrading from v1.1 where genieacs-gui creates refresh
configuration with 'age' passed as a string.
2020-09-23 23:15:00 -07:00
Zaid Abdulla 9286bd6aa0 Fix unhandled promise rejections 2020-09-17 17:00:41 -07:00
Zaid Abdulla 328bfa03e0 Allow refreshObject task on root param 2020-09-15 12:50:02 -07:00
Zaid Abdulla de65ca0921 Fix crash when deserializing operation objects 2020-09-14 15:58:47 -07:00
21 changed files with 2403 additions and 980 deletions

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# Change Log # Change Log
## 1.2.2 (2020-10-03)
- Added button to push files to selected devices from device listing page.
- A few minor UI improvements.
- Fix exception that can happen and persist after a Download request.
- Fix validation bug preventing running refreshObject task on data model root.
- Fix invalid arguments fault in refresh preset configuration when upgrading
from v1.1.
## 1.2.1 (2020-09-08) ## 1.2.1 (2020-09-08)
- Fix bug causing faults to not be displayed in the UI. - Fix bug causing faults to not be displayed in the UI.
- Fix bug where deleting objects does not get reflected immediately in the UI. - Fix bug where deleting objects does not get reflected immediately in the UI.
+4
View File
@@ -236,6 +236,10 @@ function sanitizeTask(task): void {
break; break;
case "refreshObject": case "refreshObject":
if (typeof task.objectName !== "string")
throw new Error("Missing 'objectName' property");
break;
case "deleteObject": case "deleteObject":
if (typeof task.objectName !== "string" || !task.objectName.length) if (typeof task.objectName !== "string" || !task.objectName.length)
throw new Error("Missing 'objectName' property"); throw new Error("Missing 'objectName' property");
+2 -2
View File
@@ -42,7 +42,7 @@ function interpretEscapes(str): string {
export function map( export function map(
exp: Expression, exp: Expression,
callback: (exp: Expression) => Expression callback: (e: Expression) => Expression
): Expression { ): Expression {
if (!Array.isArray(exp)) return callback(exp); if (!Array.isArray(exp)) return callback(exp);
@@ -60,7 +60,7 @@ export function map(
export async function mapAsync( export async function mapAsync(
exp: Expression, exp: Expression,
callback: (exp: Expression) => Promise<Expression> callback: (e: Expression) => Promise<Expression>
): Promise<Expression> { ): Promise<Expression> {
if (!Array.isArray(exp)) return callback(exp); if (!Array.isArray(exp)) return callback(exp);
+9 -9
View File
@@ -264,21 +264,21 @@ export function evaluateCallback(exp: Expression): Expression {
export function evaluate( export function evaluate(
exp: Expression, exp: Expression,
obj: Record<string, unknown> | ((exp: string) => Expression), obj: Record<string, unknown> | ((e: string) => Expression),
now: number, now: number,
cb?: (exp: Expression) => Expression cb?: (e: Expression) => Expression
): string | number | boolean | null; ): string | number | boolean | null;
export function evaluate( export function evaluate(
exp: Expression, exp: Expression,
obj?: Record<string, unknown> | ((exp: string) => Expression), obj?: Record<string, unknown> | ((e: string) => Expression),
now?: number, now?: number,
cb?: (exp: Expression) => Expression cb?: (e: Expression) => Expression
): Expression; ): Expression;
export function evaluate( export function evaluate(
exp: Expression, exp: Expression,
obj?: Record<string, unknown> | ((exp: string) => Expression), obj?: Record<string, unknown> | ((e: string) => Expression),
now?: number, now?: number,
cb?: (exp: Expression) => Expression cb?: (e: Expression) => Expression
): Expression { ): Expression {
return map(exp, (e) => { return map(exp, (e) => {
if (cb) e = cb(e); if (cb) e = cb(e);
@@ -306,19 +306,19 @@ export async function evaluateAsync(
exp: Expression, exp: Expression,
obj: Record<string, unknown>, obj: Record<string, unknown>,
now: number, now: number,
cb?: (exp: Expression) => Promise<Expression> cb?: (e: Expression) => Promise<Expression>
): Promise<string | number | boolean | null>; ): Promise<string | number | boolean | null>;
export async function evaluateAsync( export async function evaluateAsync(
exp: Expression, exp: Expression,
obj?: Record<string, unknown>, obj?: Record<string, unknown>,
now?: number, now?: number,
cb?: (exp: Expression) => Promise<Expression> cb?: (e: Expression) => Promise<Expression>
): Promise<Expression>; ): Promise<Expression>;
export async function evaluateAsync( export async function evaluateAsync(
exp: Expression, exp: Expression,
obj?: Record<string, unknown>, obj?: Record<string, unknown>,
now?: number, now?: number,
cb?: (exp: Expression) => Promise<Expression> cb?: (e: Expression) => Promise<Expression>
): Promise<Expression> { ): Promise<Expression> {
return mapAsync(exp, async (e) => { return mapAsync(exp, async (e) => {
if (cb) e = await cb(e); if (cb) e = await cb(e);
+7 -2
View File
@@ -1211,12 +1211,17 @@ export function listener(
}) })
.catch((err) => { .catch((err) => {
currentSessions.delete(httpResponse.connection); currentSessions.delete(httpResponse.connection);
httpResponse.writeHead(500, { Connection: "close" });
httpResponse.end(`${err.name}: ${err.message}`);
stats.concurrentRequests -= 1; stats.concurrentRequests -= 1;
setTimeout(() => { setTimeout(() => {
throw err; throw err;
}); });
try {
httpResponse.connection.unref();
httpResponse.writeHead(500, { Connection: "close" });
httpResponse.end(`${err.name}: ${err.message}`);
} catch (err) {
// Ignore
}
}); });
} }
+6 -1
View File
@@ -691,6 +691,11 @@ export async function getOperations(
for (const r of res) { for (const r of res) {
const commandKey = r._id.slice(deviceId.length + 1); const commandKey = r._id.slice(deviceId.length + 1);
delete r._id; delete r._id;
// Workaround for a bug in v1.2.1 where operation object is saved without deserialization
if (typeof r.provisions !== "string") {
operations[commandKey] = r;
continue;
}
r.timestamp = +r.timestamp; r.timestamp = +r.timestamp;
if (r.args) r.args = JSON.parse(r.args); if (r.args) r.args = JSON.parse(r.args);
r.provisions = JSON.parse(r.provisions); r.provisions = JSON.parse(r.provisions);
@@ -712,7 +717,7 @@ export async function saveOperation(
o["provisions"] = JSON.stringify(operation.provisions); o["provisions"] = JSON.stringify(operation.provisions);
o["retries"] = JSON.stringify(operation.retries); o["retries"] = JSON.stringify(operation.retries);
o["args"] = JSON.stringify(operation.args); o["args"] = JSON.stringify(operation.args);
await operationsCollection.replaceOne({ _id: id }, operation, { await operationsCollection.replaceOne({ _id: id }, o, {
upsert: true, upsert: true,
}); });
} }
+2 -2
View File
@@ -188,7 +188,7 @@ async function fetchPresets(): Promise<Preset[]> {
for (const c of preset["configurations"]) { for (const c of preset["configurations"]) {
switch (c.type) { switch (c.type) {
case "age": case "age":
_provisions.push(["refresh", c.name, c.age]); _provisions.push(["refresh", c.name, +c.age]);
break; break;
case "value": case "value":
@@ -475,7 +475,7 @@ export function getConfig(
key: string, key: string,
context: Record<string, unknown>, context: Record<string, unknown>,
now: number, now: number,
cb?: (Expression) => Expression cb?: (e: Expression) => Expression
): string | number | boolean | null { ): string | number | boolean | null {
const snapshot = snapshots.get(snapshotKey); const snapshot = snapshots.get(snapshotKey);
if (!snapshot) throw new Error("Cache snapshot does not exist"); if (!snapshot) throw new Error("Cache snapshot does not exist");
+3 -1
View File
@@ -60,7 +60,9 @@ const getAuthorizer = memoize(
); );
koa.on("error", async (err) => { koa.on("error", async (err) => {
throw err; setTimeout(() => {
throw err;
});
}); });
koa.use(async (ctx, next) => { koa.use(async (ctx, next) => {
-10
View File
@@ -145,16 +145,6 @@ export async function postTasks(
return { connectionRequest: "OK", tasks: statuses }; return { connectionRequest: "OK", tasks: statuses };
} }
interface PingResponse {
packetsTransmitted: number;
packetsReceived: number;
packetLoss: string;
min: number;
avg: number;
max: number;
mdev: number;
}
export async function putResource( export async function putResource(
resource: string, resource: string,
id: string, id: string,
+2143 -842
View File
File diff suppressed because it is too large. Load diff
+20 -20
View File
@@ -1,6 +1,6 @@
{ {
"name": "genieacs", "name": "genieacs",
"version": "1.2.1", "version": "1.2.2",
"description": "A TR-069 Auto Configuration Server (ACS)", "description": "A TR-069 Auto Configuration Server (ACS)",
"repository": { "repository": {
"type": "git", "type": "git",
@@ -31,47 +31,47 @@
"koa-router": "^9.4.0", "koa-router": "^9.4.0",
"koa-static": "^5.0.0", "koa-static": "^5.0.0",
"later": "^1.2.0", "later": "^1.2.0",
"mongodb": "^3.6.1", "mongodb": "^3.6.2",
"parsimmon": "^1.16.0", "parsimmon": "^1.16.0",
"seedrandom": "^3.0.5", "seedrandom": "^3.0.5",
"yaml": "^1.10.0" "yaml": "^1.10.0"
}, },
"devDependencies": { "devDependencies": {
"@rollup/plugin-commonjs": "^15.0.0", "@rollup/plugin-commonjs": "^15.1.0",
"@rollup/plugin-json": "^4.1.0", "@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^9.0.0", "@rollup/plugin-node-resolve": "^9.0.0",
"@rollup/plugin-typescript": "^5.0.2", "@rollup/plugin-typescript": "^6.0.0",
"@types/jsonwebtoken": "^8.5.0", "@types/jsonwebtoken": "^8.5.0",
"@types/koa": "^2.11.4", "@types/koa": "^2.11.4",
"@types/koa-compress": "^4.0.0", "@types/koa-compress": "^4.0.1",
"@types/koa-router": "^7.4.1", "@types/koa-router": "^7.4.1",
"@types/koa-static": "^4.0.1", "@types/koa-static": "^4.0.1",
"@types/mithril": "^2.0.3", "@types/mithril": "^2.0.4",
"@types/mongodb": "^3.5.27", "@types/mongodb": "^3.5.27",
"@types/parsimmon": "^1.10.2", "@types/parsimmon": "^1.10.3",
"@types/seedrandom": "^2.4.28", "@types/seedrandom": "^2.4.28",
"@types/svgo": "^1.3.3", "@types/svgo": "^1.3.3",
"@typescript-eslint/eslint-plugin": "^3.10.1", "@typescript-eslint/eslint-plugin": "^4.3.0",
"@typescript-eslint/parser": "^3.10.1", "@typescript-eslint/parser": "^4.3.0",
"ava": "^3.12.1", "ava": "^3.13.0",
"codemirror": "^5.57.0", "codemirror": "^5.58.1",
"cssnano": "^4.1.10", "cssnano": "^4.1.10",
"eslint": "^7.8.0", "eslint": "^7.10.0",
"eslint-config-prettier": "^6.11.0", "eslint-config-prettier": "^6.12.0",
"esm": "^3.2.25", "esm": "^3.2.25",
"jsbi": "^3.1.3", "jsbi": "^3.1.4",
"mithril": "^2.0.4", "mithril": "^2.0.4",
"postcss": "^7.0.32", "postcss": "^8.1.1",
"postcss-import": "^12.0.1", "postcss-import": "^12.0.1",
"postcss-preset-env": "^6.7.0", "postcss-preset-env": "^6.7.0",
"prettier": "^2.1.1", "prettier": "^2.1.2",
"rollup": "^2.26.9", "rollup": "^2.28.2",
"rollup-plugin-terser": "^7.0.1", "rollup-plugin-terser": "^7.0.2",
"source-map-loader": "^1.1.0", "source-map-loader": "^1.1.0",
"svgo": "^1.3.2", "svgo": "^1.3.2",
"ts-node": "^9.0.0", "ts-node": "^9.0.0",
"typescript": "^4.0.2", "typescript": "^4.0.3",
"webpack": "^4.44.1" "webpack": "^4.44.2"
}, },
"engines": { "engines": {
"node": ">=12.13.0" "node": ">=12.13.0"
+1 -1
View File
@@ -70,7 +70,7 @@ const component: ClosureComponent = (): Component => {
onclick: () => { onclick: () => {
taskQueue.stageDownload({ taskQueue.stageDownload({
name: "download", name: "download",
device: device["DeviceID.ID"].value[0], devices: [device["DeviceID.ID"].value[0]],
}); });
}, },
}, },
+1 -1
View File
@@ -90,7 +90,7 @@ const component: ClosureComponent = (): Component => {
onclick: () => { onclick: () => {
taskQueue.stageSpv({ taskQueue.stageSpv({
name: "setParameterValues", name: "setParameterValues",
device: device["DeviceID.ID"].value[0], devices: [device["DeviceID.ID"].value[0]],
parameterValues: [ parameterValues: [
[ [
parameter, parameter,
+2 -1
View File
@@ -81,7 +81,8 @@ const component: ClosureComponent = (): Component => {
store.fulfill(0, Date.now()); store.fulfill(0, Date.now());
}) })
.catch((err) => { .catch((err) => {
throw err; e.target.disabled = false;
notifications.push("error", err.message);
}); });
}, },
}, },
+32 -1
View File
@@ -42,6 +42,35 @@ export function flattenConfig(config: Record<string, unknown>): any {
return flatten; return flatten;
} }
// Order keys such that nested objects come last
function orderKeys(config: any): number {
let res = 1;
if (typeof config !== "object") return res;
if (Array.isArray(config)) {
for (const c of config) res += orderKeys(c);
return res;
}
const weights: [string, number][] = Object.entries(config).map(([k, v]) => [
k,
orderKeys(v),
]);
weights.sort((a, b) => {
if (a[1] !== b[1]) return a[1] - b[1];
if (b[0] > a[0]) return -1;
else return 1;
});
for (const [k, w] of weights) {
res += w;
const v = config[k];
delete config[k];
config[k] = v;
}
return res;
}
export function structureConfig(config: Config[]): any { export function structureConfig(config: Config[]): any {
config.sort((a, b) => (a._id > b._id ? 1 : a._id < b._id ? -1 : 0)); config.sort((a, b) => (a._id > b._id ? 1 : a._id < b._id ? -1 : 0));
const _config = {}; const _config = {};
@@ -93,7 +122,9 @@ export function structureConfig(config: Config[]): any {
return object; return object;
}; };
return toArray(_config); const res = toArray(_config);
orderKeys(res);
return res;
} }
export function diffConfig( export function diffConfig(
+2
View File
@@ -178,6 +178,8 @@ body {
} }
& > .queue { & > .queue {
max-height: 400px;
overflow-y: auto;
& > .pending { & > .pending {
animation: 0.5s linear 0s infinite alternate pending-blink; animation: 0.5s linear 0s infinite alternate pending-blink;
border-radius: 0.4em; border-radius: 0.4em;
+28 -13
View File
@@ -23,7 +23,7 @@ import config from "./config";
import indexTableComponent from "./index-table-component"; import indexTableComponent from "./index-table-component";
import filterComponent from "./filter-component"; import filterComponent from "./filter-component";
import * as store from "./store"; import * as store from "./store";
import * as taskQueue from "./task-queue"; import { queueTask, stageDownload } from "./task-queue";
import * as notifications from "./notifications"; import * as notifications from "./notifications";
import { parse, stringify } from "../lib/common/expression-parser"; import { parse, stringify } from "../lib/common/expression-parser";
import { evaluate, extractParams } from "../lib/common/expression"; import { evaluate, extractParams } from "../lib/common/expression";
@@ -91,12 +91,11 @@ function renderActions(selected: Set<string>): Children {
title: "Reboot selected devices", title: "Reboot selected devices",
disabled: !selected.size, disabled: !selected.size,
onclick: () => { onclick: () => {
for (const d of selected) { const tasks = [...selected].map((s) => ({
taskQueue.queueTask({ name: "reboot",
name: "reboot", device: s,
device: d, }));
}); queueTask(...tasks);
}
}, },
}, },
"Reboot" "Reboot"
@@ -110,18 +109,34 @@ function renderActions(selected: Set<string>): Children {
title: "Factory reset selected devices", title: "Factory reset selected devices",
disabled: !selected.size, disabled: !selected.size,
onclick: () => { onclick: () => {
for (const d of selected) { const tasks = [...selected].map((s) => ({
taskQueue.queueTask({ name: "factoryReset",
name: "factoryReset", device: s,
device: d, }));
}); queueTask(...tasks);
}
}, },
}, },
"Reset" "Reset"
) )
); );
buttons.push(
m(
"button.critical",
{
title: "Push a firmware or a config file",
disabled: !selected.size,
onclick: () => {
stageDownload({
name: "download",
devices: [...selected],
});
},
},
"Push file"
)
);
buttons.push( buttons.push(
m( m(
"button.primary", "button.primary",
+83 -58
View File
@@ -24,10 +24,21 @@ import m, {
Component, Component,
VnodeDOM, VnodeDOM,
} from "mithril"; } from "mithril";
import * as taskQueue from "./task-queue";
import * as store from "./store"; import * as store from "./store";
import * as notifications from "./notifications"; import * as notifications from "./notifications";
import { getIcon } from "./icons"; import { getIcon } from "./icons";
import {
clear,
commit,
deleteTask,
getQueue,
getStaging,
QueueTask,
queueTask,
StageTask,
} from "./task-queue";
const invalid: WeakSet<StageTask> = new WeakSet();
function mparam(param): Children { function mparam(param): Children {
return m("span.parameter", { title: param }, `${param}`); return m("span.parameter", { title: param }, `${param}`);
@@ -37,7 +48,7 @@ function mval(val): Children {
return m("span.value", { title: val }, `${val}`); return m("span.value", { title: val }, `${val}`);
} }
function renderStagingSpv(task, queueFunc, cancelFunc): Children { function renderStagingSpv(task: StageTask, queueFunc, cancelFunc): Children {
function keydown(e): void { function keydown(e): void {
if (e.keyCode === 13) queueFunc(); if (e.keyCode === 13) queueFunc();
else if (e.keyCode === 27) cancelFunc(); else if (e.keyCode === 27) cancelFunc();
@@ -90,13 +101,24 @@ function renderStagingSpv(task, queueFunc, cancelFunc): Children {
return [m("span", "Editing ", mparam(task.parameterValues[0][0])), input]; return [m("span", "Editing ", mparam(task.parameterValues[0][0])), input];
} }
function renderStagingDownload(task): Children { function renderStagingDownload(task: StageTask): Children {
task.invalid = !task.fileName || !task.fileType; if (!task.fileName || !task.fileType) invalid.add(task);
else invalid.delete(task);
const files = store.fetch("files", true); const files = store.fetch("files", true);
const idParts = task.device.split("-"); let oui = "";
const oui = decodeURIComponent(idParts[0]); let productClass = "";
const productClass = for (const d of task.devices) {
idParts.length === 3 ? decodeURIComponent(idParts[1]) : ""; const parts = d.split("-");
if (oui === "") oui = parts[0];
else if (oui !== parts[0]) oui = null;
if (parts.length === 3) {
if (productClass === "") productClass = parts[1];
else if (productClass !== parts[1]) productClass = null;
}
}
if (oui) oui = decodeURIComponent(oui);
if (productClass) productClass = decodeURIComponent(productClass);
const typesList = [ const typesList = [
"", "",
@@ -162,13 +184,17 @@ function renderStagingDownload(task): Children {
]; ];
} }
function renderStaging(staging): Child[] { function renderStaging(staging: Set<StageTask>): Child[] {
const elements: Child[] = []; const elements: Child[] = [];
for (const s of staging) { for (const s of staging) {
const queueFunc = (): void => { const queueFunc = (): void => {
staging.delete(s); staging.delete(s);
taskQueue.queueTask(s); for (const d of s.devices) {
const t = Object.assign({ device: d }, s);
delete t.devices;
queueTask(t);
}
}; };
const cancelFunc = (): void => { const cancelFunc = (): void => {
staging.delete(s); staging.delete(s);
@@ -181,7 +207,7 @@ function renderStaging(staging): Child[] {
const queue = m( const queue = m(
"button.primary", "button.primary",
{ title: "Queue task", onclick: queueFunc, disabled: s.invalid }, { title: "Queue task", onclick: queueFunc, disabled: invalid.has(s) },
"Queue" "Queue"
); );
const cancel = m( const cancel = m(
@@ -195,7 +221,7 @@ function renderStaging(staging): Child[] {
return elements; return elements;
} }
function renderQueue(queue): Child[] { function renderQueue(queue: Set<QueueTask>): Child[] {
const details: Child[] = []; const details: Child[] = [];
const devices: { [deviceId: string]: any[] } = {}; const devices: { [deviceId: string]: any[] } = {};
for (const t of queue) { for (const t of queue) {
@@ -215,7 +241,7 @@ function renderQueue(queue): Child[] {
{ {
title: "Retry this task", title: "Retry this task",
onclick: () => { onclick: () => {
taskQueue.queueTask(t); queueTask(t);
}, },
}, },
getIcon("retry") getIcon("retry")
@@ -229,7 +255,7 @@ function renderQueue(queue): Child[] {
{ {
title: "Remove this task", title: "Remove this task",
onclick: () => { onclick: () => {
taskQueue.deleteTask(t); deleteTask(t);
}, },
}, },
getIcon("remove") getIcon("remove")
@@ -347,8 +373,8 @@ function renderNotifications(notifs): Child[] {
const component: ClosureComponent = (): Component => { const component: ClosureComponent = (): Component => {
return { return {
view: (vnode) => { view: (vnode) => {
const queue = taskQueue.getQueue(); const queue = getQueue();
const staging = taskQueue.getStaging(); const staging = getStaging();
const notifs = notifications.getNotifications(); const notifs = notifications.getNotifications();
let drawerElement, statusElement; let drawerElement, statusElement;
@@ -394,56 +420,55 @@ const component: ClosureComponent = (): Component => {
title: "Commit queued tasks", title: "Commit queued tasks",
disabled: !statusCount.queued, disabled: !statusCount.queued,
onclick: () => { onclick: () => {
const tasks = Array.from(taskQueue.getQueue()).filter( const tasks = Array.from(getQueue()).filter(
(t) => t["status"] === "queued" (t) => t["status"] === "queued"
); );
taskQueue commit(
.commit( tasks,
tasks, (deviceId, err, connectionRequestStatus, tasks2) => {
(deviceId, err, connectionRequestStatus, tasks2) => { if (err) {
if (err) {
notifications.push(
"error",
`${deviceId}: ${err.message}`
);
return;
}
if (connectionRequestStatus !== "OK") {
notifications.push(
"error",
`${deviceId}: ${connectionRequestStatus}`
);
return;
}
for (const t of tasks2) {
if (t.status === "stale") {
notifications.push(
"error",
`${deviceId}: No contact from device`
);
return;
} else if (t.status === "fault") {
notifications.push(
"error",
`${deviceId}: Task(s) faulted`
);
return;
}
}
notifications.push( notifications.push(
"success", "error",
`${deviceId}: Task(s) committed` `${deviceId}: ${err.message}`
); );
return;
} }
)
if (connectionRequestStatus !== "OK") {
notifications.push(
"error",
`${deviceId}: ${connectionRequestStatus}`
);
return;
}
for (const t of tasks2) {
if (t.status === "stale") {
notifications.push(
"error",
`${deviceId}: No contact from device`
);
return;
} else if (t.status === "fault") {
notifications.push(
"error",
`${deviceId}: Task(s) faulted`
);
return;
}
}
notifications.push(
"success",
`${deviceId}: Task(s) committed`
);
}
)
.then(() => { .then(() => {
store.fulfill(0, Date.now()); store.fulfill(0, Date.now());
}) })
.catch((err) => { .catch((err) => {
throw err; notifications.push("error", err.message);
}); });
}, },
}, },
@@ -453,7 +478,7 @@ const component: ClosureComponent = (): Component => {
"button", "button",
{ {
title: "Clear tasks", title: "Clear tasks",
onclick: taskQueue.clear, onclick: clear,
disabled: !queueElements.length, disabled: !queueElements.length,
}, },
"Clear" "Clear"
+5 -2
View File
@@ -27,6 +27,8 @@ interface Attribute {
type?: string; type?: string;
} }
const MAX_PAGE_SIZE = 200;
function renderTable( function renderTable(
attributes: Attribute[], attributes: Attribute[],
data: Record<string, any>[], data: Record<string, any>[],
@@ -37,7 +39,7 @@ function renderTable(
onSortChange: (obj: Record<string, number>) => void, onSortChange: (obj: Record<string, number>) => void,
downloadUrl?: string, downloadUrl?: string,
valueCallback?: (attr: Attribute, record: Record<string, any>) => Children, valueCallback?: (attr: Attribute, record: Record<string, any>) => Children,
actionsCallback?: Children | ((selected: Set<string>) => Children), actionsCallback?: Children | ((sel: Set<string>) => Children),
recordActionsCallback?: Children | ((record: Record<string, any>) => Children) recordActionsCallback?: Children | ((record: Record<string, any>) => Children)
): Children { ): Children {
const records = data || []; const records = data || [];
@@ -180,7 +182,8 @@ function renderTable(
{ {
title: "Show more records", title: "Show more records",
onclick: showMoreCallback, onclick: showMoreCallback,
disabled: !data.length || records.length >= total, disabled:
!data.length || records.length >= Math.min(MAX_PAGE_SIZE, total),
}, },
"More" "More"
) )
+1 -1
View File
@@ -81,7 +81,7 @@ export const component: ClosureComponent = (): Component => {
location.reload(); location.reload();
}) })
.catch((err) => { .catch((err) => {
notifications.push("error", err.message); notifications.push("error", err.response || err.message);
e.target.disabled = false; e.target.disabled = false;
}); });
return false; return false;
+44 -13
View File
@@ -19,23 +19,41 @@
import * as store from "./store"; import * as store from "./store";
import { Task } from "../lib/types"; import { Task } from "../lib/types";
import * as notifications from "./notifications";
export interface QueueTask extends Task { export interface QueueTask extends Task {
status?: string; status?: string;
device?: string; device: string;
} }
const queue: Set<QueueTask> = new Set(); export interface StageTask extends Task {
const staging: Set<QueueTask> = new Set(); devices: string[];
}
export function queueTask(task: QueueTask): void { const MAX_QUEUE = 100;
staging.delete(task);
task.status = "queued"; const queue: Set<QueueTask> = new Set();
queue.add(task); const staging: Set<StageTask> = new Set();
function canQueue(tasks: QueueTask[]): boolean {
let count = queue.size;
for (const task of tasks) if (!queue.has(task)) ++count;
return count <= MAX_QUEUE;
}
export function queueTask(...tasks: QueueTask[]): void {
if (!canQueue(tasks)) {
notifications.push("error", "Too many tasks in queue");
return;
}
for (const task of tasks) {
task.status = "queued";
queue.add(task);
}
} }
export function deleteTask(task: QueueTask): void { export function deleteTask(task: QueueTask): void {
staging.delete(task);
queue.delete(task); queue.delete(task);
} }
@@ -47,7 +65,7 @@ export function clear(): void {
queue.clear(); queue.clear();
} }
export function getStaging(): Set<QueueTask> { export function getStaging(): Set<StageTask> {
return staging; return staging;
} }
@@ -55,11 +73,19 @@ export function clearStaging(): void {
staging.clear(); staging.clear();
} }
export function stageSpv(task: QueueTask): void { export function stageSpv(task: StageTask): void {
if (queue.size + task.devices.length > MAX_QUEUE) {
notifications.push("error", "Too many tasks in queue");
return;
}
staging.add(task); staging.add(task);
} }
export function stageDownload(task: QueueTask): void { export function stageDownload(task: StageTask): void {
if (queue.size + task.devices.length > MAX_QUEUE) {
notifications.push("error", "Too many tasks in queue");
return;
}
staging.add(task); staging.add(task);
} }
@@ -69,14 +95,19 @@ export function commit(
deviceId: string, deviceId: string,
err: Error, err: Error,
conReqStatus: string, conReqStatus: string,
tasks: QueueTask[] _tasks: QueueTask[]
) => void ) => void
): Promise<void> { ): Promise<void> {
const devices: { [deviceId: string]: any[] } = {}; const devices: { [deviceId: string]: any[] } = {};
if (!canQueue(tasks))
return Promise.reject(new Error("Too many tasks in queue"));
for (const t of tasks) { for (const t of tasks) {
devices[t.device] = devices[t.device] || []; devices[t.device] = devices[t.device] || [];
devices[t.device].push(t); devices[t.device].push(t);
queueTask(t); t.status = "queued";
queue.add(t);
} }
return new Promise((resolve) => { return new Promise((resolve) => {