All files index.js

100% Statements 512/512
100% Branches 123/123
100% Functions 22/22
100% Lines 512/512

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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 51330x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 49x 49x 49x 49x 49x 49x 49x 49x 97x 97x 46x 46x 46x 46x 46x 1x 1x 45x 46x 46x 46x 46x 46x 46x 97x 97x 2x 97x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 97x 30x 30x 30x 30x 30x 30x 30x 93x 93x 93x 93x 48x 48x 93x 93x 45x 45x 93x 93x 30x 30x 30x 30x 30x 30x 30x 30x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 56x 56x 106x 106x 50x 50x 106x 106x 106x 106x 90x 90x 90x 90x 90x 90x 90x 106x 106x 106x 30x 30x 30x 30x 30x 30x 30x 30x 30x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 27x 27x 48x 48x 21x 21x 48x 48x 48x 48x 44x 44x 44x 44x 44x 48x 48x 48x 48x 25x 25x 23x 23x 23x 23x 25x 25x 23x 23x 23x 23x 23x 25x 25x 48x 48x 48x 48x 30x 30x 30x 30x 30x 30x 30x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 13x 13x 13x 27x 27x 13x 13x 14x 14x 30x 30x 30x 30x 30x 30x 30x 30x 842x 842x 842x 842x 842x 842x 842x 842x 842x 842x 842x 770x 770x 770x 370x 370x 400x 400x 400x 400x 400x 400x 400x 400x 400x 400x 2x 2x 398x 398x 398x 398x 398x 398x 398x 398x 6x 6x 392x 392x 392x 392x 392x 392x 392x 196x 196x 392x 398x 400x 842x 842x 842x 30x 30x 30x 30x 30x 30x 30x 30x 499x 499x 499x 499x 499x 499x 499x 499x 30x 30x 30x 30x 30x 30x 30x 30x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 25x 25x 25x 25x 25x 13x 13x 25x 25x 12x 12x 25x 25x 25x 26x 26x 30x 30x 30x 30x 30x 30x 30x 30x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 25x 25x 25x 26x 26x 30x 30x 30x 30x 30x 30x 30x 30x 8x 8x 8x 8x 8x 8x 7x 7x 8x 8x 8x 30x 30x 1000x 1000x 1008x 1008x 1008x 304x 304x 304x 304x 304x 304x 304x 304x 304x 704x 704x 704x 704x 704x 704x 704x 704x 809x 355x 355x 1008x 1008x 1000x 1000x 1000x 1000x 30x 30x 996x 996x 996x 996x 996x 996x 545x 545x 996x 996x 451x 451x 996x 996x 996x 996x 996x 996x 30x 30x 2215x 2215x 2215x 2215x 2215x 397x 397x 6x 6x 6x 391x 391x 391x 1818x 1818x 2215x 2215x 30x 30x 30x 30x 30x 30x 30x 30x 3229x 3229x 3229x 3229x 1778x 1778x 3229x 3229x 1451x 1451x 3229x 3229x 30x 30x 440x 440x 440x 440x 239x 239x 440x 440x 201x 201x 440x 440x 30x 30x 876x 876x 876x 876x 481x 481x 876x 876x 395x 395x 876x 876x 876x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 398x 398x 398x 398x 398x 398x 30x 30x 30x  
'use strict';
 
const crypto = require('crypto'),
      sqlite3 = require('sqlite3'),
      { Client } = require('pg'),
      async = require('async'),
      iferr = require('iferr'),
      EventEmitter = require('events').EventEmitter;
 
/**
 Creates an object which allocates jobs across a number of instances.
 
 @param {Object} options - Configuration options.
 @param {'sqlite' | 'pg'} [options.db_type=sqlite] - Type of database to use.
 @param {string} options.db_filename - (sqlite) Filename in which to store the allocations. You can use the same file in multiple `Atributo` objects, even across different processes. They will all make and see the same allocations.
 @param {integer} [options.db_mode] - (sqlite) Mode to open the file in. See the [sqlite3](https://github.com/mapbox/node-sqlite3/wiki/API#new-sqlite3databasefilename-mode-callback) documentation.
 @param {integer} [options.busy_wait=1000] - (sqlite) Number of milliseconds to wait before retrying if another `Atributo` object has the database file locked.
 @param {Object} options.db - (pg) [`node-postgres` configuration](https://node-postgres.com/api/client).
 */
