|
| 1 | +/** |
| 2 | + * |
| 3 | + * Queue Model |
| 4 | + * |
| 5 | + * Job Realm Schema defined in ../config/Database |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +import Database from '../config/Database'; |
| 10 | +import uuid from 'react-native-uuid'; |
| 11 | +import Worker from './Worker'; |
| 12 | +import promiseReflect from 'promise-reflect'; |
| 13 | + |
| 14 | + |
| 15 | +export class Queue { |
| 16 | + |
| 17 | + constructor() { |
| 18 | + this.realm = null; |
| 19 | + this.worker = new Worker(); |
| 20 | + this.status = 'inactive'; |
| 21 | + } |
| 22 | + |
| 23 | + async init() { |
| 24 | + if (this.realm === null) { |
| 25 | + this.realm = await Database.getRealmInstance(); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + addWorker(jobName, worker, options = {}) { |
| 30 | + this.worker.addWorker(jobName, worker, options); |
| 31 | + } |
| 32 | + |
| 33 | + removeWorker(jobName) { |
| 34 | + this.worker.removeWorker(jobName); |
| 35 | + } |
| 36 | + |
| 37 | + createJob(name, payload = {}, options = {}, startQueue = true) { |
| 38 | + |
| 39 | + if (!name) { |
| 40 | + throw new Error('Job name must be supplied.'); |
| 41 | + } |
| 42 | + |
| 43 | + this.realm.write(() => { |
| 44 | + |
| 45 | + this.realm.create('Job', { |
| 46 | + id: uuid.v4(), |
| 47 | + name, |
| 48 | + payload: JSON.stringify(payload), |
| 49 | + data: JSON.stringify({ |
| 50 | + timeout: (options.timeout > 0) ? options.timeout : 0, |
| 51 | + attempts: options.attempts || 1 |
| 52 | + }), |
| 53 | + priority: options.priority || 0, |
| 54 | + active: false, |
| 55 | + created: new Date(), |
| 56 | + failed: null |
| 57 | + }); |
| 58 | + |
| 59 | + }); |
| 60 | + |
| 61 | + // Start queue on job creation if it isn't running by default. |
| 62 | + if (startQueue && this.status == 'inactive') { |
| 63 | + this.start(); |
| 64 | + } |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + async start() { |
| 69 | + |
| 70 | + // If queue is already running, don't fire up concurrent loop. |
| 71 | + if (this.status == 'active') { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + this.status = 'active'; |
| 76 | + |
| 77 | + let concurrentJobs = await this.getConcurrentJobs(); |
| 78 | + |
| 79 | + while (this.status == 'active' && concurrentJobs.length) { |
| 80 | + |
| 81 | + // Loop over jobs and process them concurrently. |
| 82 | + const processingJobs = concurrentJobs.map( job => { |
| 83 | + return this.processJob(job); |
| 84 | + }); |
| 85 | + |
| 86 | + // Promise Reflect ensures all processingJobs resolve so |
| 87 | + // we don't break await early if one of the jobs fails. |
| 88 | + await Promise.all(processingJobs.map(promiseReflect)); |
| 89 | + |
| 90 | + // Get next batch of jobs. |
| 91 | + concurrentJobs = await this.getConcurrentJobs(); |
| 92 | + |
| 93 | + } |
| 94 | + |
| 95 | + this.status = 'inactive'; |
| 96 | + |
| 97 | + } |
| 98 | + |
| 99 | + stop() { |
| 100 | + this.status = 'inactive'; |
| 101 | + } |
| 102 | + |
| 103 | + async getJobs(sync = false) { |
| 104 | + |
| 105 | + if (sync) { |
| 106 | + |
| 107 | + let jobs = null; |
| 108 | + this.realm.write(() => { |
| 109 | + |
| 110 | + jobs = this.realm.objects('Job'); |
| 111 | + |
| 112 | + }); |
| 113 | + |
| 114 | + return jobs; |
| 115 | + |
| 116 | + } else { |
| 117 | + return await this.realm.objects('Job'); |
| 118 | + } |
| 119 | + |
| 120 | + } |
| 121 | + |
| 122 | + async getConcurrentJobs() { |
| 123 | + |
| 124 | + let concurrentJobs = []; |
| 125 | + |
| 126 | + this.realm.write(() => { |
| 127 | + |
| 128 | + // Get next job from queue. |
| 129 | + let nextJob = null; |
| 130 | + |
| 131 | + let jobs = this.realm.objects('Job') |
| 132 | + .filtered('active == FALSE AND failed == null') |
| 133 | + .sorted([['priority', true], ['created', false]]); |
| 134 | + |
| 135 | + if (jobs.length) { |
| 136 | + nextJob = jobs[0]; |
| 137 | + } |
| 138 | + |
| 139 | + // If next job exists, get concurrent related jobs appropriately. |
| 140 | + if (nextJob) { |
| 141 | + |
| 142 | + const concurrency = this.worker.getConcurrency(nextJob.name); |
| 143 | + |
| 144 | + const allRelatedJobs = this.realm.objects('Job') |
| 145 | + .filtered('name == "'+ nextJob.name +'" AND active == FALSE AND failed == null') |
| 146 | + .sorted([['priority', true], ['created', false]]); |
| 147 | + |
| 148 | + let jobsToMarkActive = allRelatedJobs.slice(0, concurrency); |
| 149 | + |
| 150 | + // Grab concurrent job ids to reselect jobs as marking these jobs as active will remove |
| 151 | + // them from initial selection when write transaction exits. |
| 152 | + // See: https://stackoverflow.com/questions/47359368/does-realm-support-select-for-update-style-read-locking/47363356#comment81772710_47363356 |
| 153 | + const concurrentJobIds = jobsToMarkActive.map( job => job.id); |
| 154 | + |
| 155 | + // Mark concurrent jobs as active |
| 156 | + jobsToMarkActive = jobsToMarkActive.map( job => { |
| 157 | + job.active = true; |
| 158 | + }); |
| 159 | + |
| 160 | + // Reselect now-active concurrent jobs by id. |
| 161 | + const query = concurrentJobIds.map( jobId => 'id == "' + jobId + '"').join(' OR '); |
| 162 | + const reselectedJobs = this.realm.objects('Job') |
| 163 | + .filtered(query) |
| 164 | + .sorted([['priority', true], ['created', false]]); |
| 165 | + |
| 166 | + concurrentJobs = reselectedJobs.slice(0, concurrency); |
| 167 | + |
| 168 | + } |
| 169 | + |
| 170 | + }); |
| 171 | + |
| 172 | + return concurrentJobs; |
| 173 | + |
| 174 | + } |
| 175 | + |
| 176 | + async processJob(job) { |
| 177 | + |
| 178 | + try { |
| 179 | + |
| 180 | + await this.worker.executeJob(job); |
| 181 | + |
| 182 | + // On job completion, remove job |
| 183 | + this.realm.write(() => { |
| 184 | + |
| 185 | + this.realm.delete(job); |
| 186 | + |
| 187 | + }); |
| 188 | + |
| 189 | + } catch (error) { |
| 190 | + |
| 191 | + // Handle job failure logic, including retries. |
| 192 | + this.realm.write(() => { |
| 193 | + |
| 194 | + // Increment failed attempts number |
| 195 | + let jobData = JSON.parse(job.data); |
| 196 | + |
| 197 | + if (!jobData.failedAttempts) { |
| 198 | + jobData.failedAttempts = 1; |
| 199 | + } else { |
| 200 | + jobData.failedAttempts++; |
| 201 | + } |
| 202 | + |
| 203 | + job.data = JSON.stringify(jobData); |
| 204 | + |
| 205 | + // Reset active status |
| 206 | + job.active = false; |
| 207 | + |
| 208 | + // Mark job as failed if too many attempts |
| 209 | + if (jobData.failedAttempts >= jobData.attempts) { |
| 210 | + job.failed = new Date(); |
| 211 | + } |
| 212 | + |
| 213 | + }); |
| 214 | + |
| 215 | + } |
| 216 | + |
| 217 | + } |
| 218 | + |
| 219 | + flushQueue(jobName = null) { |
| 220 | + |
| 221 | + if (jobName) { |
| 222 | + |
| 223 | + this.realm.write(() => { |
| 224 | + |
| 225 | + let jobs = this.realm.objects('Job') |
| 226 | + .filtered('name == "' + jobName + '"'); |
| 227 | + |
| 228 | + if (jobs.length) { |
| 229 | + this.realm.delete(jobs); |
| 230 | + } |
| 231 | + |
| 232 | + }); |
| 233 | + |
| 234 | + } else { |
| 235 | + this.realm.write(() => { |
| 236 | + |
| 237 | + this.realm.deleteAll(); |
| 238 | + |
| 239 | + }); |
| 240 | + } |
| 241 | + |
| 242 | + } |
| 243 | + |
| 244 | + |
| 245 | +} |
| 246 | + |
| 247 | +export default async function queueFactory() { |
| 248 | + |
| 249 | + const queue = new Queue(); |
| 250 | + await queue.init(); |
| 251 | + |
| 252 | + return queue; |
| 253 | + |
| 254 | +} |
0 commit comments