Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement task polling composable #13158

Merged
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
:style="selectorStyle"
:options="selectArray"
:label="$tr('frequency')"
@select="handleUserInput"
/>
</KGridItem>
</KGrid>
Expand All @@ -43,6 +44,7 @@
:style="selectorStyle"
:options="getDays"
:label="$tr('day')"
@select="handleUserInput"
/>
</KGridItem>
</KGrid>
Expand All @@ -55,6 +57,7 @@
:style="selectorStyle"
:options="SyncTime"
:label="$tr('time')"
@select="handleUserInput"
/>
</KGridItem>
</KGrid>
Expand All @@ -78,7 +81,7 @@
<KCheckbox
:checked="retryFlag"
:disabled="currentTaskRunning"
@change="retryFlag = !retryFlag"
@change="handleRetryCheckboxChange"
>
{{ $tr('checkboxLabel') }}
</KCheckbox>
Expand Down Expand Up @@ -156,6 +159,7 @@
import { now } from 'kolibri/utils/serverClock';
import commonCoreStrings from 'kolibri/uiText/commonCoreStrings';
import { TaskStatuses, TaskTypes } from 'kolibri-common/utils/syncTaskUtils';
import useTaskPolling from '../../composables/useTaskPolling';
import { KDP_ID, oneHour, oneDay, oneWeek, twoWeeks, oneMonth } from './constants';
import { kdpNameTranslator } from './i18n';

Expand Down Expand Up @@ -192,6 +196,10 @@
BottomAppBar,
},
mixins: [commonCoreStrings],
setup() {
const { tasks } = useTaskPolling('facility_task');
return { tasks };
},
props: {
icon: {
type: String,
Expand All @@ -217,9 +225,9 @@
device: null,
now: null,
selectedItem: {},
tasks: [],
selectedDay: {},
selectedTime: {},
userHasEdited: false,
};
},
computed: {
Expand Down Expand Up @@ -266,16 +274,26 @@
};
});
},
filteredTasks() {
return this.tasks.filter(
task =>
(this.isKdp || task.extra_metadata.device_id === this.device.id) &&
task.facility_id === this.facilityId &&
task.type === this.taskType &&
// Only show tasks that are repeating indefinitely
task.repeat === null,
);
},
deviceName() {
return this.device && this.device.nickname && this.device.nickname.length
? this.device.nickname
: this.device.device_name;
},
currentTask() {
return this.tasks && this.tasks.length ? this.tasks[0] : null;
return this.filteredTasks.length ? this.filteredTasks[0] : null;
},
currentTaskRunning() {
return this.currentTask && this.currentTask.status === TaskStatuses.RUNNING;
return this.currentTask?.status === TaskStatuses.RUNNING;
},
timeRequired() {
return this.selectedItem.value > oneHour;
Expand Down Expand Up @@ -304,6 +322,36 @@
);
},
},
watch: {
currentTask() {
if (this.currentTask && !this.userHasEdited) {
const enqueueAt = new Date(Date.parse(this.currentTask.scheduled_datetime));
const day = enqueueAt.getDay();
const hours = enqueueAt.getHours();
const minutes = enqueueAt.getMinutes();
this.selectedItem =
this.selectArray.find(item => item.value === this.currentTask.repeat_interval) || {};
this.selectedDay = this.getDays.find(item => item.value === day) || {};
for (const time of this.SyncTime) {
// Because there can be some drift in the task scheduling process,
// we round the 'scheduled' time to the nearest 30 minutes
if (
time.minutes === 0 &&
((time.hours === hours && minutes < 15) ||
(time.hours === hours + 1 && minutes >= 45))
) {
this.selectedTime = time;
break;
}
if (time.minutes === 30 && time.hours === hours && minutes >= 15 && minutes < 45) {
this.selectedTime = time;
break;
}
}
this.retryFlag = Boolean(this.currentTask.retry_interval);
}
},
},
created() {
this.fetchDevice();
this.now = now();
Expand Down Expand Up @@ -393,67 +441,11 @@
})
.catch(() => {
this.createTaskFailedSnackbar();
if (this.currentTask) {
this.fetchSyncTasks();
}
});
},