class Atributo extends EventEmitter
{
    constructor(options)
    {
        super();
 
        this._options = Object.assign(
        {
            db_type: 'sqlite',
            busy_wait: 1000
        }, options);
 
        switch (this._options.db_type)
        {
        case 'sqlite':
            this._db = new sqlite3.Database(this._options.db_filename,
                                            this._options.db_mode);
            this._db.on('open', () => this.emit('ready'));
            this._db.on('close', () => this.emit('close'));
            this._true = 1;
            this._false = 0;
            this._busy_code = 'SQLITE_BUSY';
            break;
 
        case 'pg':
            this._db = new Client(this._options.db);
            this._db.connect(err =>
            {
                if (err)
                {
                    return this.emit('error', err);
                }
                this.emit('ready');
            });
            this._db.on('end', () => this.emit('close'));
            this._true = true;
            this._false = false;
            this._busy_code = '40001';
            break;
 
        default:
            throw new Error(`invalid database type: ${this._options.db_type}`);
        }
 
        this._db.on('error', err => this.emit('error', err));
 
        // We need to queue queries on a db connection:
        // https://github.com/mapbox/node-sqlite3/issues/304
        // Alternative would be to create a separate connection
        // for each query. The calling application can still do
        // this if required (to achieve more parallelism) by
        // creating many Atributo objects.
        this._queue = async.queue((task, cb) => task(cb));
    }
 
    /**
     Close the database file. Subsequent operations will fail.
 
     @param {closeCallback} [cb] - Called once the database is closed.
     */
    close(cb)
    {
        switch (this._options.db_type)
        {
        case 'sqlite':
            this._db.close(cb);
            break;
 
        case 'pg':
            this._db.end(cb);
            break;
        }
    }
 
    /**
     Make an instance available for job allocation.
 
     @param {string} instance_id - ID of the instance.
     @param {availableCallback} cb - Called once the instance has been made available.
     */
    available(instance_id, cb)
    {
        let b = this._busy(cb, () => this.available(instance_id, cb));
 
        this._in_transaction(b, cb =>
        {
            this._queue.unshift(cb => async.waterfall(
            [
                cb =>
                {
                    let sql;
                    switch (this._options.db_type)
                    {
                    case 'sqlite':
                        sql = 'INSERT OR IGNORE INTO instances VALUES ($1, $2);';
                        break;
 
                    case 'pg':
                        sql = 'INSERT INTO instances VALUES ($1, $2) ON CONFLICT DO NOTHING;'
                        break;
                    }
                    this._run(sql, [instance_id, this._true], cb);
                },
                cb =>
                {
                    // Do this in a transaction so we don't error if someone else
                    // deletes the row here.
                    this._run('UPDATE instances SET available = $1 WHERE id = $2;',
                              [this._true, instance_id],
                              cb);
                }
            ], cb), cb);
        });
    }
 
    /**
     Make an instance unavailable for job allocation.
 
     @param {string} instance_id - ID of the instance.
     @param {boolean} destroyed - If false, the instance won't be allocated any more jobs. If true, it is also removed from the database along with its existing job allocations.
     @param {unavailableCallback} cb - Called once the instance has been made unavailable.
     */
    unavailable(instance_id, destroyed, cb)
    {
        let b = this._busy(cb, () => this.unavailable(instance_id, destroyed, cb));
 
        this._in_transaction(b, cb =>
        {
            let statements = [
                cb =>
                {
                    let sql;
                    switch (this._options.db_type)
                    {
                    case 'sqlite':
                        sql = 'INSERT OR IGNORE INTO instances VALUES ($1, $2);';
                        break;
 
                    case 'pg':
                        sql = 'INSERT INTO instances VALUES ($1, $2) ON CONFLICT DO NOTHING;'
                        break;
                    }
                    this._run(sql, [instance_id, this._false], cb);
                },
                cb =>
                {
                    this._run('UPDATE instances SET available = $1 WHERE id = $2;',
                              [this._false, instance_id],
                              cb);
                }
            ];
 
            if (destroyed)
            {
                statements.push(
                    cb =>
                    {
                        this._run('DELETE FROM allocations WHERE instance = $1;',
                                  [instance_id],
                                  cb);
                    },
                    cb =>
                    {
                        this._run('DELETE FROM instances WHERE id = $1;',
                                  [instance_id],
                                  cb);
                    }
                );
            }
 
            this._queue.unshift(cb => async.waterfall(statements, cb), cb);
        });
    }
 
