Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 108x 108x 108x 108x 33x 33x 33x 33x 33x 33x 46x 46x 41x 1x 40x 40x 32x 32x 36x 40x 40x 28x 5x 33x 33x 33x 33x 108x | import { useEffect, useState } from "react";
import axios from "axios";
import {
JOB_LOG_POLL_INTERVAL_SECONDS,
JOB_LOG_TAIL_URL,
isJobFinished,
} from "main/utils/jobLogUtils";
/**
* Follows the log of a job of a course, like `tail -f`: asks the backend for
* the log every JOB_LOG_POLL_INTERVAL_SECONDS seconds, each time only for the
* lines added since the last one received, and stops asking once the job is
* over, when the component using it goes away, or when a request fails.
*
* @param {number|string} courseId the course the job belongs to
* @param {number|string} jobId the job whose log to follow
* @returns {{lines: string[], status: string|null, error: Error|null}} the log
* lines so far, oldest first; the latest status of the job, or null before the
* first answer; and the error of the request that made it stop, if there was one
*/
export function useJobLogTail(courseId, jobId) {
const [lines, setLines] = useState([]);
const [status, setStatus] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let stopped = false;
let timer;
// the id of the last log line received; the backend sends lines after it
let afterId = 0;
setLines([]);
setStatus(null);
setError(null);
const poll = async () => {
try {
const response = await axios.get(JOB_LOG_TAIL_URL, {
params: { courseId, jobId, afterId },
});
if (stopped) {
return;
}
const { status: newStatus, lines: newLines } = response.data;
if (newLines.length > 0) {
afterId = newLines[newLines.length - 1].id;
setLines((previous) => [
...previous,
...newLines.map((line) => line.message),
]);
}
setStatus(newStatus);
if (!isJobFinished(newStatus)) {
timer = setTimeout(poll, JOB_LOG_POLL_INTERVAL_SECONDS * 1000);
}
} catch (e) {
// if the component is gone by now, this state is simply not used
setError(e);
}
};
poll();
return () => {
stopped = true;
clearTimeout(timer);
};
}, [courseId, jobId]);
return { lines, status, error };
}
|