goBack() {
this.$router.push(this.goBackRoute);
},
pollFetchSyncTasks() {
this.pollInterval = setInterval(() => {
this.fetchSyncTasks();
}, 10000);
},
fetchSyncTasks() {
TaskResource.list({ queue: 'facility_task' }).then(tasks => {
this.tasks = tasks.filter(
task =>
(this.isKdp || task.extra_metadata.device_id === this.device.id) &&
task.facility_id === this.facilityId &&
task.type === this.taskType &&
// Only show tasks that are repeating indefinitely
task.repeat === null,
);
this.$nextTick(() => {
if (this.currentTask) {
const enqueueAt = new Date(Date.parse(this.currentTask.scheduled_datetime));
const day = enqueueAt.getDay();
const hours = enqueueAt.getHours();
const minutes = enqueueAt.getMinutes();
this.selectedItem =
this.selectArray.find(item => item.value === this.currentTask.repeat_interval) ||
{};
this.selectedDay = this.getDays.find(item => item.value === day) || {};
for (const time of this.SyncTime) {
// Because there can be some drift in the task scheduling process,
// we round the 'scheduled' time to the nearest 30 minutes
if (
time.minutes === 0 &&
((time.hours === hours && minutes < 15) ||
(time.hours === hours + 1 && minutes >= 45))
) {
this.selectedTime = time;
break;
}
if (time.minutes === 30 && time.hours === hours && minutes >= 15 && minutes < 45) {
this.selectedTime = time;
break;
}
}
this.retryFlag = Boolean(this.currentTask.retry_interval);
if (this.currentTaskRunning) {
this.pollFetchSyncTasks();
} else {
clearInterval(this.pollInterval);
this.pollInterval = null;
}
}
});
});
},
fetchDevice() {
if (this.isKdp) {
this.device = {
Expand All @@ -462,14 +454,19 @@
device_name: kdpNameTranslator.$tr('syncToKDP'),
base_url: '',
};
this.fetchSyncTasks();
return;
}
NetworkLocationResource.fetchModel({ id: this.deviceId }).then(device => {
this.device = device;
this.fetchSyncTasks();
});
},
handleUserInput() {
this.userHasEdited = true;
},
handleRetryCheckboxChange() {
this.retryFlag = !this.retryFlag;
this.handleUserInput();
},
},
$trs: {
editSyncScheduleTitle: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@
import { computed } from 'vue';
import ImmersivePage from 'kolibri/components/pages/ImmersivePage';
import CoreTable from 'kolibri/components/CoreTable';
import TaskResource from 'kolibri/apiResources/TaskResource';
import FacilityResource from 'kolibri-common/apiResources/FacilityResource';
import commonCoreStrings from 'kolibri/uiText/commonCoreStrings';
import commonSyncElements from 'kolibri-common/mixins/commonSyncElements';
Expand All @@ -127,6 +126,7 @@
useDevicesWithFilter,
} from 'kolibri-common/components/syncComponentSet/SelectDeviceModalGroup/useDevices';
import { TaskTypes } from 'kolibri-common/utils/syncTaskUtils';
import useTaskPolling from '../../composables/useTaskPolling';
import { KDP_ID, oneHour, oneDay, oneWeek, twoWeeks, oneMonth } from './constants';
import { kdpNameTranslator } from './i18n';

Expand All @@ -141,6 +141,7 @@
mixins: [commonCoreStrings, commonSyncElements],
setup(props) {
const deviceFilter = useDeviceFacilityFilter({ id: props.facilityId });
const { tasks } = useTaskPolling('facility_task');
const { devices } = useDevicesWithFilter(
{
subset_of_users_device: false,
Expand All @@ -165,6 +166,7 @@
});
return {
devicesById,
tasks,
};
},
props: {
Expand All @@ -185,10 +187,17 @@
return {
deviceModal: false,
facility: null,
facilitySyncTasks: [],
};
},
computed: {
facilitySyncTasks() {
return this.tasks.filter(
t =>
t.facility_id === this.facilityId &&
t.repeat === null &&
(t.type === TaskTypes.SYNCDATAPORTAL || t.type === TaskTypes.SYNCPEERFULL),
);
},
scheduledTasks() {
return this.facilitySyncTasks.map(task => {
const deviceName = this.devicesById[this.getDeviceId(task)]
Expand All @@ -208,7 +217,6 @@
},
},
beforeMount() {
this.pollFacilityTasks();
this.fetchFacility();
},
methods: {
Expand All @@ -217,21 +225,6 @@
this.facility = { ...facility };
});
},
pollFacilityTasks() {
TaskResource.list({ queue: 'facility_task' }).then(tasks => {
this.facilitySyncTasks = tasks.filter(
t =>
t.facility_id === this.facilityId &&
t.repeat === null &&
(t.type === TaskTypes.SYNCDATAPORTAL || t.type === TaskTypes.SYNCPEERFULL),
);
if (this.isPolling) {
setTimeout(() => {
return this.pollFacilityTasks();
}, 2000);
}
});
},
closeModal() {
this.deviceModal = false;
},
Expand Down
47 changes: 47 additions & 0 deletions packages/kolibri-common/composables/useTaskPolling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import logger from 'kolibri-logging';
import { ref, onMounted, onUnmounted } from 'vue';
import { useTimeoutPoll } from '@vueuse/core';
import TaskResource from 'kolibri/apiResources/TaskResource';

const taskPollers = new Map();

const logging = logger.getLogger(__filename);

export default function useTaskPolling(queueName) {
if (!taskPollers.has(queueName)) {
const consumers = ref(0);
const tasks = ref([]);
const { pause, resume, isActive } = useTimeoutPoll(
async () => {
try {
tasks.value = await TaskResource.list({ queue: queueName });
} catch (e) {
logging.error('Error while fetching tasks', e);
}
},
5000,
{ immediate: true },
);

taskPollers.set(queueName, { consumers, tasks, pause, resume, isActive });
}

const poller = taskPollers.get(queueName);

onMounted(() => {
poller.consumers.value++;
if (!poller.isActive.value) {
poller.resume();
}
});

onUnmounted(() => {
poller.consumers.value--;
if (poller.consumers.value === 0) {
poller.pause();
taskPollers.delete(queueName);
}
});

return { tasks: poller.tasks };
}
Loading