    /**
     Get a list of instance IDs along with their availability.
 
     @param {instancesCallback} cb - Called with the list of instances.
     */
    instances(cb)
    {
        this._queue.push(cb => async.waterfall(
        [
            cb =>
            {
                this._all('SELECT * from instances;',
                          [],
                          cb);
            },
            (r, cb) =>
            {
                for (let row of r)
                {
                    row.available = !!row.available;
                }
                cb(null, r);
            }
        ], cb), this._busy(cb, () => this.instances(cb)));
    }
 
    /**
     Allocate a job to an instance.
 
     @param {string} job_id - ID of the job to allocate.
     @param {allocateCallback} cb - Called with the ID of the instance to which the job was allocated, and whether the allocation was persisted to the database. The default allocator chooses the instance based on a hash of `job_id`. You can override the [`_allocate`](#atributo_allocate) function to provide a different allocator.
     */
    allocate(job_id, cb)
    {
        let b = this._busy(cb, () => this.allocate(job_id, cb));
 
        this._in_transaction(b, cb =>
        {
            this._queue.unshift(cb => 
            {
                this._get('SELECT instance FROM allocations WHERE job = $1;',
                          [job_id],
                          cb);
            }, iferr(cb, r =>
            {
                if (r !== undefined)
                {
                    return cb(null, r.instance, false);
                }
 
                this._queue.unshift(cb => 
                {
                    this._all('SELECT id FROM instances WHERE available = $1;',
                              [this._true],
                              cb);
                }, iferr(cb, r =>
                {
                    if (r.length === 0)
                    {
                        return cb(new Error('no instances'));
                    }
 
                    this._queue.unshift(cb =>
                    {
                        this._allocate(job_id, r.map(row => row.id), cb);
                    }, iferr(cb, (instance_id, persist) =>
                    {
                        if (!persist)
                        {
                            return cb(null, instance_id, false);
                        }
 
                        this._queue.unshift(cb =>
                        {
                            this._run('INSERT INTO allocations VALUES ($1, $2);',
                                      [job_id, instance_id],
                                      cb);
                        }, iferr(cb, r =>
                        {
                            cb(null, instance_id, true);
                        }));
                    }));
                }));
            }));
        });
    }
 
    /**
     Remove a job allocation.
 
     @param {string} job_id - ID of job to deallocate. If the job is allocated to an instance in the database, the allocation will be removed.
     @param {deallocateCallback} cb - Called when the allocation has been removed.
     */
    deallocate(job_id, cb)
    {
        this._queue.push(cb =>
        {
            this._run('DELETE FROM allocations WHERE job = $1;',
                      [job_id],
                      cb);
        }, this._busy(cb, () => this.deallocate(job_id, cb)));
    }
 
    /**
      Get whether an instance has jobs allocated to it.
 
      @param {string} instance_id - ID of the instance.
      @param {has_jobsCallback} cb - Receives whether there are jobs allocated to to the instance.
     */
    has_jobs(instance_id, cb)
    {
        this._queue.push(cb => async.waterfall(
        [
            cb =>
            {
                this._get('SELECT count(*) FROM allocations WHERE instance = $1;',
                          [instance_id],
                          cb);
            },
            (r, cb) =>
            {
                let key;
                switch (this._options.db_type)
                {
                case 'sqlite':
                    key = 'count(*)';
                    break;
 
                case 'pg':
                    key = 'count';
                    break;
                }
                cb(null, r[key] > 0);
            }
        ], cb), this._busy(cb, () => this.has_jobs(instance_id, cb)));
    }
 
    /**
     Gets the jobs allocated to an instance.
 
     @param {string} instance_id - ID of the instance.
     @param {jobsCallback} cb - Called with a list of job IDs allocated to the instance.
     */
    jobs(instance_id, cb)
    {
        this._queue.push(cb => async.waterfall(
        [
            cb =>
            {
                this._all('SELECT job from allocations WHERE instance = $1;',
                          [instance_id],
                          cb);
            },
            (r, cb) =>
            {
                cb(null, r.map(row => row.job));
            }
        ], cb), this._busy(cb, () => this.jobs(instance_id, cb)));
    }
 
