Action button uses mixins for invoking and polling actions

This commit is contained in:
Julian Stirling 2025-11-09 16:08:55 +00:00
parent 4910bef717
commit dd0a57520b
2 changed files with 118 additions and 102 deletions

View file

@ -47,8 +47,6 @@
</template> </template>
<script> <script>
import axios from "axios";
import ActionProgressBar from "./actionProgressBar.vue"; import ActionProgressBar from "./actionProgressBar.vue";
import ActionStatusModal from "./actionStatusModal.vue"; import ActionStatusModal from "./actionStatusModal.vue";
@ -165,7 +163,7 @@ export default {
n = Math.trunc(n) || 0; n = Math.trunc(n) || 0;
// Allow negative indexing from the end // Allow negative indexing from the end
if (n < 0) n += this.length; if (n < 0) n += this.length;
// OOB access is guaranteed to return undefined // Out of bounds access is guaranteed to return undefined
if (n < 0 || n >= this.length) return undefined; if (n < 0 || n >= this.length) return undefined;
// Otherwise, this is just normal property access // Otherwise, this is just normal property access
return this[n]; return this[n];
@ -215,13 +213,9 @@ export default {
* *
*/ */
async checkExistingTasks() { async checkExistingTasks() {
let response; let response = await this.findOngoingAction(this.thing, this.action);
try { // Exit if response is null, due to an error.
response = await axios.get(this.submitUrl); if (response == null) return;
} catch (error) {
console.warn("checkExistingTasks: request failed", error);
return;
}
// Check for a task that is ongoing. // Check for a task that is ongoing.
// We can't handle multiple tasks ongoing, so this picks the first. // We can't handle multiple tasks ongoing, so this picks the first.
const ongoingTask = response.data.find((t) => ["pending", "running"].includes(t.status)); const ongoingTask = response.data.find((t) => ["pending", "running"].includes(t.status));
@ -231,13 +225,7 @@ export default {
this.$emit("taskStarted"); this.$emit("taskStarted");
// Find its URL // Find its URL
const taskUrl = ongoingTask.links.find((t) => t.rel == "self").href; const taskUrl = ongoingTask.links.find((t) => t.rel == "self").href;
try { this.startPollingTask(ongoingTask.id, taskUrl);
await this.pollOngoingTask(ongoingTask.id, taskUrl);
} catch (error) {
this.$emit("error", error);
} finally {
this.onTaskEnd();
}
} }
}, },
@ -257,61 +245,66 @@ export default {
async startTask() { async startTask() {
// Starts a new Action task // Starts a new Action task
this.$emit("submit", this.submitData); this.$emit("submit", this.submitData);
// Send a request to start a task // Send a request to start a task
this.taskStarted = true; this.taskStarted = true;
this.$emit("taskStarted"); this.$emit("taskStarted");
let response;
try { try {
let response = await axios.post(this.submitUrl, this.submitData); response = await this.invokeAction(
this.thing,
this.action,
this.submitData,
false, // Stop invokeAction handling the error.
);
} catch (error) {
this.$emit("error", error);
this.onTaskEnd();
return;
}
if (this.modalProgress) { if (this.modalProgress) {
this.$refs.statusModal.show(); this.$refs.statusModal.show();
} }
await this.pollOngoingTask(response.data.id, response.data.href); // This just starts the polling. No need to await it.
} catch (error) { this.startPollingTask(response.data.id, response.data.href);
this.$emit("error", error);
} finally {
this.onTaskEnd();
}
}, },
async pollOngoingTask(taskId, taskUrl) { async startPollingTask(taskId, taskUrl) {
// Start the store polling TaskId for success // Return if taskRunning already set.
const response = await this.startPolling(taskId, taskUrl); if (this.taskRunning) return;
if (response.status == "completed") {
this.$emit("response", response);
this.$emit("completed", response.output);
} else if (response.status == "cancelled") {
this.$emit("cancelled", response);
this.modalNotify(`The action '${this.submitLabel}' was cancelled.`);
}
},
onTaskEnd: function () {
// Reset taskRunning and taskId
this.taskRunning = false;
this.taskStarted = false;
this.$emit("finished");
},
startPolling: function (taskId, taskUrl) {
if (this.taskRunning != true) {
// Starts polling an existing Action task // Starts polling an existing Action task
this.taskUrl = taskUrl; this.taskUrl = taskUrl;
// Start the store polling TaskId for success // Start the store polling TaskId for success
this.taskRunning = true; this.taskRunning = true;
this.$emit("taskRunning", taskId); this.$emit("taskRunning", taskId);
return this.pollTask(taskId, this.pollInterval); this.pollUntilComplete(
} taskUrl,
this.onPollingResponse,
this.onTaskEnd, // Method to run after task (even if error)
500, // Interval
false, // Don't handle errors,
);
}, },
pollTask: function (taskId, interval) { onTaskEnd: function (response) {
interval = interval * 1000 || 500; if (response) {
this.taskStatus = response.data.status;
this.log = response.data.log;
if (response.data.status == "completed") {
this.$emit("response", response.data);
this.$emit("completed", response.data.output);
} else if (response.data.status == "cancelled") {
this.$emit("cancelled", response.data);
this.modalNotify(`The action '${this.submitLabel}' was cancelled.`);
}
}
this.taskUrl = null;
this.taskRunning = false;
this.taskStarted = false;
this.$emit("finished");
},
var checkCondition = (resolve, reject) => { onPollingResponse(response) {
// If the condition is met, we're done!
axios.get(this.taskUrl, { baseURL: this.$store.getters.baseUri }).then((response) => {
var result = response.data.status; var result = response.data.status;
this.taskStatus = result; this.taskStatus = result;
if ((result == "running") | (result == "pending")) { if ((result == "running") | (result == "pending")) {
@ -319,11 +312,14 @@ export default {
// and schedule another poll // and schedule another poll
this.progress = response.data.progress; this.progress = response.data.progress;
this.log = response.data.log; this.log = response.data.log;
// Check again after timeout
setTimeout(checkCondition, interval, resolve, reject);
} }
// If task ends with an error // If task ends with an error
else if (result == "error") { else if (result == "error") {
this.handleErrorResponse(response);
}
},
handleErrorResponse(response) {
// Pass the error string back with reject // Pass the error string back with reject
if (!this.progress) this.progress = 1; if (!this.progress) this.progress = 1;
// Test whether the log is empty or the most recent message is not from an error // Test whether the log is empty or the most recent message is not from an error
@ -339,26 +335,16 @@ export default {
// If the Exception was raised with no message, use a default. // If the Exception was raised with no message, use a default.
else { else {
message = message =
response.data.log.from_index(-1).message || response.data.log.from_index(-1).message || "Unexpected error, please check the logs";
"Unexpected error, please check the logs";
} }
// Raise an Error with the chosen message // Raise an Error with the chosen message
reject(new Error(message)); throw new Error(message);
}
// If task ends without reporting an error
// (Note: this includes cancellation)
else {
resolve(response.data);
}
});
};
return new Promise(checkCondition);
}, },
terminateTask: function () { terminateTask: function () {
axios.delete(this.taskUrl, { baseURL: this.$store.getters.baseUri }); if (this.taskUrl) {
this.$root.$emit("modalClosed"); this.terminateAction(this.taskUrl);
}
}, },
}, },
}; };

