pip-services3-components-node
- Version 3.3.1
- Published
- 784 kB
- 3 dependencies
- MIT license
Install
npm i pip-services3-components-node
yarn add pip-services3-components-node
pnpm add pip-services3-components-node
Overview
Component definitions for Pip.Services in Node.js
Index
Classes
Interfaces
Enums
Classes
class CachedCounters
abstract class CachedCounters implements ICounters, IReconfigurable, ICounterTimingCallback {}
Abstract implementation of performance counters that measures and stores counters in memory. Child classes implement saving of the counters into various destinations.
### Configuration parameters ###
- options: - interval: interval in milliseconds to save current counters measurements (default: 5 mins) - reset_timeout: timeout in milliseconds to reset the counters. 0 disables the reset (default: 0)
constructor
constructor();
Creates a new CachedCounters object.
method beginTiming
beginTiming: (name: string) => CounterTiming;
Begins measurement of execution time interval. It returns [[CounterTiming]] object which has to be called at [[CounterTiming.endTiming]] to end the measurement and update the counter.
Parameter name
a counter name of Interval type.
Returns
a [[CounterTiming]] callback object to end timing.
method clear
clear: (name: string) => void;
Clears (resets) a counter specified by its name.
Parameter name
a counter name to clear.
method clearAll
clearAll: () => void;
Clears (resets) all counters.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method dump
dump: () => void;
Dumps (saves) the current values of counters.
See Also
[[save]]
method endTiming
endTiming: (name: string, elapsed: number) => void;
Ends measurement of execution elapsed time and updates specified counter.
Parameter name
a counter name
Parameter elapsed
execution elapsed time in milliseconds to update the counter.
See Also
[[CounterTiming.endTiming]]
method get
get: (name: string, type: CounterType) => Counter;
Gets a counter specified by its name. It counter does not exist or its type doesn't match the specified type it creates a new one.
Parameter name
a counter name to retrieve.
Parameter type
a counter type.
Returns
an existing or newly created counter of the specified type.
method getAll
getAll: () => Counter[];
Gets all captured counters.
Returns
a list with counters.
method getInterval
getInterval: () => number;
Gets the counters dump/save interval.
Returns
the interval in milliseconds.
method increment
increment: (name: string, value: number) => void;
Increments counter by given value.
Parameter name
a counter name of Increment type.
Parameter value
a value to add to the counter.
method incrementOne
incrementOne: (name: string) => void;
Increments counter by 1.
Parameter name
a counter name of Increment type.
method last
last: (name: string, value: number) => void;
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
Parameter name
a counter name of Last type.
Parameter value
a last value to record.
method save
protected abstract save: (counters: Counter[]) => void;
Saves the current counters measurements.
Parameter counters
current counters measurements to be saves.
method setInterval
setInterval: (value: number) => void;
Sets the counters dump/save interval.
Parameter value
a new interval in milliseconds.
method stats
stats: (name: string, value: number) => void;
Calculates min/average/max statistics based on the current and previous values.
Parameter name
a counter name of Statistics type
Parameter value
a value to update statistics
method timestamp
timestamp: (name: string, value: Date) => void;
Records the given timestamp.
Parameter name
a counter name of Timestamp type.
Parameter value
a timestamp to record.
method timestampNow
timestampNow: (name: string) => void;
Records the current time as a timestamp.
Parameter name
a counter name of Timestamp type.
method update
protected update: () => void;
Makes counter measurements as updated and dumps them when timeout expires.
See Also
[[dump]]
class CachedLogger
abstract class CachedLogger extends Logger {}
Abstract logger that caches captured log messages in memory and periodically dumps them. Child classes implement saving cached messages to their specified destinations.
### Configuration parameters ###
- level: maximum log level to capture - source: source (context) name - options: - interval: interval in milliseconds to save log messages (default: 10 seconds) - max_cache_size: maximum number of messages stored in this cache (default: 100)
### References ###
- *:context-info:*:*:1.0 (optional) [[ContextInfo]] to detect the context id and specify counters source
See Also
[[ILogger]]
[[Logger]]
[[LogMessage]]
constructor
constructor();
Creates a new instance of the logger.
method clear
clear: () => void;
Clears (removes) all cached log messages.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method dump
dump: () => void;
Dumps (writes) the currently cached log messages.
See Also
[[write]]
method save
protected abstract save: ( messages: LogMessage[], callback: (err: any) => void) => void;
Saves log messages from the cache.
Parameter messages
a list with log messages
Parameter callback
callback function that receives error or null for success.
method update
protected update: () => void;
Makes message cache as updated and dumps it when timeout expires.
See Also
[[dump]]
method write
protected write: ( level: LogLevel, correlationId: string, error: Error, message: string) => void;
Writes a log message to the logger destination.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
class CachedTracer
abstract class CachedTracer implements ITracer, IReconfigurable, IReferenceable {}
Abstract tracer that caches recorded traces in memory and periodically dumps them. Child classes implement saving cached traces to their specified destinations.
### Configuration parameters ###
- source: source (context) name - options: - interval: interval in milliseconds to save log messages (default: 10 seconds) - max_cache_size: maximum number of messages stored in this cache (default: 100)
### References ###
- *:context-info:*:*:1.0 (optional) [[ContextInfo]] to detect the context id and specify counters source
See Also
[[ITracer]]
[[OperationTrace]]
constructor
constructor();
Creates a new instance of the logger.
method beginTrace
beginTrace: ( correlationId: string, component: string, operation: string) => TraceTiming;
Begings recording an operation trace
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Returns
a trace timing object.
method clear
clear: () => void;
Clears (removes) all cached log messages.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method dump
dump: () => void;
Dumps (writes) the currently cached log messages.
See Also
[[write]]
method failure
failure: ( correlationId: string, component: string, operation: string, error: Error, duration: number) => void;
Records an operation failure with its name, duration and error
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter error
an error object associated with this trace.
Parameter duration
execution duration in milliseconds.
method save
protected abstract save: ( messages: OperationTrace[], callback: (err: any) => void) => void;
Saves log messages from the cache.
Parameter messages
a list with log messages
Parameter callback
callback function that receives error or null for success.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method trace
trace: ( correlationId: string, component: string, operation: string, duration: number) => void;
Records an operation trace with its name and duration
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter duration
execution duration in milliseconds.
method update
protected update: () => void;
Makes trace cache as updated and dumps it when timeout expires.
See Also
[[dump]]
method write
protected write: ( correlationId: string, component: string, operation: string, error: Error, duration: number) => void;
Writes a log message to the logger destination.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter error
an error object associated with this trace.
Parameter duration
execution duration in milliseconds.
class CacheEntry
class CacheEntry {}
Data object to store cached values with their keys used by [[MemoryCache]]
constructor
constructor(key: string, value: any, timeout: number);
Creates a new instance of the cache entry and assigns its values.
Parameter key
a unique key to locate the value.
Parameter value
a value to be stored.
Parameter timeout
expiration timeout in milliseconds.
method getExpiration
getExpiration: () => number;
Gets the expiration timeout.
Returns
the expiration timeout in milliseconds.
method getKey
getKey: () => string;
Gets the key to locate the cached value.
Returns
the value key.
method getValue
getValue: () => any;
Gets the cached value.
Returns
the value object.
method isExpired
isExpired: () => boolean;
Checks if this value already expired.
Returns
true if the value already expires and false otherwise.
method setValue
setValue: (value: any, timeout: number) => void;
Sets a new value and extends its expiration.
Parameter value
a new cached value.
Parameter timeout
a expiration timeout in milliseconds.
class Component
class Component implements IConfigurable, IReferenceable {}
Abstract component that supportes configurable dependencies, logging and performance counters.
### Configuration parameters ###
- __dependencies:__ - [dependency name 1]: Dependency 1 locator (descriptor) - ... - [dependency name N]: Dependency N locator (descriptor)
### References ###
- *:counters:*:*:1.0 (optional) [[ICounters]] components to pass collected measurements - *:logger:*:*:1.0 (optional) [[ILogger]] components to pass log messages - *:tracer:*:*:1.0 (optional) [[ITracer]] components to record traces - ... References must match configured dependencies.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
class CompositeConnectionResolver
class CompositeConnectionResolver implements IReferenceable, IConfigurable {}
Helper class that resolves connection and credential parameters, validates them and generates connection options.
### Configuration parameters ###
- connection(s): - discovery_key: (optional) a key to retrieve the connection from [[https://pip-services3-node.github.io/pip-services3-components-node/interfaces/connect.idiscovery.html IDiscovery]] - protocol: communication protocol - host: host name or IP address - port: port number - uri: resource URI or connection string with all parameters in it - credential(s): - store_key: (optional) a key to retrieve the credentials from [[https://pip-services3-node.github.io/pip-services3-components-node/interfaces/auth.icredentialstore.html ICredentialStore]] - username: user name - password: user password
### References ###
- *:discovery:*:*:1.0 (optional) [[https://pip-services3-node.github.io/pip-services3-components-node/interfaces/connect.idiscovery.html IDiscovery]] services to resolve connections - *:credential-store:*:*:1.0 (optional) Credential stores to resolve credentials
method compose
compose: ( correlationId: string, connections: ConnectionParams[], credential: CredentialParams, parameters: ConfigParams, callback: (err: any, options: any) => void) => void;
Composes Composite connection options from connection and credential parameters.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter connections
connection parameters
Parameter credential
credential parameters
Parameter parameters
optional parameters
Parameter callback
callback function that receives resolved options or error.
method composeOptions
protected composeOptions: ( connections: ConnectionParams[], credential: CredentialParams, parameters: ConfigParams) => ConfigParams;
Composes connection and credential parameters into connection options. This method can be overriden in child classes.
Parameter connections
a list of connection parameters
Parameter credential
credential parameters
Parameter parameters
optional parameters
Returns
a composed connection options.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method finalizeOptions
protected finalizeOptions: (options: ConfigParams) => ConfigParams;
Finalize merged options This method can be overriden in child classes.
Parameter options
connection options
Returns
finalized connection options
method mergeConnection
protected mergeConnection: ( options: ConfigParams, connection: ConnectionParams) => ConfigParams;
Merges connection options with connection parameters This method can be overriden in child classes.
Parameter options
connection options
Parameter connection
connection parameters to be merged
Returns
merged connection options.
method mergeCredential
protected mergeCredential: ( options: ConfigParams, credential: CredentialParams) => ConfigParams;
Merges connection options with credential parameters This method can be overriden in child classes.
Parameter options
connection options
Parameter credential
credential parameters to be merged
Returns
merged connection options.
method mergeOptional
protected mergeOptional: ( options: ConfigParams, parameters: ConfigParams) => ConfigParams;
Merges connection options with optional parameters This method can be overriden in child classes.
Parameter options
connection options
Parameter parameters
optional parameters to be merged
Returns
merged connection options.
method resolve
resolve: ( correlationId: string, callback: (err: any, options: ConfigParams) => void) => void;
Resolves connection options from connection and credential parameters.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter callback
callback function that receives resolved options or error.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method validateConnection
protected validateConnection: ( correlationId: string, connection: ConnectionParams) => any;
Validates connection parameters. This method can be overriden in child classes.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter connection
connection parameters to be validated
Returns
error or null if validation was successful
method validateCredential
protected validateCredential: ( correlationId: string, credential: CredentialParams) => any;
Validates credential parameters. This method can be overriden in child classes.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter credential
credential parameters to be validated
Returns
error or null if validation was successful
class CompositeCounters
class CompositeCounters implements ICounters, ICounterTimingCallback, IReferenceable {}
Aggregates all counters from component references under a single component.
It allows to capture metrics and conveniently send them to multiple destinations.
### References ###
- *:counters:*:*:1.0 (optional) [[ICounters]] components to pass collected measurements
See Also
[[ICounters]]
### Example ###
class MyComponent implements IReferenceable { private _counters: CompositeCounters = new CompositeCounters();
public setReferences(references: IReferences): void { this._counters.setReferences(references); ... }
public myMethod(): void { this._counters.increment("mycomponent.mymethod.calls"); var timing = this._counters.beginTiming("mycomponent.mymethod.exec_time"); try { ... } finally { timing.endTiming(); } } }
constructor
constructor(references?: IReferences);
Creates a new instance of the counters.
Parameter references
references to locate the component dependencies.
method beginTiming
beginTiming: (name: string) => CounterTiming;
Begins measurement of execution time interval. It returns [[CounterTiming]] object which has to be called at [[CounterTiming.endTiming]] to end the measurement and update the counter.
Parameter name
a counter name of Interval type.
Returns
a [[CounterTiming]] callback object to end timing.
method endTiming
endTiming: (name: string, elapsed: number) => void;
Ends measurement of execution elapsed time and updates specified counter.
Parameter name
a counter name
Parameter elapsed
execution elapsed time in milliseconds to update the counter.
See Also
[[CounterTiming.endTiming]]
method increment
increment: (name: string, value: number) => void;
Increments counter by given value.
Parameter name
a counter name of Increment type.
Parameter value
a value to add to the counter.
method incrementOne
incrementOne: (name: string) => void;
Increments counter by 1.
Parameter name
a counter name of Increment type.
method last
last: (name: string, value: number) => void;
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
Parameter name
a counter name of Last type.
Parameter value
a last value to record.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method stats
stats: (name: string, value: number) => void;
Calculates min/average/max statistics based on the current and previous values.
Parameter name
a counter name of Statistics type
Parameter value
a value to update statistics
method timestamp
timestamp: (name: string, value: Date) => void;
Records the given timestamp.
Parameter name
a counter name of Timestamp type.
Parameter value
a timestamp to record.
method timestampNow
timestampNow: (name: string) => void;
Records the current time as a timestamp.
Parameter name
a counter name of Timestamp type.
class CompositeFactory
class CompositeFactory implements IFactory {}
Aggregates multiple factories into a single factory component. When a new component is requested, it iterates through factories to locate the one able to create the requested component.
This component is used to conveniently keep all supported factories in a single place.
### Example ###
let factory = new CompositeFactory(); factory.add(new DefaultLoggerFactory()); factory.add(new DefaultCountersFactory());
let loggerLocator = new Descriptor("*", "logger", "*", "*", "1.0"); factory.canCreate(loggerLocator); // Result: Descriptor("pip-service", "logger", "null", "default", "1.0") factory.create(loggerLocator); // Result: created NullLogger
constructor
constructor(...factories: IFactory[]);
Creates a new instance of the factory.
Parameter factories
a list of factories to embed into this factory.
method add
add: (factory: IFactory) => void;
Adds a factory into the list of embedded factories.
Parameter factory
a factory to be added.
method canCreate
canCreate: (locator: any) => any;
Checks if this factory is able to create component by given locator.
This method searches for all registered components and returns a locator for component it is able to create that matches the given locator. If the factory is not able to create a requested component is returns null.
Parameter locator
a locator to identify component to be created.
Returns
a locator for a component that the factory is able to create.
method create
create: (locator: any) => any;
Creates a component identified by given locator.
Parameter locator
a locator to identify component to be created.
Returns
the created component.
Throws
a CreateException if the factory is not able to create the component.
method remove
remove: (factory: IFactory) => void;
Removes a factory from the list of embedded factories.
Parameter factory
the factory to remove.
class CompositeLogger
class CompositeLogger extends Logger implements IReferenceable {}
Aggregates all loggers from component references under a single component.
It allows to log messages and conveniently send them to multiple destinations.
### References ###
- *:logger:*:*:1.0 (optional) [[ILogger]] components to pass log messages
See Also
[[ILogger]]
### Example ###
class MyComponent implements IConfigurable, IReferenceable { private _logger: CompositeLogger = new CompositeLogger();
public configure(config: ConfigParams): void { this._logger.configure(config); ... }
public setReferences(references: IReferences): void { this._logger.setReferences(references); ... }
public myMethod(string correlationId): void { this._logger.debug(correlationId, "Called method mycomponent.mymethod"); ... } }
constructor
constructor(references?: IReferences);
Creates a new instance of the logger.
Parameter references
references to locate the component dependencies.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method write
protected write: ( level: LogLevel, correlationId: string, error: Error, message: string) => void;
Writes a log message to the logger destination(s).
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
class CompositeTracer
class CompositeTracer implements ITracer, IReferenceable {}
Aggregates all tracers from component references under a single component.
It allows to record traces and conveniently send them to multiple destinations.
### References ###
- *:tracer:*:*:1.0 (optional) [[ITracer]] components to pass operation traces
See Also
[[ITracer]]
### Example ###
class MyComponent implements IReferenceable { private _tracer: CompositeTracer = new CompositeTracer();
public setReferences(references: IReferences): void { this._tracer.setReferences(references); ... }
public myMethod(correlatonId: string): void { var timing = this._tracer.beginTrace(correlationId, "mycomponent", "mymethod"); try { ... timing.endTrace(); } catch (err) { timing.endFailure(err); } } }
constructor
constructor(references?: IReferences);
Creates a new instance of the tracer.
Parameter references
references to locate the component dependencies.
method beginTrace
beginTrace: ( correlationId: string, component: string, operation: string) => TraceTiming;
Begings recording an operation trace
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Returns
a trace timing object.
method failure
failure: ( correlationId: string, component: string, operation: string, error: Error, duration: number) => void;
Records an operation failure with its name, duration and error
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter error
an error object associated with this trace.
Parameter duration
execution duration in milliseconds.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method trace
trace: ( correlationId: string, component: string, operation: string, duration: number) => void;
Records an operation trace with its name and duration
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter duration
execution duration in milliseconds.
class ConfigReader
abstract class ConfigReader implements IConfigurable {}
Abstract config reader that supports configuration parameterization.
### Configuration parameters ###
- __parameters:__ this entire section is used as template parameters - ...
See Also
[[IConfigReader]]
constructor
constructor();
Creates a new instance of the config reader.
method addChangeListener
addChangeListener: (listener: INotifiable) => void;
Adds a listener that will be notified when configuration is changed
Parameter listener
a listener to be added.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method parameterize
protected parameterize: (config: string, parameters: ConfigParams) => string;
Parameterized configuration template given as string with dynamic parameters.
The method uses [[https://handlebarsjs.com Handlebars]] template engine.
Parameter config
a string with configuration template to be parameterized
Parameter parameters
dynamic parameters to inject into the template
Returns
a parameterized configuration string.
method readConfig
abstract readConfig: ( correlationId: string, parameters: ConfigParams, callback: (err: any, config: ConfigParams) => void) => void;
Reads configuration and parameterize it with given values.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration or null to skip parameterization.
Parameter callback
callback function that receives configuration or error.
method removeChangeListener
removeChangeListener: (listener: INotifiable) => void;
Remove a previously added change listener.
Parameter listener
a listener to be removed.
class ConnectionParams
class ConnectionParams extends ConfigParams {}
Contains connection parameters to connect to external services. They are used together with credential parameters, but usually stored separately from more protected sensitive values.
### Configuration parameters ###
- discovery_key: key to retrieve parameters from discovery service - protocol: connection protocol like http, https, tcp, udp - host: host name or IP address - port: port number - uri: resource URI or connection string with all parameters in it
In addition to standard parameters ConnectionParams may contain any number of custom parameters
See Also
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/config.configparams.html ConfigParams]]
[[CredentialParams]]
[[ConnectionResolver]]
[[IDiscovery]]
### Example ###
Example ConnectionParams object usage:
let connection = ConnectionParams.fromTuples( "protocol", "http", "host", "10.1.1.100", "port", "8080", "cluster", "mycluster" );
let host = connection.getHost(); // Result: "10.1.1.100" let port = connection.getPort(); // Result: 8080 let cluster = connection.getAsNullableString("cluster"); // Result: "mycluster"
constructor
constructor(values?: any);
Creates a new connection parameters and fills it with values.
Parameter values
(optional) an object to be converted into key-value pairs to initialize this connection.
method fromConfig
static fromConfig: (config: ConfigParams) => ConnectionParams;
Retrieves a single ConnectionParams from configuration parameters from "connection" section. If "connections" section is present instead, then is returns only the first connection element.
Parameter config
ConnectionParams, containing a section named "connection(s)".
Returns
the generated ConnectionParams object.
See Also
[[manyFromConfig]]
method fromString
static fromString: (line: string) => ConnectionParams;
Creates a new ConnectionParams object filled with key-value pairs serialized as a string.
Parameter line
a string with serialized key-value pairs as "key1=value1;key2=value2;..." Example: "Key1=123;Key2=ABC;Key3=2016-09-16T00:00:00.00Z"
Returns
a new ConnectionParams object.
See Also
[[StringValueMap.fromString]]
method fromTuples
static fromTuples: (...tuples: any[]) => ConnectionParams;
Creates a new ConnectionParams object filled with provided key-value pairs called tuples. Tuples parameters contain a sequence of key1, value1, key2, value2, ... pairs.
Parameter tuples
the tuples to fill a new ConnectionParams object.
Returns
a new ConnectionParams object.
method getDiscoveryKey
getDiscoveryKey: () => string;
Gets the key to retrieve this connection from [[DiscoveryService]]. If this key is null, than all parameters are already present.
Returns
the discovery key to retrieve connection.
See Also
[[useDiscovery]]
method getHost
getHost: () => string;
Gets the host name or IP address.
Returns
the host name or IP address.
method getPort
getPort: () => number;
Gets the port number.
Returns
the port number.
method getPortWithDefault
getPortWithDefault: (defaultPort: number) => number;
Gets the port number with default value.
Parameter defaultPort
a default port number.
Returns
the port number.
method getProtocol
getProtocol: () => string;
Gets the connection protocol.
Returns
the connection protocol or the default value if it's not set.
method getProtocolWithDefault
getProtocolWithDefault: (defaultValue: string) => string;
Gets the connection protocol with default value.
Parameter defaultValue
(optional) the default protocol
Returns
the connection protocol or the default value if it's not set.
method getUri
getUri: () => string;
Gets the resource URI or connection string. Usually it includes all connection parameters in it.
Returns
the resource URI or connection string.
method manyFromConfig
static manyFromConfig: (config: ConfigParams) => ConnectionParams[];
Retrieves all ConnectionParams from configuration parameters from "connections" section. If "connection" section is present instead, than it returns a list with only one ConnectionParams.
Parameter config
a configuration parameters to retrieve connections
Returns
a list of retrieved ConnectionParams
method setDiscoveryKey
setDiscoveryKey: (value: string) => void;
Sets the key to retrieve these parameters from [[DiscoveryService]].
Parameter value
a new key to retrieve connection.
method setHost
setHost: (value: string) => void;
Sets the host name or IP address.
Parameter value
a new host name or IP address.
method setPort
setPort: (value: number) => void;
Sets the port number.
Parameter value
a new port number.
See Also
[[getHost]]
method setProtocol
setProtocol: (value: string) => void;
Sets the connection protocol.
Parameter value
a new connection protocol.
method setUri
setUri: (value: string) => void;
Sets the resource URI or connection string.
Parameter value
a new resource URI or connection string.
method useDiscovery
useDiscovery: () => boolean;
Checks if these connection parameters shall be retrieved from [[DiscoveryService]]. The connection parameters are redirected to [[DiscoveryService]] when discovery_key parameter is set.
Returns
true if connection shall be retrieved from [[DiscoveryService]]
See Also
[[getDiscoveryKey]]
class ConnectionResolver
class ConnectionResolver {}
Helper class to retrieve component connections.
If connections are configured to be retrieved from [[IDiscovery]], it automatically locates [[IDiscovery]] in component references and retrieve connections from there using discovery_key parameter.
### Configuration parameters ###
- __connection:__ - discovery_key: (optional) a key to retrieve the connection from [[https://pip-services3-node.github.io/pip-services3-components-node/interfaces/connect.idiscovery.html IDiscovery]] - ... other connection parameters
- __connections:__ alternative to connection - [connection params 1]: first connection parameters - ... connection parameters for key 1 - [connection params N]: Nth connection parameters - ... connection parameters for key N
### References ###
- *:discovery:*:*:1.0 (optional) [[https://pip-services3-node.github.io/pip-services3-components-node/interfaces/connect.idiscovery.html IDiscovery]] services to resolve connections
See Also
[[ConnectionParams]]
[[IDiscovery]]
### Example ###
let config = ConfigParams.fromTuples( "connection.host", "10.1.1.100", "connection.port", 8080 );
let connectionResolver = new ConnectionResolver(); connectionResolver.configure(config); connectionResolver.setReferences(references);
connectionResolver.resolve("123", (err, connection) => { // Now use connection... });
constructor
constructor(config?: ConfigParams, references?: IReferences);
Creates a new instance of connection resolver.
Parameter config
(optional) component configuration parameters
Parameter references
(optional) component references
method add
add: (connection: ConnectionParams) => void;
Adds a new connection to component connections
Parameter connection
new connection parameters to be added
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method getAll
getAll: () => ConnectionParams[];
Gets all connections configured in component configuration.
Redirect to Discovery services is not done at this point. If you need fully fleshed connection use [[resolve]] method instead.
Returns
a list with connection parameters
method register
register: ( correlationId: string, connection: ConnectionParams, callback: (err: any) => void) => void;
Registers the given connection in all referenced discovery services. This method can be used for dynamic service discovery.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter connection
a connection to register.
Parameter callback
callback function that receives registered connection or error.
See Also
[[IDiscovery]]
method resolve
resolve: ( correlationId: string, callback: (err: any, result: ConnectionParams) => void) => void;
Resolves a single component connection. If connections are configured to be retrieved from Discovery service it finds a [[IDiscovery]] and resolves the connection there.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter callback
callback function that receives resolved connection or error.
See Also
[[IDiscovery]]
method resolveAll
resolveAll: ( correlationId: string, callback: (err: any, result: ConnectionParams[]) => void) => void;
Resolves all component connection. If connections are configured to be retrieved from Discovery service it finds a [[IDiscovery]] and resolves the connection there.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter callback
callback function that receives resolved connections or error.
See Also
[[IDiscovery]]
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
class ConnectionUtils
class ConnectionUtils {}
A set of utility functions to process connection parameters
method composeUri
static composeUri: ( options: ConfigParams, defaultProtocol: string, defaultPort: number) => string;
Composes URI from config parameters. The result URI will be in the following form: protocol://username@password@host1:port1,host2:port2,...?param1=abc¶m2=xyz&...
Parameter options
configuration parameters
Parameter defaultProtocol
a default protocol
Parameter defaultPort
a default port
Returns
a composed URI
method concat
static concat: ( options1: ConfigParams, options2: ConfigParams, ...keys: string[]) => ConfigParams;
Concatinates two options by combining duplicated properties into comma-separated list
Parameter options1
first options to merge
Parameter options2
second options to merge
Parameter keys
when define it limits only to specific keys
method exclude
static exclude: (options: ConfigParams, ...keys: string[]) => ConfigParams;
Excludes specified keys from the config parameters.
Parameter options
configuration parameters to be processed.
Parameter keys
a list of keys to be excluded.
Returns
a processed config parameters.
method include
static include: (options: ConfigParams, ...keys: string[]) => ConfigParams;
Includes specified keys from the config parameters.
Parameter options
configuration parameters to be processed.
Parameter keys
a list of keys to be included.
Returns
a processed config parameters.
method parseUri
static parseUri: ( uri: string, defaultProtocol: string, defaultPort: number) => ConfigParams;
Parses URI into config parameters. The URI shall be in the following form: protocol://username@password@host1:port1,host2:port2,...?param1=abc¶m2=xyz&...
Parameter uri
the URI to be parsed
Parameter defaultProtocol
a default protocol
Parameter defaultPort
a default port
Returns
a configuration parameters with URI elements
class ConsoleLogger
class ConsoleLogger extends Logger {}
Logger that writes log messages to console.
Errors are written to standard err stream and all other messages to standard out stream.
### Configuration parameters ###
- level: maximum log level to capture - source: source (context) name
### References ###
- *:context-info:*:*:1.0 (optional) [[ContextInfo]] to detect the context id and specify counters source
See Also
[[Logger]]
### Example ###
let logger = new ConsoleLogger(); logger.setLevel(LogLevel.debug);
logger.error("123", ex, "Error occured: %s", ex.message); logger.debug("123", "Everything is OK.");
constructor
constructor();
Creates a new instance of the logger.
method write
protected write: ( level: LogLevel, correlationId: string, error: Error, message: string) => void;
Writes a log message to the logger destination.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
class ContextInfo
class ContextInfo implements IReconfigurable {}
Context information component that provides detail information about execution context: container or/and process.
Most often ContextInfo is used by logging and performance counters to identify source of the collected logs and metrics.
### Configuration parameters ###
- name: the context (container or process) name - description: human-readable description of the context - properties: entire section of additional descriptive properties - ...
### Example ###
let contextInfo = new ContextInfo(); contextInfo.configure(ConfigParams.fromTuples( "name", "MyMicroservice", "description", "My first microservice" ));
context.name; // Result: "MyMicroservice" context.contextId; // Possible result: "mylaptop" context.startTime; // Possible result: 2018-01-01:22:12:23.45Z context.uptime; // Possible result: 3454345
constructor
constructor(name?: string, description?: string);
Creates a new instance of this context info.
Parameter name
(optional) a context name.
Parameter description
(optional) a human-readable description of the context.
property contextId
contextId: string;
Gets the unique context id. Usually it is the current host name.
Returns
the unique context id.
property description
description: string;
Gets the human-readable description of the context.
Returns
the human-readable description of the context.
property name
name: string;
Gets the context name.
Returns
the context name
property properties
properties: any;
Gets context additional parameters.
Returns
a JSON object with additional context parameters.
property startTime
startTime: Date;
Gets the context start time.
Returns
the context start time.
property uptime
readonly uptime: number;
Calculates the context uptime as from the start time.
Returns
number of milliseconds from the context start time.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method fromConfig
static fromConfig: (config: ConfigParams) => ContextInfo;
Creates a new ContextInfo and sets its configuration parameters.
Parameter config
configuration parameters for the new ContextInfo.
Returns
a newly created ContextInfo
class Counter
class Counter {}
Data object to store measurement for a performance counter. This object is used by [[CachedCounters]] to store counters.
constructor
constructor(name: string, type: CounterType);
Creates a instance of the data obejct
Parameter name
a counter name.
Parameter type
a counter type.
property average
average: number;
The average value
property count
count: number;
The total count
property last
last: number;
The last recorded value
property max
max: number;
The maximum value
property min
min: number;
The minimum value
property name
name: string;
The counter unique name
property time
time: Date;
The recorded timestamp
property type
type: CounterType;
The counter type that defines measurement algorithm
class CounterTiming
class CounterTiming {}
Callback object returned by ICounters.beginTiming to end timing of execution block and update the associated counter.
### Example ###
let timing = counters.beginTiming("mymethod.exec_time"); try { ... } finally { timing.endTiming(); }
constructor
constructor(counter?: string, callback?: ICounterTimingCallback);
Creates a new instance of the timing callback object.
Parameter counter
an associated counter name
Parameter callback
a callback that shall be called when endTiming is called.
method endTiming
endTiming: () => void;
Ends timing of an execution block, calculates elapsed time and updates the associated counter.
class CreateException
class CreateException extends InternalException {}
Error raised when factory is not able to create requested component.
See Also
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/errors.internalexception.html InternalException]] (in the PipServices "Commons" package)
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/errors.applicationexception.html ApplicationException]] (in the PipServices "Commons" package)
constructor
constructor(correlationId: string, messageOrLocator: any);
Creates an error instance and assigns its values.
Parameter correlation_id
(optional) a unique transaction id to trace execution through call chain.
Parameter messageOrLocator
human-readable error or locator of the component that cannot be created.
class CredentialParams
class CredentialParams extends ConfigParams {}
Contains credentials to authenticate against external services. They are used together with connection parameters, but usually stored in a separate store, protected from unauthorized access.
### Configuration parameters ###
- store_key: key to retrieve parameters from credential store - username: user name - user: alternative to username - password: user password - pass: alternative to password - access_id: application access id - client_id: alternative to access_id - access_key: application secret key - client_key: alternative to access_key - secret_key: alternative to access_key
In addition to standard parameters CredentialParams may contain any number of custom parameters
See Also
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/config.configparams.html ConfigParams]]
[[ConnectionParams]]
[[CredentialResolver]]
[[ICredentialStore]]
### Example ###
let credential = CredentialParams.fromTuples( "user", "jdoe", "pass", "pass123", "pin", "321" );
let username = credential.getUsername(); // Result: "jdoe" let password = credential.getPassword(); // Result: "pass123" let pin = credential.getAsNullableString("pin"); // Result: 321
constructor
constructor(values?: any);
Creates a new credential parameters and fills it with values.
Parameter values
(optional) an object to be converted into key-value pairs to initialize these credentials.
method fromConfig
static fromConfig: (config: ConfigParams) => CredentialParams;
Retrieves a single CredentialParams from configuration parameters from "credential" section. If "credentials" section is present instead, then is returns only the first credential element.
Parameter config
ConfigParams, containing a section named "credential(s)".
Returns
the generated CredentialParams object.
See Also
[[manyFromConfig]]
method fromString
static fromString: (line: string) => CredentialParams;
Creates a new CredentialParams object filled with key-value pairs serialized as a string.
Parameter line
a string with serialized key-value pairs as "key1=value1;key2=value2;..." Example: "Key1=123;Key2=ABC;Key3=2016-09-16T00:00:00.00Z"
Returns
a new CredentialParams object.
method fromTuples
static fromTuples: (...tuples: any[]) => CredentialParams;
Creates a new CredentialParams object filled with provided key-value pairs called tuples. Tuples parameters contain a sequence of key1, value1, key2, value2, ... pairs.
Parameter tuples
the tuples to fill a new CredentialParams object.
Returns
a new CredentialParams object.
method getAccessId
getAccessId: () => string;
Gets the application access id. The value can be stored in parameters "access_id" pr "client_id"
Returns
the application access id.
method getAccessKey
getAccessKey: () => string;
Gets the application secret key. The value can be stored in parameters "access_key", "client_key" or "secret_key".
Returns
the application secret key.
method getPassword
getPassword: () => string;
Get the user password. The value can be stored in parameters "password" or "pass".
Returns
the user password.
method getStoreKey
getStoreKey: () => string;
Gets the key to retrieve these credentials from [[CredentialStore]]. If this key is null, than all parameters are already present.
Returns
the store key to retrieve credentials.
See Also
[[useCredentialStore]]
method getUsername
getUsername: () => string;
Gets the user name. The value can be stored in parameters "username" or "user".
Returns
the user name.
method manyFromConfig
static manyFromConfig: (config: ConfigParams) => CredentialParams[];
Retrieves all CredentialParams from configuration parameters from "credentials" section. If "credential" section is present instead, than it returns a list with only one CredentialParams.
Parameter config
a configuration parameters to retrieve credentials
Returns
a list of retrieved CredentialParams
method setAccessId
setAccessId: (value: string) => void;
Sets the application access id.
Parameter value
a new application access id.
method setAccessKey
setAccessKey: (value: string) => void;
Sets the application secret key.
Parameter value
a new application secret key.
method setPassword
setPassword: (value: string) => void;
Sets the user password.
Parameter value
a new user password.
method setStoreKey
setStoreKey: (value: string) => void;
Sets the key to retrieve these parameters from [[CredentialStore]].
Parameter value
a new key to retrieve credentials.
method setUsername
setUsername: (value: string) => void;
Sets the user name.
Parameter value
a new user name.
method useCredentialStore
useCredentialStore: () => boolean;
Checks if these credential parameters shall be retrieved from [[CredentialStore]]. The credential parameters are redirected to [[CredentialStore]] when store_key parameter is set.
Returns
true if credentials shall be retrieved from [[CredentialStore]]
See Also
[[getStoreKey]]
class CredentialResolver
class CredentialResolver {}
Helper class to retrieve component credentials.
If credentials are configured to be retrieved from [[ICredentialStore]], it automatically locates [[ICredentialStore]] in component references and retrieve credentials from there using store_key parameter.
### Configuration parameters ###
__credential:__ - store_key: (optional) a key to retrieve the credentials from [[ICredentialStore]] - ... other credential parameters
__credentials:__ alternative to credential - [credential params 1]: first credential parameters - ... credential parameters for key 1 - ... - [credential params N]: Nth credential parameters - ... credential parameters for key N
### References ###
- *:credential-store:*:*:1.0 (optional) Credential stores to resolve credentials
See Also
[[CredentialParams]]
[[ICredentialStore]]
### Example ###
let config = ConfigParams.fromTuples( "credential.user", "jdoe", "credential.pass", "pass123" );
let credentialResolver = new CredentialResolver(); credentialResolver.configure(config); credentialResolver.setReferences(references);
credentialResolver.lookup("123", (err, credential) => { // Now use credential... });
constructor
constructor(config?: ConfigParams, references?: IReferences);
Creates a new instance of credentials resolver.
Parameter config
(optional) component configuration parameters
Parameter references
(optional) component references
method add
add: (credential: CredentialParams) => void;
Adds a new credential to component credentials
Parameter credential
new credential parameters to be added
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method getAll
getAll: () => CredentialParams[];
Gets all credentials configured in component configuration.
Redirect to CredentialStores is not done at this point. If you need fully fleshed credential use [[lookup]] method instead.
Returns
a list with credential parameters
method lookup
lookup: ( correlationId: string, callback: (err: any, result: CredentialParams) => void) => void;
Looks up component credential parameters. If credentials are configured to be retrieved from Credential store it finds a [[ICredentialStore]] and lookups credentials there.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter callback
callback function that receives resolved credential or error.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
class DefaultCacheFactory
class DefaultCacheFactory extends Factory {}
Creates [[ICache]] components by their descriptors.
See Also
[[Factory]]
[[ICache]]
[[MemoryCache]]
[[NullCache]]
constructor
constructor();
Create a new instance of the factory.
class DefaultConfigReaderFactory
class DefaultConfigReaderFactory extends Factory {}
Creates [[IConfigReader]] components by their descriptors.
See Also
[[Factory]]
[[MemoryConfigReader]]
[[JsonConfigReader]]
[[YamlConfigReader]]
constructor
constructor();
Create a new instance of the factory.
class DefaultCountersFactory
class DefaultCountersFactory extends Factory {}
Creates [[ICounters]] components by their descriptors.
See Also
[[Factory]]
[[NullCounters]]
[[LogCounters]]
[[CompositeCounters]]
constructor
constructor();
Create a new instance of the factory.
class DefaultCredentialStoreFactory
class DefaultCredentialStoreFactory extends Factory {}
Creates [[ICredentialStore]] components by their descriptors.
See Also
[[IFactory]]
[[ICredentialStore]]
[[MemoryCredentialStore]]
constructor
constructor();
Create a new instance of the factory.
class DefaultDiscoveryFactory
class DefaultDiscoveryFactory extends Factory {}
Creates [[https://pip-services3-node.github.io/pip-services3-components-node/interfaces/connect.idiscovery.html IDiscovery]] components by their descriptors.
See Also
[[Factory]]
[[IDiscovery]]
[[MemoryDiscovery]]
constructor
constructor();
Create a new instance of the factory.
class DefaultInfoFactory
class DefaultInfoFactory extends Factory {}
Creates information components by their descriptors.
See Also
[[IFactory]]
[[ContextInfo]]
constructor
constructor();
Create a new instance of the factory.
class DefaultLockFactory
class DefaultLockFactory extends Factory {}
Creates [[ILock]] components by their descriptors.
See Also
[[Factory]]
[[ILock]]
[[MemoryLock]]
[[NullLock]]
constructor
constructor();
Create a new instance of the factory.
class DefaultLoggerFactory
class DefaultLoggerFactory extends Factory {}
Creates [[ILogger]] components by their descriptors.
See Also
[[Factory]]
[[NullLogger]]
[[ConsoleLogger]]
[[CompositeLogger]]
constructor
constructor();
Create a new instance of the factory.
class DefaultTestFactory
class DefaultTestFactory extends Factory {}
Creates test components by their descriptors.
See Also
[[Factory]]
[[Shutdown]]
constructor
constructor();
Create a new instance of the factory.
class DefaultTracerFactory
class DefaultTracerFactory extends Factory {}
Creates [[ITracer]] components by their descriptors.
See Also
[[Factory]]
[[NullTracer]]
[[ConsoleTracer]]
[[CompositeTracer]]
constructor
constructor();
Create a new instance of the factory.
class Factory
class Factory implements IFactory {}
Basic component factory that creates components using registered types and factory functions.
#### Example ###
let factory = new Factory();
factory.registerAsType( new Descriptor("mygroup", "mycomponent1", "default", "*", "1.0"), MyComponent1 ); factory.register( new Descriptor("mygroup", "mycomponent2", "default", "*", "1.0"), (locator) => { return new MyComponent2(); } );
factory.create(new Descriptor("mygroup", "mycomponent1", "default", "name1", "1.0")) factory.create(new Descriptor("mygroup", "mycomponent2", "default", "name2", "1.0"))
See Also
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/refer.descriptor.html Descriptor]]
[[IFactory]]
method canCreate
canCreate: (locator: any) => any;
Checks if this factory is able to create component by given locator.
This method searches for all registered components and returns a locator for component it is able to create that matches the given locator. If the factory is not able to create a requested component is returns null.
Parameter locator
a locator to identify component to be created.
Returns
a locator for a component that the factory is able to create.
method create
create: (locator: any) => any;
Creates a component identified by given locator.
Parameter locator
a locator to identify component to be created.
Returns
the created component.
Throws
a CreateException if the factory is not able to create the component.
method register
register: (locator: any, factory: (locator: any) => any) => void;
Registers a component using a factory method.
Parameter locator
a locator to identify component to be created.
Parameter factory
a factory function that receives a locator and returns a created component.
method registerAsType
registerAsType: (locator: any, type: any) => void;
Registers a component using its type (a constructor function).
Parameter locator
a locator to identify component to be created.
Parameter type
a component type.
class FileConfigReader
abstract class FileConfigReader extends ConfigReader {}
Abstract config reader that reads configuration from a file. Child classes add support for config files in their specific format like JSON, YAML or property files.
### Configuration parameters ###
- path: path to configuration file - parameters: this entire section is used as template parameters - ...
See Also
[[IConfigReader]]
[[ConfigReader]]
constructor
constructor(path?: string);
Creates a new instance of the config reader.
Parameter path
(optional) a path to configuration file.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method getPath
getPath: () => string;
Get the path to configuration file..
Returns
the path to configuration file.
method setPath
setPath: (path: string) => void;
Set the path to configuration file.
Parameter path
a new path to configuration file.
class JsonConfigReader
class JsonConfigReader extends FileConfigReader {}
Config reader that reads configuration from JSON file.
The reader supports parameterization using Handlebar template engine.
### Configuration parameters ###
- path: path to configuration file - parameters: this entire section is used as template parameters - ...
See Also
[[IConfigReader]]
[[FileConfigReader]]
### Example ###
======== config.json ====== { "key1": "{{KEY1_VALUE}}", "key2": "{{KEY2_VALUE}}" } ===========================
let configReader = new JsonConfigReader("config.json");
let parameters = ConfigParams.fromTuples("KEY1_VALUE", 123, "KEY2_VALUE", "ABC"); configReader.readConfig("123", parameters, (err, config) => { // Result: key1=123;key2=ABC });
constructor
constructor(path?: string);
Creates a new instance of the config reader.
Parameter path
(optional) a path to configuration file.
method readConfig
static readConfig: ( correlationId: string, path: string, parameters: ConfigParams) => ConfigParams;
Reads configuration and parameterize it with given values.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration
Parameter callback
callback function that receives configuration or error.
Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter file
a path to configuration file.
Parameter parameters
values to parameters the configuration.
Parameter callback
callback function that receives configuration or error.
method readObject
static readObject: ( correlationId: string, path: string, parameters: ConfigParams) => any;
Reads configuration file, parameterizes its content and converts it into JSON object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration.
Returns
a JSON object with configuration.
Reads configuration file, parameterizes its content and converts it into JSON object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter file
a path to configuration file.
Parameter parameters
values to parameters the configuration.
Returns
a JSON object with configuration.
class Lock
abstract class Lock implements ILock, IReconfigurable {}
Abstract lock that implements default lock acquisition routine.
### Configuration parameters ###
- __options:__ - retry_timeout: timeout in milliseconds to retry lock acquisition. (Default: 100)
See Also
[[ILock]]
method acquireLock
acquireLock: ( correlationId: string, key: string, ttl: number, timeout: number, callback: (err: any) => void) => void;
Makes multiple attempts to acquire a lock by its key within give time interval.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter timeout
a lock acquisition timeout.
Parameter callback
callback function that receives error or null for success.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method releaseLock
abstract releaseLock: ( correlationId: string, key: string, callback?: (err: any) => void) => void;
Releases prevously acquired lock by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to release.
Parameter callback
callback function that receives error or null for success.
method tryAcquireLock
abstract tryAcquireLock: ( correlationId: string, key: string, ttl: number, callback: (err: any, result: boolean) => void) => void;
Makes a single attempt to acquire a lock by its key. It returns immediately a positive or negative result.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter callback
callback function that receives a lock result or error.
class LogCounters
class LogCounters extends CachedCounters implements IReferenceable {}
Performance counters that periodically dumps counters measurements to logger.
### Configuration parameters ###
- __options:__ - interval: interval in milliseconds to save current counters measurements (default: 5 mins) - reset_timeout: timeout in milliseconds to reset the counters. 0 disables the reset (default: 0)
### References ###
- *:logger:*:*:1.0 [[ILogger]] components to dump the captured counters - *:context-info:*:*:1.0 (optional) [[ContextInfo]] to detect the context id and specify counters source
See Also
[[Counter]]
[[CachedCounters]]
[[CompositeLogger]]
### Example ###
let counters = new LogCounters(); counters.setReferences(References.fromTuples( new Descriptor("pip-services", "logger", "console", "default", "1.0"), new ConsoleLogger() ));
counters.increment("mycomponent.mymethod.calls"); let timing = counters.beginTiming("mycomponent.mymethod.exec_time"); try { ... } finally { timing.endTiming(); }
counters.dump();
constructor
constructor();
Creates a new instance of the counters.
method save
protected save: (counters: Counter[]) => void;
Saves the current counters measurements.
Parameter counters
current counters measurements to be saves.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
class Logger
abstract class Logger implements ILogger, IReconfigurable, IReferenceable {}
Abstract logger that captures and formats log messages. Child classes take the captured messages and write them to their specific destinations.
### Configuration parameters ###
Parameters to pass to the [[configure]] method for component configuration:
- level: maximum log level to capture - source: source (context) name
### References ###
- *:context-info:*:*:1.0 (optional) [[ContextInfo]] to detect the context id and specify counters source
See Also
[[ILogger]]
constructor
protected constructor();
Creates a new instance of the logger.
method composeError
protected composeError: (error: Error) => string;
Composes an human-readable error description
Parameter error
an error to format.
Returns
a human-reable error description.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method debug
debug: (correlationId: string, message: string, ...args: any[]) => void;
Logs a high-level debug information for troubleshooting.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method error
error: ( correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs recoverable application error.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method fatal
fatal: ( correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs fatal (unrecoverable) message that caused the process to crash.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method formatAndWrite
protected formatAndWrite: ( level: LogLevel, correlationId: string, error: Error, message: string, ...args: any[]) => void;
Formats the log message and writes it to the logger destination.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method getLevel
getLevel: () => LogLevel;
Gets the maximum log level. Messages with higher log level are filtered out.
Returns
the maximum log level.
method getSource
getSource: () => string;
Gets the source (context) name.
Returns
the source (context) name.
method info
info: (correlationId: string, message: string, ...args: any[]) => void;
Logs an important information message
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method log
log: ( level: LogLevel, correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs a message at specified log level.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method setLevel
setLevel: (value: LogLevel) => void;
Set the maximum log level.
Parameter value
a new maximum log level.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method setSource
setSource: (value: string) => void;
Sets the source (context) name.
Parameter value
a new source (context) name.
method trace
trace: (correlationId: string, message: string, ...args: any[]) => void;
Logs a low-level debug information for troubleshooting.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method warn
warn: (correlationId: string, message: string, ...args: any[]) => void;
Logs a warning that may or may not have a negative impact.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method write
protected abstract write: ( level: LogLevel, correlationId: string, error: Error, message: string) => void;
Writes a log message to the logger destination.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
class LogLevelConverter
class LogLevelConverter {}
Helper class to convert log level values.
See Also
[[LogLevel]]
method toInteger
static toInteger: (level: LogLevel) => number;
Converts log level to a number.
Parameter level
a log level to convert.
Returns
log level number value.
method toLogLevel
static toLogLevel: (value: any, defaultValue?: LogLevel) => LogLevel;
Converts numbers and strings to standard log level values.
Parameter value
a value to be converted
Parameter defaultValue
a default value if conversion is not possible
Returns
converted log level
method toString
static toString: (level: LogLevel) => string;
Converts log level to a string.
Parameter level
a log level to convert
Returns
log level name string.
See Also
[[LogLevel]]
class LogMessage
class LogMessage {}
Data object to store captured log messages. This object is used by [[CachedLogger]].
property correlation_id
correlation_id: string;
The transaction id to trace execution through call chain.
property error
error: ErrorDescription;
The description of the captured error
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/errors.errordescription.html ErrorDescription]] [[https://pip-services3-node.github.io/pip-services3-commons-node/classes/errors.applicationexception.html ApplicationException]]
property level
level: string;
This log level
property message
message: string;
The human-readable message
property source
source: string;
The source (context name)
property time
time: Date;
The time then message was generated
class LogTracer
class LogTracer implements IConfigurable, IReferenceable {}
Tracer that dumps recorded traces to logger.
### Configuration parameters ###
- __options:__ - log_level: log level to record traces (default: debug)
### References ###
- *:logger:*:*:1.0 [[ILogger]] components to dump the captured counters - *:context-info:*:*:1.0 (optional) [[ContextInfo]] to detect the context id and specify counters source
See Also
[[Tracer]]
[[CachedCounters]]
[[CompositeLogger]]
### Example ###
let tracer = new LogTracer(); tracer.setReferences(References.fromTuples( new Descriptor("pip-services", "logger", "console", "default", "1.0"), new ConsoleLogger() ));
let timing = trcer.beginTrace("123", "mycomponent", "mymethod"); try { ... timing.endTrace(); } catch(err) { timing.endFailure(err); }
constructor
constructor();
Creates a new instance of the tracer.
method beginTrace
beginTrace: ( correlationId: string, component: string, operation: string) => TraceTiming;
Begings recording an operation trace
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Returns
a trace timing object.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method failure
failure: ( correlationId: string, component: string, operation: string, error: Error, duration: number) => void;
Records an operation failure with its name, duration and error
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter error
an error object associated with this trace.
Parameter duration
execution duration in milliseconds.
method setReferences
setReferences: (references: IReferences) => void;
Sets references to dependent components.
Parameter references
references to locate the component dependencies.
method trace
trace: ( correlationId: string, component: string, operation: string, duration: number) => void;
Records an operation trace with its name and duration
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter duration
execution duration in milliseconds.
class MemoryCache
class MemoryCache implements ICache, IReconfigurable {}
Cache that stores values in the process memory.
Remember: This implementation is not suitable for synchronization of distributed processes.
### Configuration parameters ###
__options:__ - timeout: default caching timeout in milliseconds (default: 1 minute) - max_size: maximum number of values stored in this cache (default: 1000)
See Also
[[ICache]]
### Example ###
let cache = new MemoryCache();
cache.store("123", "key1", "ABC", (err) => { cache.store("123", "key1", (err, value) => { // Result: "ABC" }); });
constructor
constructor();
Creates a new instance of the cache.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method remove
remove: ( correlationId: string, key: string, callback: (err: any) => void) => void;
Removes a value from the cache by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter callback
(optional) callback function that receives an error or null for success
method retrieve
retrieve: ( correlationId: string, key: string, callback: (err: any, value: any) => void) => void;
Retrieves cached value from the cache using its key. If value is missing in the cache or expired it returns null.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter callback
callback function that receives cached value or error.
method store
store: ( correlationId: string, key: string, value: any, timeout: number, callback: (err: any, value: any) => void) => void;
Stores value in the cache with expiration time.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter value
a value to store.
Parameter timeout
expiration timeout in milliseconds.
Parameter callback
(optional) callback function that receives an error or null for success
class MemoryConfigReader
class MemoryConfigReader implements IConfigReader, IReconfigurable {}
Config reader that stores configuration in memory.
The reader supports parameterization using Handlebars template engine: [[https://handlebarsjs.com]]
### Configuration parameters ###
The configuration parameters are the configuration template
See Also
[[IConfigReader]]
### Example ####
let config = ConfigParams.fromTuples( "connection.host", "{{SERVICE_HOST}}", "connection.port", "{{SERVICE_PORT}}{{^SERVICE_PORT}}8080{{/SERVICE_PORT}}" );
let configReader = new MemoryConfigReader(); configReader.configure(config);
let parameters = ConfigParams.fromValue(process.env);
configReader.readConfig("123", parameters, (err, config) => { // Possible result: connection.host=10.1.1.100;connection.port=8080 });
constructor
constructor(config?: ConfigParams);
Creates a new instance of config reader.
Parameter config
(optional) component configuration parameters
method addChangeListener
addChangeListener: (listener: INotifiable) => void;
Adds a listener that will be notified when configuration is changed
Parameter listener
a listener to be added.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method readConfig
readConfig: ( correlationId: string, parameters: ConfigParams, callback: (err: any, config: ConfigParams) => void) => void;
Reads configuration and parameterize it with given values.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration or null to skip parameterization.
Parameter callback
callback function that receives configuration or error.
method removeChangeListener
removeChangeListener: (listener: INotifiable) => void;
Remove a previously added change listener.
Parameter listener
a listener to be removed.
class MemoryCredentialStore
class MemoryCredentialStore implements ICredentialStore, IReconfigurable {}
Credential store that keeps credentials in memory.
### Configuration parameters ###
- [credential key 1]: - ... credential parameters for key 1 - [credential key 2]: - ... credential parameters for key N - ...
See Also
[[ICredentialStore]]
[[CredentialParams]]
### Example ###
let config = ConfigParams.fromTuples( "key1.user", "jdoe", "key1.pass", "pass123", "key2.user", "bsmith", "key2.pass", "mypass" );
let credentialStore = new MemoryCredentialStore(); credentialStore.readCredentials(config);
credentialStore.lookup("123", "key1", (err, credential) => { // Result: user=jdoe;pass=pass123 });
constructor
constructor(config?: ConfigParams);
Creates a new instance of the credential store.
Parameter config
(optional) configuration with credential parameters.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method lookup
lookup: ( correlationId: string, key: string, callback: (err: any, result: CredentialParams) => void) => void;
Lookups credential parameters by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the credential parameters.
Parameter callback
callback function that receives found credential parameters or error.
method readCredentials
readCredentials: (config: ConfigParams) => void;
Reads credentials from configuration parameters. Each section represents an individual CredentialParams
Parameter config
configuration parameters to be read
method store
store: ( correlationId: string, key: string, credential: CredentialParams, callback: (err: any) => void) => void;
Stores credential parameters into the store.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the credential parameters.
Parameter credential
a credential parameters to be stored.
Parameter callback
callback function that receives an error or null for success.
class MemoryDiscovery
class MemoryDiscovery implements IDiscovery, IReconfigurable {}
Discovery service that keeps connections in memory.
### Configuration parameters ###
- [connection key 1]: - ... connection parameters for key 1 - [connection key 2]: - ... connection parameters for key N
See Also
[[IDiscovery]]
[[ConnectionParams]]
### Example ###
let config = ConfigParams.fromTuples( "key1.host", "10.1.1.100", "key1.port", "8080", "key2.host", "10.1.1.100", "key2.port", "8082" );
let discovery = new MemoryDiscovery(); discovery.readConnections(config);
discovery.resolve("123", "key1", (err, connection) => { // Result: host=10.1.1.100;port=8080 });
constructor
constructor(config?: ConfigParams);
Creates a new instance of discovery service.
Parameter config
(optional) configuration with connection parameters.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method readConnections
readConnections: (config: ConfigParams) => void;
Reads connections from configuration parameters. Each section represents an individual Connectionparams
Parameter config
configuration parameters to be read
method register
register: ( correlationId: string, key: string, connection: ConnectionParams, callback: (err: any, result: ConnectionParams) => void) => void;
Registers connection parameters into the discovery service.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the connection parameters.
Parameter credential
a connection to be registered.
Parameter callback
callback function that receives a registered connection or error.
method resolveAll
resolveAll: ( correlationId: string, key: string, callback: (err: any, result: ConnectionParams[]) => void) => void;
Resolves all connection parameters by their key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the connections.
Parameter callback
callback function that receives found connections or error.
method resolveOne
resolveOne: ( correlationId: string, key: string, callback: (err: any, result: ConnectionParams) => void) => void;
Resolves a single connection parameters by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the connection.
Parameter callback
callback function that receives found connection or error.
class MemoryLock
class MemoryLock extends Lock {}
Lock that is used to synchronize execution within one process using shared memory.
Remember: This implementation is not suitable for synchronization of distributed processes.
### Configuration parameters ###
- __options:__ - retry_timeout: timeout in milliseconds to retry lock acquisition. (Default: 100)
See Also
[[ILock]]
[[Lock]]
### Example ###
let lock = new MemoryLock();
lock.acquire("123", "key1", (err) => { if (err == null) { try { // Processing... } finally { lock.releaseLock("123", "key1", (err) => { // Continue... }); } } });
method releaseLock
releaseLock: ( correlationId: string, key: string, callback?: (err: any) => void) => void;
Releases the lock with the given key.
Parameter correlationId
not used.
Parameter key
the key of the lock that is to be released.
Parameter callback
(optional) the function to call once the lock has been released. Will be called with null.
method tryAcquireLock
tryAcquireLock: ( correlationId: string, key: string, ttl: number, callback: (err: any, result: boolean) => void) => void;
Makes a single attempt to acquire a lock by its key. It returns immediately a positive or negative result.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter callback
callback function that receives a lock result or error.
class NullCache
class NullCache implements ICache {}
Dummy cache implementation that doesn't do anything.
It can be used in testing or in situations when cache is required but shall be disabled.
See Also
[[ICache]]
method remove
remove: ( correlationId: string, key: string, callback: (err: any) => void) => void;
Removes a value from the cache by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter callback
(optional) callback function that receives an error or null for success
method retrieve
retrieve: ( correlationId: string, key: string, callback: (err: any, value: any) => void) => void;
Retrieves cached value from the cache using its key. If value is missing in the cache or expired it returns null.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter callback
callback function that receives cached value or error.
method store
store: ( correlationId: string, key: string, value: any, timeout: number, callback: (err: any, value: any) => void) => void;
Stores value in the cache with expiration time.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter value
a value to store.
Parameter timeout
expiration timeout in milliseconds.
Parameter callback
(optional) callback function that receives an error or null for success
class NullCounters
class NullCounters implements ICounters {}
Dummy implementation of performance counters that doesn't do anything.
It can be used in testing or in situations when counters is required but shall be disabled.
See Also
[[ICounters]]
constructor
constructor();
Creates a new instance of the counter.
method beginTiming
beginTiming: (name: string) => CounterTiming;
Begins measurement of execution time interval. It returns [[CounterTiming]] object which has to be called at [[CounterTiming.endTiming]] to end the measurement and update the counter.
Parameter name
a counter name of Interval type.
Returns
a [[CounterTiming]] callback object to end timing.
method increment
increment: (name: string, value: number) => void;
Increments counter by given value.
Parameter name
a counter name of Increment type.
Parameter value
a value to add to the counter.
method incrementOne
incrementOne: (name: string) => void;
Increments counter by 1.
Parameter name
a counter name of Increment type.
method last
last: (name: string, value: number) => void;
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
Parameter name
a counter name of Last type.
Parameter value
a last value to record.
method stats
stats: (name: string, value: number) => void;
Calculates min/average/max statistics based on the current and previous values.
Parameter name
a counter name of Statistics type
Parameter value
a value to update statistics
method timestamp
timestamp: (name: string, value: Date) => void;
Records the given timestamp.
Parameter name
a counter name of Timestamp type.
Parameter value
a timestamp to record.
method timestampNow
timestampNow: (name: string) => void;
Records the current time as a timestamp.
Parameter name
a counter name of Timestamp type.
class NullLock
class NullLock implements ILock {}
Dummy lock implementation that doesn't do anything.
It can be used in testing or in situations when lock is required but shall be disabled.
See Also
[[ILock]]
method acquireLock
acquireLock: ( correlationId: string, key: string, ttl: number, timeout: number, callback: (err: any) => void) => void;
Makes multiple attempts to acquire a lock by its key within give time interval.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter timeout
a lock acquisition timeout.
Parameter callback
callback function that receives error or null for success.
method releaseLock
releaseLock: ( correlationId: string, key: string, callback?: (err: any) => void) => void;
Releases prevously acquired lock by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to release.
Parameter callback
callback function that receives error or null for success.
method tryAcquireLock
tryAcquireLock: ( correlationId: string, key: string, ttl: number, callback: (err: any, result: boolean) => void) => void;
Makes a single attempt to acquire a lock by its key. It returns immediately a positive or negative result.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter callback
callback function that receives a lock result or error.
class NullLogger
class NullLogger implements ILogger {}
Dummy implementation of logger that doesn't do anything.
It can be used in testing or in situations when logger is required but shall be disabled.
See Also
[[ILogger]]
constructor
constructor();
Creates a new instance of the logger.
method debug
debug: (correlationId: string, message: string, ...args: any[]) => void;
Logs a high-level debug information for troubleshooting.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method error
error: ( correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs recoverable application error.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method fatal
fatal: ( correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs fatal (unrecoverable) message that caused the process to crash.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method getLevel
getLevel: () => LogLevel;
Gets the maximum log level. Messages with higher log level are filtered out.
Returns
the maximum log level.
method info
info: (correlationId: string, message: string, ...args: any[]) => void;
Logs an important information message
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method log
log: ( level: LogLevel, correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs a message at specified log level.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method setLevel
setLevel: (value: LogLevel) => void;
Set the maximum log level.
Parameter value
a new maximum log level.
method trace
trace: (correlationId: string, message: string, ...args: any[]) => void;
Logs a low-level debug information for troubleshooting.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method warn
warn: (correlationId: string, message: string, ...args: any[]) => void;
Logs a warning that may or may not have a negative impact.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
class NullTracer
class NullTracer implements ITracer {}
Dummy implementation of tracer that doesn't do anything.
It can be used in testing or in situations when tracing is required but shall be disabled.
See Also
[[ITracer]]
method beginTrace
beginTrace: ( correlationId: string, component: string, operation: string) => TraceTiming;
Begings recording an operation trace
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Returns
a trace timing object.
method failure
failure: ( correlationId: string, component: string, operation: string, error: Error, duration: number) => void;
Records an operation failure with its name, duration and error
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter error
an error object associated with this trace.
Parameter duration
execution duration in milliseconds.
method NullTracer
NullTracer: () => void;
Creates a new instance of the tracer.
method trace
trace: ( correlationId: string, component: string, operation: string, duration: number) => void;
Records an operation trace with its name and duration
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter duration
execution duration in milliseconds.
class OperationTrace
class OperationTrace {}
Data object to store captured operation traces. This object is used by [[CachedTracer]].
property component
component: string;
The name of component
property correlation_id
correlation_id: string;
The transaction id to trace execution through call chain.
property duration
duration: number;
The duration of the operation in milliseconds
property error
error: ErrorDescription;
The description of the captured error
[[https://pip-services3-node.github.io/pip-services3-commons-node/classes/errors.errordescription.html ErrorDescription]] [[https://pip-services3-node.github.io/pip-services3-commons-node/classes/errors.applicationexception.html ApplicationException]]
property operation
operation: string;
The name of the executed operation
property source
source: string;
The source (context name)
property time
time: Date;
The time when operation was executed
class Shutdown
class Shutdown implements IConfigurable, IOpenable {}
Random shutdown component that crashes the process using various methods.
The component is usually used for testing, but brave developers can try to use it in production to randomly crash microservices. It follows the concept of "Chaos Monkey" popularized by Netflix.
### Configuration parameters ###
- mode: null - crash by NullPointer excepiton, zero - crash by dividing by zero, excetion = crash by unhandled exception, exit - exit the process - min_timeout: minimum crash timeout in milliseconds (default: 5 mins) - max_timeout: maximum crash timeout in milliseconds (default: 15 minutes)
### Example ###
let shutdown = new Shutdown(); shutdown.configure(ConfigParams.fromTuples( "mode": "exception" )); shutdown.shutdown(); // Result: Bang!!! the process crashes
constructor
constructor();
Creates a new instance of the shutdown component.
method close
close: (correlationId: string, callback: (err: any) => void) => void;
Closes component and frees used resources.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter callback
callback function that receives error or null no errors occured.
method configure
configure: (config: ConfigParams) => void;
Configures component by passing configuration parameters.
Parameter config
configuration parameters to be set.
method isOpen
isOpen: () => boolean;
Checks if the component is opened.
Returns
true if the component has been opened and false otherwise.
method open
open: (correlationId: string, callback: (err: any) => void) => void;
Opens the component.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter callback
callback function that receives error or null no errors occured.
method shutdown
shutdown: () => void;
Crashes the process using the configured crash mode.
class TraceTiming
class TraceTiming {}
Timing object returned by ITracer.beginTrace to end timing of execution block and record the associated trace.
### Example ###
let timing = tracer.beginTrace("mymethod.exec_time"); try { ... timing.endTrace(); } catch (err) { timing.endFailure(err); }
constructor
constructor( correlationId: string, component: string, operation: string, tracer?: ITracer);
Creates a new instance of the timing callback object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
an associated component name
Parameter operation
an associated operation name
Parameter callback
a callback that shall be called when endTiming is called.
method endFailure
endFailure: (error: Error) => void;
Ends timing of a failed block, calculates elapsed time and records the associated trace.
Parameter error
an error object associated with this trace.
method endTrace
endTrace: () => void;
Ends timing of an execution block, calculates elapsed time and records the associated trace.
class YamlConfigReader
class YamlConfigReader extends FileConfigReader {}
Config reader that reads configuration from YAML file.
The reader supports parameterization using [[https://handlebarsjs.com Handlebars]] template engine.
### Configuration parameters ###
- path: path to configuration file - parameters: this entire section is used as template parameters - ...
See Also
[[IConfigReader]]
[[FileConfigReader]]
### Example ###
======== config.yml ====== key1: "{{KEY1_VALUE}}" key2: "{{KEY2_VALUE}}" ===========================
let configReader = new YamlConfigReader("config.yml");
let parameters = ConfigParams.fromTuples("KEY1_VALUE", 123, "KEY2_VALUE", "ABC"); configReader.readConfig("123", parameters, (err, config) => { // Result: key1=123;key2=ABC });
constructor
constructor(path?: string);
Creates a new instance of the config reader.
Parameter path
(optional) a path to configuration file.
method readConfig
static readConfig: ( correlationId: string, path: string, parameters: ConfigParams) => ConfigParams;
Reads configuration and parameterize it with given values.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration or null to skip parameterization.
Parameter callback
callback function that receives configuration or error.
Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter file
a path to configuration file.
Parameter parameters
values to parameters the configuration or null to skip parameterization.
Parameter callback
callback function that receives configuration or error.
method readObject
static readObject: ( correlationId: string, path: string, parameters: ConfigParams) => any;
Reads configuration file, parameterizes its content and converts it into JSON object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration.
Returns
a JSON object with configuration.
Reads configuration file, parameterizes its content and converts it into JSON object.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter file
a path to configuration file.
Parameter parameters
values to parameters the configuration.
Returns
a JSON object with configuration.
Interfaces
interface ICache
interface ICache {}
Interface for caches that are used to cache values to improve performance.
method remove
remove: ( correlationId: string, key: string, callback?: (err: any) => void) => any;
Removes a value from the cache by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter callback
(optional) callback function that receives an error or null for success
method retrieve
retrieve: ( correlationId: string, key: string, callback: (err: any, value: any) => void) => void;
Retrieves cached value from the cache using its key. If value is missing in the cache or expired it returns null.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter callback
callback function that receives cached value or error.
method store
store: ( correlationId: string, key: string, value: any, timeout: number, callback?: (err: any) => void) => void;
Stores value in the cache with expiration time.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique value key.
Parameter value
a value to store.
Parameter timeout
expiration timeout in milliseconds.
Parameter callback
(optional) callback function that receives an error or null for success
interface IConfigReader
interface IConfigReader {}
Interface for configuration readers that retrieve configuration from various sources and make it available for other components.
Some IConfigReader implementations may support configuration parameterization. The parameterization allows to use configuration as a template and inject there dynamic values. The values may come from application command like arguments or environment variables.
method addChangeListener
addChangeListener: (listener: INotifiable) => void;
Adds a listener that will be notified when configuration is changed
Parameter listener
a listener to be added.
method readConfig
readConfig: ( correlationId: string, parameters: ConfigParams, callback: (err: any, config: ConfigParams) => void) => void;
Reads configuration and parameterize it with given values.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter parameters
values to parameters the configuration or null to skip parameterization.
Parameter callback
callback function that receives configuration or error.
method removeChangeListener
removeChangeListener: (listener: INotifiable) => void;
Remove a previously added change listener.
Parameter listener
a listener to be removed.
interface ICounters
interface ICounters {}
Interface for performance counters that measure execution metrics.
The performance counters measure how code is performing: how fast or slow, how many transactions performed, how many objects are stored, what was the latest transaction time and so on.
They are critical to monitor and improve performance, scalability and reliability of code in production.
method beginTiming
beginTiming: (name: string) => CounterTiming;
Begins measurement of execution time interval. It returns [[CounterTiming]] object which has to be called at [[CounterTiming.endTiming]] to end the measurement and update the counter.
Parameter name
a counter name of Interval type.
Returns
a [[CounterTiming]] callback object to end timing.
method increment
increment: (name: string, value: number) => void;
Increments counter by given value.
Parameter name
a counter name of Increment type.
Parameter value
a value to add to the counter.
method incrementOne
incrementOne: (name: string) => void;
Increments counter by 1.
Parameter name
a counter name of Increment type.
method last
last: (name: string, value: number) => void;
Records the last calculated measurement value.
Usually this method is used by metrics calculated externally.
Parameter name
a counter name of Last type.
Parameter value
a last value to record.
method stats
stats: (name: string, value: number) => void;
Calculates min/average/max statistics based on the current and previous values.
Parameter name
a counter name of Statistics type
Parameter value
a value to update statistics
method timestamp
timestamp: (name: string, value: Date) => void;
Records the given timestamp.
Parameter name
a counter name of Timestamp type.
Parameter value
a timestamp to record.
method timestampNow
timestampNow: (name: string) => void;
Records the current time as a timestamp.
Parameter name
a counter name of Timestamp type.
interface ICounterTimingCallback
interface ICounterTimingCallback {}
Interface for a callback to end measurement of execution elapsed time.
See Also
[[CounterTiming]]
method endTiming
endTiming: (name: string, elapsed: number) => void;
Ends measurement of execution elapsed time and updates specified counter.
Parameter name
a counter name
Parameter elapsed
execution elapsed time in milliseconds to update the counter.
See Also
[[CounterTiming.endTiming]]
interface ICredentialStore
interface ICredentialStore {}
Interface for credential stores which are used to store and lookup credentials to authenticate against external services.
See Also
[[CredentialParams]]
[[ConnectionParams]]
method lookup
lookup: ( correlationId: string, key: string, callback: (err: any, result: CredentialParams) => void) => void;
Lookups credential parameters by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the credential.
Parameter callback
callback function that receives found credential or error.
method store
store: ( correlationId: string, key: String, credential: CredentialParams, callback: (err: any) => void) => void;
Stores credential parameters into the store.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the credential.
Parameter credential
a credential to be stored.
Parameter callback
callback function that receives an error or null for success.
interface IDiscovery
interface IDiscovery {}
Interface for discovery services which are used to store and resolve connection parameters to connect to external services.
See Also
[[ConnectionParams]]
[[CredentialParams]]
method register
register: ( correlationId: string, key: string, connection: ConnectionParams, callback: (err: any, result: ConnectionParams) => void) => void;
Registers connection parameters into the discovery service.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the connection parameters.
Parameter credential
a connection to be registered.
Parameter callback
callback function that receives a registered connection or error.
method resolveAll
resolveAll: ( correlationId: string, key: string, callback: (err: any, result: ConnectionParams[]) => void) => void;
Resolves all connection parameters by their key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the connections.
Parameter callback
callback function that receives found connections or error.
method resolveOne
resolveOne: ( correlationId: string, key: string, callback: (err: any, result: ConnectionParams) => void) => void;
Resolves a single connection parameters by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a key to uniquely identify the connection.
Parameter callback
callback function that receives found connection or error.
interface IFactory
interface IFactory {}
Interface for component factories.
Factories use locators to identify components to be created.
The locators are similar to those used to locate components in references. They can be of any type like strings or integers. However Pip.Services toolkit most often uses Descriptor objects as component locators.
method canCreate
canCreate: (locator: any) => any;
Checks if this factory is able to create component by given locator.
This method searches for all registered components and returns a locator for component it is able to create that matches the given locator. If the factory is not able to create a requested component is returns null.
Parameter locator
a locator to identify component to be created.
Returns
a locator for a component that the factory is able to create.
method create
create: (locator: any) => any;
Creates a component identified by given locator.
Parameter locator
a locator to identify component to be created.
Returns
the created component.
Throws
a CreateException if the factory is not able to create the component.
interface ILock
interface ILock {}
Interface for locks to synchronize work or parallel processes and to prevent collisions.
The lock allows to manage multiple locks identified by unique keys.
method acquireLock
acquireLock: ( correlationId: string, key: string, ttl: number, timeout: number, callback: (err: any) => void) => void;
Makes multiple attempts to acquire a lock by its key within give time interval.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter timeout
a lock acquisition timeout.
Parameter callback
callback function that receives error or null for success.
method releaseLock
releaseLock: ( correlationId: string, key: string, callback?: (err: any) => void) => void;
Releases prevously acquired lock by its key.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to release.
Parameter callback
callback function that receives error or null for success.
method tryAcquireLock
tryAcquireLock: ( correlationId: string, key: string, ttl: number, callback: (err: any, result: boolean) => void) => void;
Makes a single attempt to acquire a lock by its key. It returns immediately a positive or negative result.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter key
a unique lock key to acquire.
Parameter ttl
a lock timeout (time to live) in milliseconds.
Parameter callback
callback function that receives a lock result or error.
interface ILogger
interface ILogger {}
Interface for logger components that capture execution log messages.
method debug
debug: (correlationId: string, message: string, ...args: any[]) => void;
Logs a high-level debug information for troubleshooting.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method error
error: ( correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs recoverable application error.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method fatal
fatal: ( correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs fatal (unrecoverable) message that caused the process to crash.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method getLevel
getLevel: () => LogLevel;
Gets the maximum log level. Messages with higher log level are filtered out.
Returns
the maximum log level.
method info
info: (correlationId: string, message: string, ...args: any[]) => void;
Logs an important information message
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method log
log: ( level: LogLevel, correlationId: string, error: Error, message: string, ...args: any[]) => void;
Logs a message at specified log level.
Parameter level
a log level.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter error
an error object associated with this message.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method setLevel
setLevel: (value: LogLevel) => void;
Set the maximum log level.
Parameter value
a new maximum log level.
method trace
trace: (correlationId: string, message: string, ...args: any[]) => void;
Logs a low-level debug information for troubleshooting.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
method warn
warn: (correlationId: string, message: string, ...args: any[]) => void;
Logs a warning that may or may not have a negative impact.
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter message
a human-readable message to log.
Parameter args
arguments to parameterize the message.
interface ITracer
interface ITracer {}
Interface for tracer components that capture operation traces.
method beginTrace
beginTrace: ( correlationId: string, component: string, operation: string) => TraceTiming;
Begings recording an operation trace
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Returns
a trace timing object.
method failure
failure: ( correlationId: string, component: string, operation: string, error: Error, duration: number) => void;
Records an operation failure with its name, duration and error
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter error
an error object associated with this trace.
Parameter duration
execution duration in milliseconds.
method trace
trace: ( correlationId: string, component: string, operation: string, duration: number) => void;
Records an operation trace with its name and duration
Parameter correlationId
(optional) transaction id to trace execution through call chain.
Parameter component
a name of called component
Parameter operation
a name of the executed operation.
Parameter duration
execution duration in milliseconds.
Enums
enum CounterType
enum CounterType { Interval = 0, LastValue = 1, Statistics = 2, Timestamp = 3, Increment = 4,}
Types of counters that measure different types of metrics
member Increment
Increment = 4
Counter that increment counters
member Interval
Interval = 0
Counters that measure execution time intervals
member LastValue
LastValue = 1
Counters that keeps the latest measured value
member Statistics
Statistics = 2
Counters that measure min/average/max statistics
member Timestamp
Timestamp = 3
Counter that record timestamps
enum LogLevel
enum LogLevel { None = 0, Fatal = 1, Error = 2, Warn = 3, Info = 4, Debug = 5, Trace = 6,}
Standard log levels.
Logs at debug and trace levels are usually captured only locally for troubleshooting and never sent to consolidated log services.
member Debug
Debug = 5
Log everything except traces
member Error
Error = 2
Log all errors.
member Fatal
Fatal = 1
Log only fatal errors that cause processes to crash
member Info
Info = 4
Log errors and important information messages
member None
None = 0
Nothing to log
member Trace
Trace = 6
Log everything.
member Warn
Warn = 3
Log errors and warnings
Package Files (67)
- obj/src/Component.d.ts
- obj/src/auth/CredentialParams.d.ts
- obj/src/auth/CredentialResolver.d.ts
- obj/src/auth/DefaultCredentialStoreFactory.d.ts
- obj/src/auth/ICredentialStore.d.ts
- obj/src/auth/MemoryCredentialStore.d.ts
- obj/src/build/CompositeFactory.d.ts
- obj/src/build/CreateException.d.ts
- obj/src/build/Factory.d.ts
- obj/src/build/IFactory.d.ts
- obj/src/cache/CacheEntry.d.ts
- obj/src/cache/DefaultCacheFactory.d.ts
- obj/src/cache/ICache.d.ts
- obj/src/cache/MemoryCache.d.ts
- obj/src/cache/NullCache.d.ts
- obj/src/config/ConfigReader.d.ts
- obj/src/config/DefaultConfigReaderFactory.d.ts
- obj/src/config/FileConfigReader.d.ts
- obj/src/config/IConfigReader.d.ts
- obj/src/config/JsonConfigReader.d.ts
- obj/src/config/MemoryConfigReader.d.ts
- obj/src/config/YamlConfigReader.d.ts
- obj/src/connect/CompositeConnectionResolver.d.ts
- obj/src/connect/ConnectionParams.d.ts
- obj/src/connect/ConnectionResolver.d.ts
- obj/src/connect/ConnectionUtils.d.ts
- obj/src/connect/DefaultDiscoveryFactory.d.ts
- obj/src/connect/IDiscovery.d.ts
- obj/src/connect/MemoryDiscovery.d.ts
- obj/src/count/CachedCounters.d.ts
- obj/src/count/CompositeCounters.d.ts
- obj/src/count/Counter.d.ts
- obj/src/count/CounterTiming.d.ts
- obj/src/count/CounterType.d.ts
- obj/src/count/DefaultCountersFactory.d.ts
- obj/src/count/ICounterTimingCallback.d.ts
- obj/src/count/ICounters.d.ts
- obj/src/count/LogCounters.d.ts
- obj/src/count/NullCounters.d.ts
- obj/src/index.d.ts
- obj/src/info/ContextInfo.d.ts
- obj/src/info/DefaultInfoFactory.d.ts
- obj/src/lock/DefaultLockFactory.d.ts
- obj/src/lock/ILock.d.ts
- obj/src/lock/Lock.d.ts
- obj/src/lock/MemoryLock.d.ts
- obj/src/lock/NullLock.d.ts
- obj/src/log/CachedLogger.d.ts
- obj/src/log/CompositeLogger.d.ts
- obj/src/log/ConsoleLogger.d.ts
- obj/src/log/DefaultLoggerFactory.d.ts
- obj/src/log/ILogger.d.ts
- obj/src/log/LogLevel.d.ts
- obj/src/log/LogLevelConverter.d.ts
- obj/src/log/LogMessage.d.ts
- obj/src/log/Logger.d.ts
- obj/src/log/NullLogger.d.ts
- obj/src/test/DefaultTestFactory.d.ts
- obj/src/test/Shutdown.d.ts
- obj/src/trace/CachedTracer.d.ts
- obj/src/trace/CompositeTracer.d.ts
- obj/src/trace/DefaultTracerFactory.d.ts
- obj/src/trace/ITracer.d.ts
- obj/src/trace/LogTracer.d.ts
- obj/src/trace/NullTracer.d.ts
- obj/src/trace/OperationTrace.d.ts
- obj/src/trace/TraceTiming.d.ts
Dependencies (3)
Dev Dependencies (7)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/pip-services3-components-node
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/pip-services3-components-node)
- HTML<a href="https://www.jsdocs.io/package/pip-services3-components-node"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 8981 ms. - Missing or incorrect documentation? Open an issue for this package.