    /**
     Gets the instance to which a job is allocated.
 
     @param {string} job_id - ID of the job.
     @param {instanceCallback} cb - Called with the ID of the instance to which the job is allocated, or `null`.
     */
    instance(job_id, cb)
    {
        this._queue.push(cb =>
        {
            this._get('SELECT instance FROM allocations WHERE job = $1;',
                      [job_id],
                      iferr(cb, r =>
                      {
                          cb(null, r === undefined ? null : r.instance);
                      }));
        }, this._busy(cb, () => this.instance(job_id, cb)));
    }
 
    _end_transaction(cb)
    {
        let f = (err, ...args) =>
        {
            if (err)
            {
                return this._queue.unshift(cb =>
                {
                    this._run('ROLLBACK',
                              [],
                              cb);
                }, this._busy(err2 => cb(err2 || err, ...args),
                              () => f(err, ...args),
                              true));
            }
 
            const cb2 = err => cb(err, ...args);
 
            this._queue.unshift(cb =>
            {
                this._run('END TRANSACTION',
                          [],
                          cb);
            }, this._options.db_type === 'sqlite' ?
                this._busy(cb2,
                           () => f(err, ...args),
                           true) :
                cb2);
        };
 
        return f;
    }
 
    _in_transaction(cb, f)
    {
        let isolation_level;
 
        switch (this._options.db_type)
        {
        case 'sqlite':
            isolation_level = ''; // SQLite transactions are serializable
            break;
 
        case 'pg':
            isolation_level = 'ISOLATION LEVEL SERIALIZABLE';
            break;
        }
 
        this._queue.push(cb2 =>
            this._run(`BEGIN TRANSACTION ${isolation_level}`, [], cb2),
            iferr(cb, () => f(this._end_transaction(cb))));
    }
 
    _busy(f, retry, block)
    {
        return (err, ...args) =>
        {
            if (err && (err.code === this._busy_code))
            {
                if (block)
                {
                    return this._queue.unshift(cb => setTimeout(cb, this._options.busy_wait),
                                               retry);
                }
 
                return setTimeout(retry, this._options.busy_wait);
            }
 
            f(err, ...args);
        };
    }
 
    // Note: $1, $2 placeholders in SQL statements are PostgreSQL syntax.
    // However, as long as they appear _in order_ (i.e. never $2 before $1)
    // then they work in SQLite too. This is because when $ is used, SQLite
    // binds first parameter in array to first $whatever in the statement,
    // second parameter to second $something etc.
 
    _run(sql, values, cb)
    {
        switch (this._options.db_type)
        {
        case 'sqlite':
            this._db.run(sql, ...values, cb);
            break;
 
        case 'pg':
            this._db.query(sql, values, iferr(cb, () => cb()));
            break;
        }
    }
 
    _all(sql, values, cb)
    {
        switch (this._options.db_type)
        {
        case 'sqlite':
            this._db.all(sql, ...values, cb);
            break;
 
        case 'pg':
            this._db.query(sql, values, iferr(cb, r => cb(null, r.rows)));
            break;
        }
    }
 
    _get(sql, values, cb)
    {
        switch (this._options.db_type)
        {
        case 'sqlite':
            this._db.get(sql, ...values, cb);
            break;
 
        case 'pg':
            this._db.query(sql, values, iferr(cb, r => cb(null, r.rows[0])));
            break;
        }
 
    }
 
    /**
     The default job allocator algorithm. `job_id` is hashed, treated as an
     integer and used as an index into the array of available instances.
     Override this method to provide a different algorithm.
 
     @param {string} job_id - ID of the job to allocate.
     @param {string[]} instance_ids - IDs of available instances.
     @param {_allocateCallback} cb - Your allocator method should call this once it's decided to which instance the job should be allocated.
     */
    _allocate(job_id, instance_ids, cb)
    {
        let h = crypto.createHash('md5'); // not for security, just mapping
        h.update(job_id);
        let buf = h.digest();
        cb(null, instance_ids[buf.readUInt32BE(0) % instance_ids.length], true);
    }
}
 
exports.Atributo = Atributo;