View file

@ -64,19 +64,31 @@ export default {
} }
await axios.put(url, value); await axios.put(url, value);
}, },
async invokeAction(thing, action, data) { async invokeAction(thing, action, data, handleErrors = true) {
let url = this.$store.getters["wot/thingActionUrl"](thing, action, "invokeaction", false); let url = this.thingActionUrl(thing, action);
try { try {
let response = await axios.post(url, data); let response = await axios.post(url, data);
return response; return response;
} catch (error) { } catch (error) {
if (handleErrors) {
this.modalError(error); this.modalError(error);
return undefined; return undefined;
} else {
throw error;
}
} }
}, },
async pollUntilComplete(taskUrl, ongoingMethod, finalMethod, interval = 500) { async pollUntilComplete(
taskUrl,
ongoingMethod,
finalMethod,
interval = 500,
modalErrors = true,
) {
let response;
let finalMethodCalled = false;
try { try {
const response = await axios.get(taskUrl, { baseURL: this.$store.getters.baseUri }); response = await axios.get(taskUrl, { baseURL: this.$store.getters.baseUri });
const result = response.data.status; const result = response.data.status;
if ((result == "running") | (result == "pending")) { if ((result == "running") | (result == "pending")) {
@ -87,15 +99,33 @@ export default {
} else { } else {
clearTimeout(this.pollTimers[taskUrl]); clearTimeout(this.pollTimers[taskUrl]);
delete this.pollTimers[taskUrl]; delete this.pollTimers[taskUrl];
finalMethodCalled = true;
finalMethod?.(response); finalMethod?.(response);
} }
} catch (error) { } catch (error) {
clearTimeout(this.pollTimers[taskUrl]); this.$emit("error", error);
delete this.pollTimers[taskUrl]; if (modalErrors) {
this.modalError(error); this.modalError(error);
} }
clearTimeout(this.pollTimers[taskUrl]);
delete this.pollTimers[taskUrl];
if (!finalMethodCalled) {
finalMethod?.(response);
}
}
},
terminateAction(taskUrl) {
axios.delete(taskUrl, { baseURL: this.$store.getters.baseUri });
},
async findOngoingAction(thing, action) {
let url = this.thingActionUrl(thing, action);
try {
return await axios.get(url);
} catch (error) {
console.warn("checkExistingTasks: request failed", error);
return null;
}
}, },
thingActionUrl(thing, action, allowUndefined = false) { thingActionUrl(thing, action, allowUndefined = false) {
let url = this.$store.getters["wot/thingActionUrl"]( let url = this.$store.getters["wot/thingActionUrl"](
thing, thing,