/**
* Manages DataAPI requests and return data
*
* Copyright (C) 2010-2019 R-T Specialty, LLC.
*
* This file is part of the Liza Data Collection Framework
*
* liza is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
const { Class } = require( 'easejs' );
const { EventEmitter } = require( 'events' );
const MissingDataError = require( './MissingDataError' );
/**
* Pends and manages API calls and return data
*
* TODO: Extracted pretty much verbatim from Program; needs refactoring
*/
module.exports = Class( 'DataApiManager' )
.extend( EventEmitter,
{
/**
* Factory used to create data APIs
* @type {DataApiFactory}
*/
'private _dataApiFactory': null,
/**
* DataApi instance promises, indexed by API id
* @type {Object}
*/
'private _dataApis': {},
/**
* Data returned for fields via a data API, per index, formatted
* @type {Object}
*/
'private _fieldData': {},
/**
* Data returned for fields via a data API, per index, unformatted
* @type {Object}
*/
'private _fieldRawData': {},
/**
* Pending API calls (by tracking identifier, not API id)
* @type {Object}
*/
'private _pendingApiCall': {},
/**
* API calls queued for request
* @type {Object}
*/
'private _queuedApiCall': {},
/**
* Stack depth for field updates (recursion detection)
* @type {Object}
*/
'private _fieldUpdateDepth': {},
/**
* Whether new field data has been emitted
* @type {Object}
*/
'private _fieldDataEmitted': {},
/**
* Id of timer to process API queue
* @type {number}
*/
'private _fieldApiTimer': 0,
/**
* Fields that require API requests
* @type {Object}}
*/
'private _fieldStale': {},
/**
* API descriptions
* @type {Object}
*/
'private _apis': {},
__construct: function( api_factory, apis )
{
this._dataApiFactory = api_factory;
this.setApis( apis || {} );
},
/**
* Set available APIs
*
* TODO: Remove me; pass via ctor
* TODO: Document API definition format
*
* @param {Object} apis API definitions
*
* @return {DataApiManager} self
*/
'public setApis': function( apis )
{
this._apis = apis;
return this;
},
/**
* Retrieve data from the API identified by the given id
*
* The optional request id permits cancelling requests if necessary.
*
* Once a field has finished loading, a `fieldLoaded` event will be
* emitted with `name` and `index`.
*
* TODO: refactor argument list; it's just been built upon too much and
* needs reordering
*
* @param {string} api API id
* @param {Object} data API arguments (key-value)
* @param {function(Object)} callback callback to contain response
* @param {string} name element name for tracking
* @param {number} index index for tracking
* @param {bucket} bucket optional bucket to use as data source
* @param {function(Error)} fc failure continuation
*
* @return {Program} self
*/
'public getApiData': function( api, data, callback, name, index, bucket, fc )
{
var id = ( name === undefined )
? ( ( new Date() ).getTime() )
: name + '_' + index;
var _self = this;
if ( !( this._apis[ api ] ) )
{
this.emit( 'error', Error( 'Unknown data API: ' + api ) );
}
// create the API if necessary (lazy-load); otherwise, use the existing
// instance (well, a promise for one)
var apip = this._dataApis[ api ] || ( function()
{
var apidesc = _self._apis[ api ];
// create a new instance of the API
return _self._dataApis[ api ] = _self._dataApiFactory.fromType(
apidesc.type, apidesc, bucket, api
)
.then( api =>
api.on( 'error', e => _self.emit( 'error', e ) )
);
} )();
// this has the effect of wiping out previous requests of the same id,
// ensuring that we will make only the most recent request
this._queuedApiCall[ id ] = function()
{
// mark this request as pending (note that we aren't storing and
// references to this object because we do not want a reference to
// be used---the entire object may be reassigned by something else
// in order to wipe out all values)
var uid = ( ( new Date() ).getTime() );
_self._pendingApiCall[ id ] = {
uid: uid,
name: name,
index: index
};
// process the request; we'll let them know when it comes back
apip.then( api => api.request( data, function()
{
// we only wish to populate the field if the request should
// still be considered pending
var curuid = ( _self._pendingApiCall[ id ] || {} ).uid;
if ( curuid === uid )
{
// forward to the caller
callback.apply( this, arguments );
// clear the pending flag
_self._pendingApiCall[ id ] = undefined;
_self.emit( 'fieldLoaded', name, +index );
}
}, id ) )
.catch( e => fc( e ) );
};
// field is about to be re-loaded
this.fieldStale( name, index, false );
this._setFieldApiTimer();
return this;
},
/**
* Get pending API calls
*
* TODO: Added to support a progressive refactoring; this breaks
* encapsulation and should be removed, or formalized.
*
* Returned object contains uid, name, and index fields.
*
* @return {Object} pending API calls
*/
'public getPendingApiCalls': function()
{
return this._pendingApiCall;
},
/**
* Marks field for re-loading
*
* Stale fields will not be considered to have data, but the data
* will remain in memory until the next request.
*
* @param {string} field field name
* @param {number} index field index
* @param {?boolean} stale whether field is stale
*
* @return {DataApiManager} self
*/
'public fieldStale': function( field, index, stale )
{
stale = ( stale === undefined ) ? true : !!stale;
this._fieldStale[ field ] = this.fieldStale[ field ] || [];
this._fieldStale[ field ][ index ] = stale;
return this;
},
/**
* Whether field is marked stale
*
* @param {string} field field name
* @param {number} index field index
*
* @return {boolean} whether field is stale
*/
'protected isFieldStale': function( field, index )
{
return ( this._fieldStale[ field ] || [] )[ index ] === true;
},
'public fieldNotReady': function( id, i, bucket )
{
if ( !( this.hasFieldData( id, i ) ) )
{
return;
}
// failure means that we don't have all the necessary params; clear the
// field
this.clearFieldData( id, i );
// clear the value of this field (IMPORTANT: do this *after* clearing
// the field data, since the empty value may otherwise be invalid);
// ***note that this will also clear any bucket values associated with
// this field, because this will trigger the change event for this
// field***
if ( bucket.hasIndex( id, i ) )
{
var data={};
data[ id ] = [];
data[ id ][ i ] = '';
// the second argument ensures that we merge indexes, rather than
// overwrite the entire value (see FS#11224)
bucket.setValues( data, true );
}
},
'private _setFieldApiTimer': function()
{
// no use in re-setting
if ( this._fieldApiTimer )
{
return;
}
var _self = this;
this._fieldApiTimer = setTimeout( function()
{
_self.processFieldApiCalls();
}, 0 );
},
'public processFieldApiCalls': function()
{
// this may trigger more requests, so be prepared with a fresh queue
var oldqueue = this._queuedApiCall;
this._fieldApiTimer = 0;
this._queuedApiCall = {};
for ( var c in oldqueue )
{
if ( oldqueue[c] === undefined )
{
continue;
}
// perform the API call.
oldqueue[c]();
}
return this;
},
/**
* Set API return data for a given field
*
* @param {string} name field name
* @param {number} index field index
* @param {Array.