repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
citrineos-core | github_2023 | citrineos | typescript | LocalAuthListService.persistSendLocalListForStationIdAndCorrelationIdAndSendLocalListRequest | async persistSendLocalListForStationIdAndCorrelationIdAndSendLocalListRequest(
stationId: string,
correlationId: string,
sendLocalListRequest: SendLocalListRequest,
): Promise<SendLocalList> {
const localListVersion =
await this._localAuthListRepository.readOnlyOneByQuery({
where: {
stationId: stationId,
},
include: [LocalListAuthorization],
});
const sendLocalList =
await this.createSendLocalListFromStationIdAndRequestAndCurrentVersion(
stationId,
correlationId,
sendLocalListRequest,
localListVersion,
);
const newLocalAuthListLength =
await this.countUpdatedAuthListFromRequestAndCurrentVersion(
sendLocalList,
localListVersion,
);
// DeviceModelRefactor: If different variable characteristics are allowed for the same variable, per station, then we need to update this
const maxLocalAuthListEntries = await this.getMaxLocalAuthListEntries();
if (!maxLocalAuthListEntries) {
throw new Error(
'Could not get max local auth list entries, required by D01.FR.12',
);
} else if (newLocalAuthListLength > maxLocalAuthListEntries) {
throw new Error(
`Updated local auth list length (${newLocalAuthListLength}) will exceed max local auth list entries (${maxLocalAuthListEntries})`,
);
}
const itemsPerMessageSendLocalList =
(await this.getItemsPerMessageSendLocalListByStationId(stationId)) ||
(sendLocalListRequest.localAuthorizationList
? sendLocalListRequest.localAuthorizationList?.length
: 0);
if (
itemsPerMessageSendLocalList &&
sendLocalListRequest.localAuthorizationList &&
itemsPerMessageSendLocalList <
sendLocalListRequest.localAuthorizationList.length
) {
throw new Error(
`Number of authorizations (${sendLocalListRequest.localAuthorizationList.length}) in SendLocalListRequest (${JSON.stringify(sendLocalListRequest)}) exceeds itemsPerMessageSendLocalList (${itemsPerMessageSendLocalList}) (see D01.FR.11; break list up into multiple SendLocalListRequests of at most ${itemsPerMessageSendLocalList} authorizations by sending one with updateType Full and additional with updateType Differential until all authorizations have been sent)`,
);
}
return sendLocalList;
} | /**
* Validates a SendLocalListRequest and persists it, then returns the correlation Id.
*
* @param {string} stationId - The ID of the station to which the SendLocalListRequest belongs.
* @param {string} correlationId - The correlation Id that will be used for the SendLocalListRequest.
* @param {SendLocalListRequest} sendLocalListRequest - The SendLocalListRequest to validate and persist.
* @return {SendLocalList} The persisted SendLocalList.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/EVDriver/src/module/LocalAuthListService.ts#L40-L95 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | EVDriverModuleApi.constructor | constructor(
evDriverModule: EVDriverModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(evDriverModule, server, logger);
} | /**
* Constructs a new instance of the class.
*
* @param {EVDriverModule} evDriverModule - The EVDriver module.
* @param {FastifyInstance} server - The Fastify server instance.
* @param {Logger<ILogObj>} [logger] - The logger for logging.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/EVDriver/src/module/api.ts#L65-L71 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | EVDriverModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix = this._module.config.modules.evdriver.endpointPrefix;
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/EVDriver/src/module/api.ts#L428-L431 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | EVDriverModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix = this._module.config.modules.evdriver.endpointPrefix;
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/EVDriver/src/module/api.ts#L439-L442 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | EVDriverModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
authorizeRepository?: IAuthorizationRepository,
localAuthListRepository?: ILocalAuthListRepository,
deviceModelRepository?: IDeviceModelRepository,
tariffRepository?: ITariffRepository,
transactionEventRepository?: ITransactionEventRepository,
chargingProfileRepository?: IChargingProfileRepository,
reservationRepository?: IReservationRepository,
callMessageRepository?: ICallMessageRepository,
certificateAuthorityService?: CertificateAuthorityService,
authorizers?: IAuthorizer[],
idGenerator?: IdGenerator,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.EVDriver,
logger,
);
const timer = new Timer();
this._logger.info('Initializing...');
if (!deasyncPromise(this._initHandler(this._requests, this._responses))) {
throw new Error(
'Could not initialize module due to failure in handler initialization.',
);
}
this._authorizeRepository =
authorizeRepository ||
new sequelize.SequelizeAuthorizationRepository(config, logger);
this._localAuthListRepository =
localAuthListRepository ||
new sequelize.SequelizeLocalAuthListRepository(config, logger);
this._deviceModelRepository =
deviceModelRepository ||
new sequelize.SequelizeDeviceModelRepository(config, logger);
this._tariffRepository =
tariffRepository ||
new sequelize.SequelizeTariffRepository(config, logger);
this._transactionEventRepository =
transactionEventRepository ||
new sequelize.SequelizeTransactionEventRepository(config, logger);
this._chargingProfileRepository =
chargingProfileRepository ||
new sequelize.SequelizeChargingProfileRepository(config, logger);
this._reservationRepository =
reservationRepository ||
new sequelize.SequelizeReservationRepository(config, logger);
this._callMessageRepository =
callMessageRepository ||
new sequelize.SequelizeCallMessageRepository(config, logger);
this._certificateAuthorityService =
certificateAuthorityService ||
new CertificateAuthorityService(config, logger);
this._localAuthListService = new LocalAuthListService(
this._localAuthListRepository,
this._deviceModelRepository,
);
this._authorizers = authorizers || [];
this._idGenerator =
idGenerator ||
new IdGenerator(
new SequelizeChargingStationSequenceRepository(config, this._logger),
);
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link EVDriverModule}.
*
* @param {SystemConfig} config - The `config` contains configuration settings for the module.
*
* @param {ICache} [cache] - The cache instance which is shared among the modules & Central System to pass information such as blacklisted actions or boot status.
*
* @param {IMessageSender} [sender] - The `sender` parameter is an optional parameter that represents an instance of the {@link IMessageSender} interface.
* It is used to send messages from the central system to external systems or devices. If no `sender` is provided, a default {@link RabbitMqSender} instance is created and used.
*
* @param {IMessageHandler} [handler] - The `handler` parameter is an optional parameter that represents an instance of the {@link IMessageHandler} interface.
* It is used to handle incoming messages and dispatch them to the appropriate methods or functions. If no `handler` is provided, a default {@link RabbitMqReceiver} instance is created and used.
*
* @param {Logger<ILogObj>} [logger] - The `logger` parameter is an optional parameter that represents an instance of {@link Logger<ILogObj>}.
* It is used to propagate system wide logger settings and will serve as the parent logger for any sub-component logging. If no `logger` is provided, a default {@link Logger<ILogObj>} instance is created and used.
*
* @param {IAuthorizationRepository} [authorizeRepository] - An optional parameter of type {@link IAuthorizationRepository} which represents a repository for accessing and manipulating Authorization data.
* If no `authorizeRepository` is provided, a default {@link sequelize:AuthorizationRepository} instance is created and used.
*
* @param {ILocalAuthListRepository} [localAuthListRepository] - An optional parameter of type {@link ILocalAuthListRepository} which represents a repository for accessing and manipulating Local Authorization List data.
* If no `localAuthListRepository` is provided, a default {@link sequelize:localAuthListRepository} instance is created and used.
*
* @param {IDeviceModelRepository} [deviceModelRepository] - An optional parameter of type {@link IDeviceModelRepository} which represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link sequelize:deviceModelRepository} instance is
* created and used.
*
* @param {ITariffRepository} [tariffRepository] - An optional parameter of type {@link ITariffRepository} which
* represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link sequelize:tariffRepository} instance is
* created and used.
*
* @param {ITransactionEventRepository} [transactionEventRepository] - An optional parameter of type {@link ITransactionEventRepository}
* which represents a repository for accessing and manipulating transaction data.
* If no `transactionEventRepository` is provided, a default {@link sequelize:transactionEventRepository} instance is
* created and used.
*
* @param {IChargingProfileRepository} [chargingProfileRepository] - An optional parameter of type {@link IChargingProfileRepository}
* which represents a repository for accessing and manipulating charging profile data.
* If no `chargingProfileRepository` is provided, a default {@link sequelize:chargingProfileRepository} instance is created and used.
*
* @param {IReservationRepository} [reservationRepository] - An optional parameter of type {@link IReservationRepository}
* which represents a repository for accessing and manipulating reservation data.
* If no `reservationRepository` is provided, a default {@link sequelize:reservationRepository} instance is created and used.
*
* @param {ICallMessageRepository} [callMessageRepository] - An optional parameter of type {@link ICallMessageRepository}
* which represents a repository for accessing and manipulating callMessage data.
* If no `callMessageRepository` is provided, a default {@link sequelize:callMessageRepository} instance is created and used.
*
* @param {CertificateAuthorityService} [certificateAuthorityService] - An optional parameter of
* type {@link CertificateAuthorityService} which handles certificate authority operations.
*
* @param {IAuthorizer[]} [authorizers] - An optional parameter of type {@link IAuthorizer[]} which represents
* a list of authorizers that can be used to authorize requests.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/EVDriver/src/module/module.ts#L168-L247 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MonitoringModuleApi.constructor | constructor(
monitoringModule: MonitoringModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(monitoringModule, server, logger);
} | /**
* Constructor for the class.
*
* @param {MonitoringModule} monitoringModule - The monitoring module.
* @param {FastifyInstance} server - The server instance.
* @param {Logger<ILogObj>} [logger] - The logger instance.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Monitoring/src/module/api.ts#L68-L74 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MonitoringModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix =
this._module.config.modules.monitoring.endpointPrefix;
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Monitoring/src/module/api.ts#L531-L535 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MonitoringModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix =
this._module.config.modules.monitoring.endpointPrefix;
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Monitoring/src/module/api.ts#L543-L547 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MonitoringModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
deviceModelRepository?: IDeviceModelRepository,
variableMonitoringRepository?: IVariableMonitoringRepository,
idGenerator?: IdGenerator,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.Monitoring,
logger,
);
const timer = new Timer();
this._logger.info('Initializing...');
if (!deasyncPromise(this._initHandler(this._requests, this._responses))) {
throw new Error(
'Could not initialize module due to failure in handler initialization.',
);
}
this._deviceModelRepository =
deviceModelRepository ||
new SequelizeDeviceModelRepository(config, this._logger);
this._variableMonitoringRepository =
variableMonitoringRepository ||
new SequelizeVariableMonitoringRepository(config, this._logger);
this._deviceModelService = new DeviceModelService(
this._deviceModelRepository,
);
this._monitoringService = new MonitoringService(
this._variableMonitoringRepository,
this._logger,
);
this._idGenerator =
idGenerator ||
new IdGenerator(
new SequelizeChargingStationSequenceRepository(config, this._logger),
);
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link MonitoringModule}.
*
* @param {SystemConfig} config - The `config` contains configuration settings for the module.
*
* @param {ICache} [cache] - The cache instance which is shared among the modules & Central System to pass information such as blacklisted actions or boot status.
*
* @param {IMessageSender} [sender] - The `sender` parameter is an optional parameter that represents an instance of the {@link IMessageSender} interface.
* It is used to send messages from the central system to external systems or devices. If no `sender` is provided, a default {@link RabbitMqSender} instance is created and used.
*
* @param {IMessageHandler} [handler] - The `handler` parameter is an optional parameter that represents an instance of the {@link IMessageHandler} interface.
* It is used to handle incoming messages and dispatch them to the appropriate methods or functions. If no `handler` is provided, a default {@link RabbitMqReceiver} instance is created and used.
*
* @param {Logger<ILogObj>} [logger] - The `logger` parameter is an optional parameter that represents an instance of {@link Logger<ILogObj>}.
* It is used to propagate system-wide logger settings and will serve as the parent logger for any subcomponent logging. If no `logger` is provided, a default {@link Logger<ILogObj>} instance is created and used.
*
* @param {IDeviceModelRepository} [deviceModelRepository] - An optional parameter of type {@link IDeviceModelRepository} which represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link SequelizeDeviceModelRepository} instance is created and used.
*
* @param {IVariableMonitoringRepository} [variableMonitoringRepository] - An optional parameter of type {@link IVariableMonitoringRepository}
* which represents a repository for accessing and manipulating variable monitoring data.
* If no `variableMonitoringRepository` is provided, a default {@link SequelizeVariableMonitoringRepository}
* instance is created and used.
*
* @param {IdGenerator} [idGenerator] - An optional parameter of type {@link IdGenerator} which
* represents a generator for ids.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Monitoring/src/module/module.ts#L101-L151 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | DeviceModelService.getItemsPerMessageByComponentAndVariableInstanceAndStationId | async getItemsPerMessageByComponentAndVariableInstanceAndStationId(
componentName: string,
variableInstance: string,
stationId: string,
): Promise<number | null> {
const itemsPerMessageAttributes: VariableAttribute[] =
await this._deviceModelRepository.readAllByQuerystring({
stationId: stationId,
component_name: componentName,
variable_name: 'ItemsPerMessage',
variable_instance: variableInstance,
type: AttributeEnumType.Actual,
});
if (itemsPerMessageAttributes.length === 0) {
return null;
} else {
// It is possible for itemsPerMessageAttributes.length > 1 if component instances or evses
// are associated with alternate options. That structure is not supported by this logic, and that
// structure is a violation of Part 2 - Specification of OCPP 2.0.1.
return Number(itemsPerMessageAttributes[0].value);
}
} | /**
* Fetches the ItemsPerMessage attribute from the device model.
* Returns null if no such attribute exists.
* It is possible for there to be multiple ItemsPerMessage attributes if component instances or evses
* are associated with alternate options. That structure is not supported by this logic, and that
* structure is a violation of Part 2 - Specification of OCPP 2.0.1.
* In that case, the first attribute will be returned.
* @param stationId Charging station identifier.
* @returns ItemsPerMessage as a number or null if no such attribute exists.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Monitoring/src/module/services.ts#L25-L46 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | DeviceModelService.getBytesPerMessageByComponentAndVariableInstanceAndStationId | async getBytesPerMessageByComponentAndVariableInstanceAndStationId(
componentName: string,
variableInstance: string,
stationId: string,
): Promise<number | null> {
const bytesPerMessageAttributes: VariableAttribute[] =
await this._deviceModelRepository.readAllByQuerystring({
stationId: stationId,
component_name: componentName,
variable_name: 'BytesPerMessage',
variable_instance: variableInstance,
type: AttributeEnumType.Actual,
});
if (bytesPerMessageAttributes.length === 0) {
return null;
} else {
// It is possible for bytesPerMessageAttributes.length > 1 if component instances or evses
// are associated with alternate options. That structure is not supported by this logic, and that
// structure is a violation of Part 2 - Specification of OCPP 2.0.1.
return Number(bytesPerMessageAttributes[0].value);
}
} | /**
* Fetches the BytesPerMessage attribute from the device model.
* Returns null if no such attribute exists.
* It is possible for there to be multiple BytesPerMessage attributes if component instances or evses
* are associated with alternate options. That structure is not supported by this logic, and that
* structure is a violation of Part 2 - Specification of OCPP 2.0.1.
* In that case, the first attribute will be returned.
* @param stationId Charging station identifier.
* @returns BytesPerMessage as a number or null if no such attribute exists.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Monitoring/src/module/services.ts#L58-L79 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | AdminApi.constructor | constructor(
ocppRouter: MessageRouterImpl,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(ocppRouter, server, logger);
} | /**
* Constructs a new instance of the class.
*
* @param {MessageRouterImpl} ocppRouter - The OcppRouter module.
* @param {FastifyInstance} server - The Fastify server instance.
* @param {Logger<ILogObj>} [logger] - The logger instance.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/api.ts#L44-L50 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | AdminApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix = '/ocpprouter';
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/api.ts#L152-L155 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | AdminApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix = '/ocpprouter';
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/api.ts#L163-L166 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender: IMessageSender,
handler: IMessageHandler,
dispatcher: WebhookDispatcher,
networkHook: (identifier: string, message: string) => Promise<boolean>,
logger?: Logger<ILogObj>,
ajv?: Ajv,
locationRepository?: ILocationRepository,
subscriptionRepository?: ISubscriptionRepository,
) {
super(config, cache, handler, sender, networkHook, logger, ajv);
this._cache = cache;
this._sender = sender;
this._handler = handler;
this._webhookDispatcher = dispatcher;
this._networkHook = networkHook;
this._locationRepository =
locationRepository ||
new sequelize.SequelizeLocationRepository(config, logger);
this.subscriptionRepository =
subscriptionRepository ||
new sequelize.SequelizeSubscriptionRepository(config, this._logger);
} | /**
* Constructor for the class.
*
* @param {SystemConfig} config - the system configuration
* @param {ICache} cache - the cache object
* @param {IMessageSender} [sender] - the message sender
* @param {IMessageHandler} [handler] - the message handler
* @param {WebhookDispatcher} [dispatcher] - the webhook dispatcher
* @param {Function} networkHook - the network hook needed to send messages to chargers
* @param {ILocationRepository} [locationRepository] - An optional parameter of type {@link ILocationRepository} which
* represents a repository for accessing and manipulating variable data.
* If no `locationRepository` is provided, a default {@link sequelize.LocationRepository} instance is created and used.
*
* @param {ISubscriptionRepository} [subscriptionRepository] - the subscription repository
* @param {Logger<ILogObj>} [logger] - the logger object (optional)
* @param {Ajv} [ajv] - the Ajv object, for message validation (optional)
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L81-L106 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl.registerConnection | async registerConnection(connectionIdentifier: string): Promise<boolean> {
const dispatcherRegistration =
this._webhookDispatcher.register(connectionIdentifier);
const requestSubscription = this._handler.subscribe(
connectionIdentifier,
undefined,
{
stationId: connectionIdentifier,
state: MessageState.Request.toString(),
origin: MessageOrigin.ChargingStationManagementSystem.toString(),
},
);
const responseSubscription = this._handler.subscribe(
connectionIdentifier,
undefined,
{
stationId: connectionIdentifier,
state: MessageState.Response.toString(),
origin: MessageOrigin.ChargingStationManagementSystem.toString(),
},
);
const updateIsOnline = this._locationRepository.setChargingStationIsOnline(connectionIdentifier, true);
return Promise.all([
dispatcherRegistration,
requestSubscription,
responseSubscription,
updateIsOnline,
])
.then((resolvedArray) => resolvedArray[1] && resolvedArray[2])
.catch((error) => {
this._logger.error(
`Error registering connection for ${connectionIdentifier}: ${error}`,
);
return false;
});
} | // TODO: Below method should lock these tables so that a rapid connect-disconnect cannot result in race condition. | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L109-L148 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl.onMessage | async onMessage(
identifier: string,
message: string,
timestamp: Date,
): Promise<boolean> {
this._webhookDispatcher.dispatchMessageReceived(identifier, message);
let rpcMessage: any;
let messageTypeId: MessageTypeId | undefined = undefined;
let messageId: string = '-1'; // OCPP 2.0.1 part 4, section 4.2.3, "When also the MessageId cannot be read, the CALLERROR SHALL contain "-1" as MessageId."
try {
try {
rpcMessage = JSON.parse(message);
} catch (error) {
this._logger.error(
`Error parsing ${message} from websocket, unable to reply: ${JSON.stringify(error)}`,
);
}
messageTypeId = rpcMessage[0];
messageId = rpcMessage[1];
switch (messageTypeId) {
case MessageTypeId.Call:
await this._onCall(identifier, rpcMessage as Call, timestamp);
break;
case MessageTypeId.CallResult:
this._onCallResult(identifier, rpcMessage as CallResult, timestamp);
break;
case MessageTypeId.CallError:
this._onCallError(identifier, rpcMessage as CallError, timestamp);
break;
default:
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Unknown message type id: ' + messageTypeId,
{},
);
}
return true;
} catch (error) {
this._logger.error('Error processing message:', message, error);
if (
messageTypeId != MessageTypeId.CallResult &&
messageTypeId != MessageTypeId.CallError
) {
const callError =
error instanceof OcppError
? error.asCallError()
: [
MessageTypeId.CallError,
messageId,
ErrorCode.InternalError,
'Unable to process message',
{ error: error },
];
const rawMessage = JSON.stringify(callError, (k, v) => v ?? undefined);
this._sendMessage(identifier, rawMessage);
}
// TODO: Publish raw payload for error reporting
return false;
}
} | // find way to include tenantId here | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L161-L221 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl.sendCall | async sendCall(
identifier: string,
tenantId: string,
action: CallAction,
payload: OcppRequest,
correlationId = uuidv4(),
origin?: MessageOrigin,
): Promise<IMessageConfirmation> {
const message: Call = [MessageTypeId.Call, correlationId, action, payload];
if (await this._sendCallIsAllowed(identifier, message)) {
if (
await this._cache.setIfNotExist(
identifier,
`${action}:${correlationId}`,
CacheNamespace.Transactions,
this._config.maxCallLengthSeconds,
)
) {
// Intentionally removing NULL values from object for OCPP conformity
const rawMessage = JSON.stringify(message, (k, v) => v ?? undefined);
const success = await this._sendMessage(identifier, rawMessage);
return { success };
} else {
this._logger.info(
'Call already in progress, throwing retry exception',
identifier,
message,
);
throw new RetryMessageError('Call already in progress');
}
} else {
this._logger.info(
'RegistrationStatus Rejected, unable to send',
identifier,
message,
);
return { success: false };
}
} | /**
* Sends a Call message to a charging station with given identifier.
*
* @param {string} identifier - The identifier of the charging station.
* @param {Call} message - The Call message to send.
* @return {Promise<boolean>} A promise that resolves to a boolean indicating if the call was sent successfully.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L230-L268 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl.sendCallResult | async sendCallResult(
correlationId: string,
identifier: string,
tenantId: string,
action: CallAction,
payload: OcppResponse,
origin?: MessageOrigin,
): Promise<IMessageConfirmation> {
const message: CallResult = [
MessageTypeId.CallResult,
correlationId,
payload,
];
const cachedActionMessageId = await this._cache.get<string>(
identifier,
CacheNamespace.Transactions,
);
if (!cachedActionMessageId) {
this._logger.error(
'Failed to send callResult due to missing message id',
identifier,
message,
);
return { success: false };
}
let [cachedAction, cachedMessageId] = cachedActionMessageId?.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (cachedAction === action && cachedMessageId === correlationId) {
// Intentionally removing NULL values from object for OCPP conformity
const rawMessage = JSON.stringify(message, (k, v) => v ?? undefined);
const success = await Promise.all([
this._sendMessage(identifier, rawMessage),
this._cache.remove(identifier, CacheNamespace.Transactions),
]).then((successes) => successes.every(Boolean));
return { success };
} else {
this._logger.error(
'Failed to send callResult due to mismatch in message id',
identifier,
cachedActionMessageId,
message,
);
return { success: false };
}
} | /**
* Sends the CallResult to a charging station with given identifier.
*
* @param {string} identifier - The identifier of the charging station.
* @param {CallResult} message - The CallResult message to send.
* @return {Promise<boolean>} A promise that resolves to true if the call result was sent successfully, or false otherwise.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L277-L320 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl.sendCallError | async sendCallError(
correlationId: string,
identifier: string,
tenantId: string,
action: CallAction,
error: OcppError,
origin?: MessageOrigin | undefined,
): Promise<IMessageConfirmation> {
const message: CallError = error.asCallError();
const cachedActionMessageId = await this._cache.get<string>(
identifier,
CacheNamespace.Transactions,
);
if (!cachedActionMessageId) {
this._logger.error(
'Failed to send callError due to missing message id',
identifier,
message,
);
return { success: false };
}
let [cachedAction, cachedMessageId] = cachedActionMessageId?.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (cachedMessageId === correlationId) {
// Intentionally removing NULL values from object for OCPP conformity
const rawMessage = JSON.stringify(message, (k, v) => v ?? undefined);
const success = await Promise.all([
this._sendMessage(identifier, rawMessage),
this._cache.remove(identifier, CacheNamespace.Transactions),
]).then((successes) => successes.every(Boolean));
return { success };
} else {
this._logger.error(
'Failed to send callError due to mismatch in message id',
identifier,
cachedActionMessageId,
message,
);
return { success: false };
}
} | /**
* Sends a CallError message to a charging station with given identifier.
*
* @param {string} identifier - The identifier of the charging station.
* @param {CallError} message - The CallError message to send.
* @return {Promise<boolean>} - A promise that resolves to true if the message was sent successfully.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L329-L368 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl._onCall | async _onCall(
identifier: string,
message: Call,
timestamp: Date,
): Promise<void> {
const messageId = message[1];
const action = message[2] as CallAction;
try {
const isAllowed = await this._onCallIsAllowed(action, identifier);
if (!isAllowed) {
throw new OcppError(
messageId,
ErrorCode.SecurityError,
`Action ${action} not allowed`,
);
}
// Run schema validation for incoming Call message
const { isValid, errors } = this._validateCall(identifier, message);
if (!isValid || errors) {
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Invalid message format',
{ errors: errors },
);
}
// Ensure only one call is processed at a time
const successfullySet = await this._cache.setIfNotExist(
identifier,
`${action}:${messageId}`,
CacheNamespace.Transactions,
this._config.maxCallLengthSeconds,
);
if (!successfullySet) {
throw new OcppError(
messageId,
ErrorCode.RpcFrameworkError,
'Call already in progress',
{},
);
}
} catch (error) {
// Send manual reply since cache was unable to be set
const callError =
error instanceof OcppError
? error.asCallError()
: [
MessageTypeId.CallError,
messageId,
ErrorCode.InternalError,
'Unable to process message',
{ error: error },
];
const rawMessage = JSON.stringify(callError, (k, v) => v ?? undefined);
this._sendMessage(identifier, rawMessage);
}
try {
// Route call
const confirmation = await this._routeCall(
identifier,
message,
timestamp,
);
if (!confirmation.success) {
throw new OcppError(messageId, ErrorCode.InternalError, 'Call failed', {
details: confirmation.payload,
});
}
} catch (error) {
const callError =
error instanceof OcppError
? error
: new OcppError(messageId, ErrorCode.InternalError, 'Call failed', {
details: error,
});
// TODO: identifier may not be unique, may require combination of tenantId and identifier.
// find way to include tenantId here
this.sendCallError(
messageId,
identifier,
'undefined',
action,
callError,
).finally(() => {
this._cache.remove(identifier, CacheNamespace.Transactions);
});
}
} | /**
* Handles an incoming Call message from a client connection.
*
* @param {string} identifier - The client identifier.
* @param {Call} message - The Call message received.
* @param {Date} timestamp Time at which the message was received from the charger.
* @return {void}
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L387-L480 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl._onCallResult | _onCallResult(
identifier: string,
message: CallResult,
timestamp: Date,
): void {
const messageId = message[1];
const payload = message[2];
this._logger.debug('Process CallResult', identifier, messageId, payload);
this._cache
.get<string>(identifier, CacheNamespace.Transactions)
.then((cachedActionMessageId) => {
this._cache.remove(identifier, CacheNamespace.Transactions); // Always remove pending call transaction
if (!cachedActionMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'MessageId not found, call may have timed out',
{ maxCallLengthSeconds: this._config.maxCallLengthSeconds },
);
}
const [actionString, cachedMessageId] =
cachedActionMessageId.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (messageId !== cachedMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
"MessageId doesn't match",
{ expectedMessageId: cachedMessageId },
);
}
const action: CallAction =
CallAction[actionString as keyof typeof CallAction]; // Parse CallAction
return {
action,
...this._validateCallResult(identifier, action, message),
}; // Run schema validation for incoming CallResult message
})
.then(({ action, isValid, errors }) => {
if (!isValid || errors) {
throw new OcppError(
messageId,
ErrorCode.FormatViolation,
'Invalid message format',
{ errors: errors },
);
}
// Route call result
return this._routeCallResult(identifier, message, action, timestamp);
})
.then((confirmation) => {
if (!confirmation.success) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'CallResult failed',
{ details: confirmation.payload },
);
}
})
.catch((error) => {
// TODO: There's no such thing as a CallError in response to a CallResult. The above call error exceptions should be replaced.
// TODO: Ideally the error log is also stored in the database in a failed invocations table to ensure these are visible outside of a log file.
this._logger.error('Failed processing call result: ', error);
});
} | /**
* Handles a CallResult made by the client.
*
* @param {string} identifier - The client identifier that made the call.
* @param {CallResult} message - The OCPP CallResult message.
* @param {Date} timestamp Time at which the message was received from the charger.
* @return {void}
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L490-L556 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl._onCallError | _onCallError(identifier: string, message: CallError, timestamp: Date): void {
const messageId = message[1];
this._logger.debug('Process CallError', identifier, message);
this._cache
.get<string>(identifier, CacheNamespace.Transactions)
.then((cachedActionMessageId) => {
this._cache.remove(identifier, CacheNamespace.Transactions); // Always remove pending call transaction
if (!cachedActionMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
'MessageId not found, call may have timed out',
{ maxCallLengthSeconds: this._config.maxCallLengthSeconds },
);
}
const [actionString, cachedMessageId] =
cachedActionMessageId.split(/:(.*)/); // Returns all characters after first ':' in case ':' is used in messageId
if (messageId !== cachedMessageId) {
throw new OcppError(
messageId,
ErrorCode.InternalError,
"MessageId doesn't match",
{ expectedMessageId: cachedMessageId },
);
}
const action: CallAction =
CallAction[actionString as keyof typeof CallAction]; // Parse CallAction
return this._routeCallError(identifier, message, action, timestamp);
})
.then((confirmation) => {
if (!confirmation.success) {
this._logger.warn('Unable to route call error: ', confirmation);
}
})
.catch((error) => {
// TODO: Ideally the error log is also stored in the database in a failed invocations table to ensure these are visible outside of a log file.
this._logger.error('Failed processing call error: ', error);
});
} | /**
* Handles the CallError that may have occured during a Call exchange.
*
* @param {string} identifier - The client identifier.
* @param {CallError} message - The error message.
* @param {Date} timestamp Time at which the message was received from the charger.
* @return {void} This function doesn't return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L566-L606 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MessageRouterImpl._onCallIsAllowed | private _onCallIsAllowed(
action: CallAction,
identifier: string,
): Promise<boolean> {
return this._cache
.exists(action, identifier)
.then((blacklisted) => !blacklisted);
} | /**
* Determine if the given action for identifier is allowed.
*
* @param {CallAction} action - The action to be checked.
* @param {string} identifier - The identifier to be checked.
* @return {Promise<boolean>} A promise that resolves to a boolean indicating if the action and identifier are allowed.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/router.ts#L615-L622 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebhookDispatcher._loadSubscriptionsForConnection | private async _loadSubscriptionsForConnection(connectionIdentifier: string) {
const onConnectionCallbacks: OnConnectionCallback[] = [];
const onCloseCallbacks: OnCloseCallback[] = [];
const onMessageCallbacks: OnMessageCallback[] = [];
const sentMessageCallbacks: OnSentMessageCallback[] = [];
const subscriptions =
await this._subscriptionRepository.readAllByStationId(
connectionIdentifier,
);
for (const subscription of subscriptions) {
if (subscription.onConnect) {
onConnectionCallbacks.push(this._onConnectionCallback(subscription));
this._logger.debug(
`Added onConnect callback to ${subscription.url} for station ${subscription.stationId}`,
);
}
if (subscription.onClose) {
onCloseCallbacks.push(this._onCloseCallback(subscription));
this._logger.debug(
`Added onClose callback to ${subscription.url} for station ${subscription.stationId}`,
);
}
if (subscription.onMessage) {
onMessageCallbacks.push(this._onMessageReceivedCallback(subscription));
this._logger.debug(
`Added onMessage callback to ${subscription.url} for station ${subscription.stationId}`,
);
}
if (subscription.sentMessage) {
sentMessageCallbacks.push(this._onMessageSentCallback(subscription));
this._logger.debug(
`Added sentMessage callback to ${subscription.url} for station ${subscription.stationId}`,
);
}
}
this._onConnectionCallbacks.set(
connectionIdentifier,
onConnectionCallbacks,
);
this._onCloseCallbacks.set(connectionIdentifier, onCloseCallbacks);
this._onMessageCallbacks.set(connectionIdentifier, onMessageCallbacks);
this._sentMessageCallbacks.set(connectionIdentifier, sentMessageCallbacks);
} | /**
* Loads all subscriptions for a given connection into memory
*
* @param {string} connectionIdentifier - the identifier of the connection
* @return {Promise<void>} a promise that resolves once all subscriptions are loaded
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/webhook.dispatcher.ts#L129-L174 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebhookDispatcher._subscriptionCallback | private async _subscriptionCallback(
requestBody: {
stationId: string;
event: string;
origin?: MessageOrigin;
message?: string;
error?: any;
info?: Map<string, string>;
},
url: string,
): Promise<boolean> {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
this._logger.error(
`Route to subscription ${url} on charging station ${requestBody.stationId} failed.
Event: ${requestBody.event}, ${response.status} ${response.statusText} - ${errorText}`,
);
}
return response.ok;
} catch (error) {
this._logger.error(
`Route to subscription ${url} on charging station ${requestBody.stationId} failed.
Event: ${requestBody.event}, ${error}`,
);
return false;
}
} | /**
* Sends a message to a given URL that has been subscribed to a station connection event
*
* @param {Object} requestBody - request body containing stationId, event, origin, message, error, and info
* @param {string} url - the URL to fetch data from
* @return {Promise<boolean>} a Promise that resolves to a boolean indicating success
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/OcppRouter/src/module/webhook.dispatcher.ts#L250-L285 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ReportingModuleApi.constructor | constructor(
reportingModule: ReportingModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(reportingModule, server, logger);
} | /**
* Constructs a new instance of the class.
*
* @param {ReportingModule} ReportingModule - The Reporting module.
* @param {FastifyInstance} server - The Fastify server instance.
* @param {Logger<ILogObj>} [logger] - The logger instance.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Reporting/src/module/api.ts#L47-L53 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ReportingModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix = this._module.config.modules.reporting.endpointPrefix;
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Reporting/src/module/api.ts#L274-L277 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ReportingModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix = this._module.config.modules.reporting.endpointPrefix;
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Reporting/src/module/api.ts#L285-L288 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ReportingModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
deviceModelRepository?: IDeviceModelRepository,
securityEventRepository?: ISecurityEventRepository,
variableMonitoringRepository?: IVariableMonitoringRepository,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.Reporting,
logger,
);
const timer = new Timer();
this._logger.info('Initializing...');
if (!deasyncPromise(this._initHandler(this._requests, this._responses))) {
throw new Error(
'Could not initialize module due to failure in handler initialization.',
);
}
this._deviceModelRepository =
deviceModelRepository ||
new sequelize.SequelizeDeviceModelRepository(config, this._logger);
this._securityEventRepository =
securityEventRepository ||
new sequelize.SequelizeSecurityEventRepository(config, this._logger);
this._variableMonitoringRepository =
variableMonitoringRepository ||
new sequelize.SequelizeVariableMonitoringRepository(config, this._logger);
this._deviceModelService = new DeviceModelService(
this._deviceModelRepository,
);
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link ReportingModule}.
*
* @param {SystemConfig} config - The `config` contains configuration settings for the module.
*
* @param {ICache} [cache] - The cache instance which is shared among the modules & Central System to pass information such as blacklisted actions or boot status.
*
* @param {IMessageSender} [sender] - The `sender` parameter is an optional parameter that represents an instance of the {@link IMessageSender} interface.
* It is used to send messages from the central system to external systems or devices. If no `sender` is provided, a default {@link RabbitMqSender} instance is created and used.
*
* @param {IMessageHandler} [handler] - The `handler` parameter is an optional parameter that represents an instance of the {@link IMessageHandler} interface.
* It is used to handle incoming messages and dispatch them to the appropriate methods or functions. If no `handler` is provided, a default {@link RabbitMqReceiver} instance is created and used.
*
* @param {Logger<ILogObj>} [logger] - The `logger` parameter is an optional parameter that represents an instance of {@link Logger<ILogObj>}.
* It is used to propagate system wide logger settings and will serve as the parent logger for any sub-component logging. If no `logger` is provided, a default {@link Logger<ILogObj>} instance is created and used.
*
* @param {IDeviceModelRepository} [deviceModelRepository] - An optional parameter of type {@link IDeviceModelRepository} which represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link sequelize:deviceModelRepository} instance is created and used.
*
* @param {ISecurityEventRepository} [securityEventRepository] - An optional parameter of type {@link ISecurityEventRepository} which represents a repository for accessing security event notification data.
*
* @param {IVariableMonitoringRepository} [variableMonitoringRepository] - An optional parameter of type {@link IVariableMonitoringRepository} which represents a repository for accessing and manipulating monitoring data.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Reporting/src/module/module.ts#L116-L158 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | DeviceModelService.getItemsPerMessageByComponentAndVariableInstanceAndStationId | async getItemsPerMessageByComponentAndVariableInstanceAndStationId(
componentName: string,
variableInstance: string,
stationId: string,
): Promise<number | null> {
const itemsPerMessageAttributes: VariableAttribute[] =
await this._deviceModelRepository.readAllByQuerystring({
stationId: stationId,
component_name: componentName,
variable_name: 'ItemsPerMessage',
variable_instance: variableInstance,
type: AttributeEnumType.Actual,
});
if (itemsPerMessageAttributes.length === 0) {
return null;
} else {
// It is possible for itemsPerMessageAttributes.length > 1 if component instances or evses
// are associated with alternate options. That structure is not supported by this logic, and that
// structure is a violation of Part 2 - Specification of OCPP 2.0.1.
return Number(itemsPerMessageAttributes[0].value);
}
} | /**
* Fetches the ItemsPerMessage attribute from the device model.
* Returns null if no such attribute exists.
* @param stationId Charging station identifier.
* @returns ItemsPerMessage as a number or null if no such attribute exists.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Reporting/src/module/services.ts#L21-L42 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | DeviceModelService.getBytesPerMessageByComponentAndVariableInstanceAndStationId | async getBytesPerMessageByComponentAndVariableInstanceAndStationId(
componentName: string,
variableInstance: string,
stationId: string,
): Promise<number | null> {
const bytesPerMessageAttributes: VariableAttribute[] =
await this._deviceModelRepository.readAllByQuerystring({
stationId: stationId,
component_name: componentName,
variable_name: 'BytesPerMessage',
variable_instance: variableInstance,
type: AttributeEnumType.Actual,
});
if (bytesPerMessageAttributes.length === 0) {
return null;
} else {
// It is possible for bytesPerMessageAttributes.length > 1 if component instances or evses
// are associated with alternate options. That structure is not supported by this logic, and that
// structure is a violation of Part 2 - Specification of OCPP 2.0.1.
return Number(bytesPerMessageAttributes[0].value);
}
} | /**
* Fetches the BytesPerMessage attribute from the device model.
* Returns null if no such attribute exists.
* It is possible for there to be multiple BytesPerMessage attributes if component instances or evses
* are associated with alternate options. That structure is not supported by this logic, and that
* structure is a violation of Part 2 - Specification of OCPP 2.0.1.
* In that case, the first attribute will be returned.
* @param stationId Charging station identifier.
* @returns BytesPerMessage as a number or null if no such attribute exists.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Reporting/src/module/services.ts#L54-L75 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SmartChargingModuleApi.constructor | constructor(
smartChargingModule: SmartChargingModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(smartChargingModule, server, logger);
} | /**
* Constructs a new instance of the class.
*
* @param {SmartChargingModule} smartChargingModule - The SmartCharging module.
* @param {FastifyInstance} server - The Fastify server instance.
* @param {Logger<ILogObj>} [logger] - The logger instance.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/SmartCharging/src/module/api.ts#L50-L56 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SmartChargingModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix =
this._module.config.modules.smartcharging?.endpointPrefix;
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/SmartCharging/src/module/api.ts#L588-L592 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SmartChargingModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix =
this._module.config.modules.smartcharging?.endpointPrefix;
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/SmartCharging/src/module/api.ts#L600-L604 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SmartChargingModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
transactionEventRepository?: ITransactionEventRepository,
deviceModelRepository?: IDeviceModelRepository,
chargingProfileRepository?: IChargingProfileRepository,
smartChargingService?: ISmartCharging,
idGenerator?: IdGenerator,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.SmartCharging,
logger,
);
const timer = new Timer();
this._logger.info('Initializing...');
if (!deasyncPromise(this._initHandler(this._requests, this._responses))) {
throw new Error(
'Could not initialize module due to failure in handler initialization.',
);
}
this._transactionEventRepository =
transactionEventRepository ||
new sequelize.SequelizeTransactionEventRepository(config, this._logger);
this._deviceModelRepository =
deviceModelRepository ||
new sequelize.SequelizeDeviceModelRepository(config, this._logger);
this._chargingProfileRepository =
chargingProfileRepository ||
new sequelize.SequelizeChargingProfileRepository(config, this._logger);
this._smartChargingService =
smartChargingService ||
new InternalSmartCharging(this._chargingProfileRepository);
this._idGenerator =
idGenerator ||
new IdGenerator(
new SequelizeChargingStationSequenceRepository(config, this._logger),
);
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link SmartChargingModule}.
*
* @param {SystemConfig} config - The `config` contains configuration settings for the module.
*
* @param {ICache} [cache] - The cache instance which is shared among the modules & Central System to pass information such as blacklisted actions or boot status.
*
* @param {IMessageSender} [sender] - The `sender` parameter is an optional parameter that represents an instance of the {@link IMessageSender} interface.
* It is used to send messages from the central system to external systems or devices. If no `sender` is provided, a default {@link RabbitMqSender} instance is created and used.
*
* @param {IMessageHandler} [handler] - The `handler` parameter is an optional parameter that represents an instance of the {@link IMessageHandler} interface.
* It is used to handle incoming messages and dispatch them to the appropriate methods or functions. If no `handler` is provided, a default {@link RabbitMqReceiver} instance is created and used.
*
* @param {Logger<ILogObj>} [logger] - The `logger` parameter is an optional parameter that represents an instance of {@link Logger<ILogObj>}.
* It is used to propagate system wide logger settings and will serve as the parent logger for any sub-component logging. If no `logger` is provided, a default {@link Logger<ILogObj>} instance is created and used.
*
* @param {ITransactionEventRepository} [transactionEventRepository] - An optional parameter of type {@link ITransactionEventRepository}
* which represents a repository for accessing and manipulating transaction data.
* If no `transactionEventRepository` is provided, a default {@link sequelize:transactionEventRepository} instance is created and used.
*
* @param {IDeviceModelRepository} [deviceModelRepository] - An optional parameter of type {@link IDeviceModelRepository}
* which represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link sequelize:deviceModelRepository} instance is created and used.
*
* @param {IChargingProfileRepository} [chargingProfileRepository] - An optional parameter of type {@link IChargingProfileRepository}
* which represents a repository for accessing and manipulating charging profile data.
* If no `chargingProfileRepository` is provided, a default {@link sequelize:chargingProfileRepository} instance is created and used.
*
* @param {ISmartCharging} [smartChargingService] - An optional parameter of type {@link ISmartCharging} which
* provides smart charging functionalities, e.g., calculation and validation.
*
* @param {IdGenerator} [idGenerator] - An optional parameter of type {@link IdGenerator} which
* represents a generator for ids.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/SmartCharging/src/module/module.ts#L132-L183 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SmartChargingModule._generateSetChargingProfileRequest | private async _generateSetChargingProfileRequest(
request: NotifyEVChargingScheduleRequest,
transaction: Transaction,
stationId: string,
): Promise<SetChargingProfileRequest> {
const { chargingSchedule, evseId } = request;
const purpose = ChargingProfilePurposeEnumType.TxProfile;
chargingSchedule.id =
await this._chargingProfileRepository.getNextChargingScheduleId(
stationId,
);
const chargingProfile: ChargingProfileType = {
id: await this._chargingProfileRepository.getNextChargingProfileId(
stationId,
),
stackLevel: await this._chargingProfileRepository.getNextStackLevel(
stationId,
transaction.id,
purpose,
),
chargingProfilePurpose: purpose,
chargingProfileKind: ChargingProfileKindEnumType.Absolute,
chargingSchedule: [chargingSchedule],
transactionId: transaction.transactionId,
};
return {
evseId,
chargingProfile,
} as SetChargingProfileRequest;
} | /**
* Generates a `SetChargingProfileRequest` from the given `NotifyEVChargingScheduleRequest`.
*
* This method creates a charging profile based on the EV's charging schedule.
*
* @param request - The `NotifyEVChargingScheduleRequest` containing EV's charging schedule.
* @param transaction - The transaction associated with the charging profile.
* @param stationId - Station ID
*
* @returns A `SetChargingProfileRequest` with a generated charging profile.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/SmartCharging/src/module/module.ts#L573-L605 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | InternalSmartCharging.calculateChargingProfile | async calculateChargingProfile(
request: NotifyEVChargingNeedsRequest,
transaction: Transaction,
stationId: string,
): Promise<ChargingProfileType> {
const { chargingNeeds } = request;
const acParams = chargingNeeds.acChargingParameters;
const dcParams = chargingNeeds.dcChargingParameters;
const transferMode = chargingNeeds.requestedEnergyTransfer;
// Default values
const profileId =
await this._chargingProfileRepository.getNextChargingProfileId(stationId);
const profilePurpose: ChargingProfilePurposeEnumType =
ChargingProfilePurposeEnumType.TxProfile;
// Find existing charging profile and then add 1 as stack level
const stackLevel = await this._chargingProfileRepository.getNextStackLevel(
stationId,
transaction.id,
profilePurpose,
);
// Create charging schedule
const scheduleId =
await this._chargingProfileRepository.getNextChargingScheduleId(
stationId,
);
let limit = 0;
let numberPhases: number | undefined;
let minChargingRate: number | undefined;
let chargingRateUnit: ChargingRateUnitEnumType = ChargingRateUnitEnumType.A;
// Determine charging parameters based on energy transfer mode
switch (transferMode) {
case EnergyTransferModeEnumType.AC_single_phase:
case EnergyTransferModeEnumType.AC_two_phase:
case EnergyTransferModeEnumType.AC_three_phase:
if (acParams) {
const { evMinCurrent, evMaxCurrent } = acParams;
numberPhases =
transferMode === EnergyTransferModeEnumType.AC_single_phase
? 1
: transferMode === EnergyTransferModeEnumType.AC_two_phase
? 2
: 3; // For AC_three_phase
chargingRateUnit = ChargingRateUnitEnumType.A; // always use amp for AC
limit = evMaxCurrent;
minChargingRate = evMinCurrent;
}
break;
case EnergyTransferModeEnumType.DC:
if (dcParams) {
const { evMaxPower, evMaxCurrent, evMaxVoltage } = dcParams;
numberPhases = undefined; // For a DC EVSE this field should be omitted.
[chargingRateUnit, limit] = this._getChargingRateUnitAndLimit(
evMaxCurrent,
evMaxVoltage,
evMaxPower,
);
}
break;
default:
throw new Error('Unsupported energy transfer mode');
}
await this._validateLimitAgainstExistingProfile(
limit,
stationId,
transaction.id,
);
const departureTime = chargingNeeds.departureTime
? new Date(chargingNeeds.departureTime)
: undefined;
const currentTime = new Date();
const duration = departureTime
? departureTime.getTime() - currentTime.getTime()
: undefined;
// Create charging period
const chargingSchedulePeriod: [
ChargingSchedulePeriodType,
...ChargingSchedulePeriodType[],
] = [
{
startPeriod: 0,
limit,
numberPhases,
},
];
const chargingSchedule: ChargingScheduleType = {
id: scheduleId,
duration,
chargingRateUnit,
chargingSchedulePeriod,
minChargingRate,
};
return {
id: profileId,
stackLevel,
chargingProfilePurpose: profilePurpose,
chargingProfileKind: ChargingProfileKindEnumType.Absolute,
validFrom: currentTime.toISOString(), // Now
validTo: chargingNeeds.departureTime, // Until departure
chargingSchedule: [chargingSchedule],
transactionId: transaction.transactionId,
} as ChargingProfileType;
} | /**
* Generates a `ChargingProfileType` from the given `NotifyEVChargingNeedsRequest`.
*
* This method creates a charging profile based on the EV's charging needs and the specified energy transfer mode.
* The profile includes the necessary parameters to set up a charging schedule for the EV.
*
* @param request - The `NotifyEVChargingNeedsRequest` containing details about the EV's charging requirements.
* @param transaction - The ID of the transaction associated with the charging profile.
* @param stationId - The ID of the station
* @returns A `ChargingProfileType`.
*
* @throws Error if the energy transfer mode is unsupported.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/SmartCharging/src/module/smartCharging/InternalSmartCharging.ts#L48-L157 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TenantModuleApi.constructor | constructor(
tenantModule: TenantModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(tenantModule, server, logger);
} | /**
*
* Constructs a new instance of the class.
*
* @param {TenantModule} tenantModule - The Tenant module.
* @param {FastifyInstance} server - The Fastify server instance.
* @param {Logger<ILogObj>} [logger] - The logger instance.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Tenant/src/module/api.ts#L27-L33 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TenantModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix = this._module.config.modules.tenant.endpointPrefix;
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Tenant/src/module/api.ts#L41-L44 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TenantModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix = this._module.config.modules.tenant.endpointPrefix;
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Tenant/src/module/api.ts#L52-L55 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TenantModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.Tenant,
logger,
);
const timer = new Timer();
this._logger.info('Initializing...');
if (!deasyncPromise(this._initHandler(this._requests, this._responses))) {
throw new Error(
'Could not initialize module due to failure in handler initialization.',
);
}
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link TenantModule}.
*
* @param {SystemConfig} config - The `config` contains configuration settings for the module.
*
* @param {ICache} [cache] - The cache instance which is shared among the modules & Central System to pass information such as blacklisted actions or boot status.
*
* @param {IMessageSender} [sender] - The `sender` parameter is an optional parameter that represents an instance of the {@link IMessageSender} interface.
* It is used to send messages from the central system to external systems or devices. If no `sender` is provided, a default {@link RabbitMqSender} instance is created and used.
*
* @param {IMessageHandler} [handler] - The `handler` parameter is an optional parameter that represents an instance of the {@link IMessageHandler} interface.
* It is used to handle incoming messages and dispatch them to the appropriate methods or functions. If no `handler` is provided, a default {@link RabbitMqReceiver} instance is created and used.
*
* @param {Logger<ILogObj>} [logger] - The `logger` parameter is an optional parameter that represents an instance of {@link Logger<ILogObj>}.
* It is used to propagate system wide logger settings and will serve as the parent logger for any sub-component logging. If no `logger` is provided, a default {@link Logger<ILogObj>} instance is created and used.
*
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Tenant/src/module/module.ts#L49-L75 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CostCalculator.calculateTotalCost | async calculateTotalCost(
stationId: string,
transactionDbId: number,
totalKwh?: number | null,
): Promise<number> {
if (totalKwh === undefined || totalKwh === null) {
const kwh =
await this._transactionService.recalculateTotalKwh(transactionDbId);
return this._calculateTotalCost(stationId, kwh);
}
return this._calculateTotalCost(stationId, totalKwh);
} | /**
* Calculates the total cost for a transaction.
*
* Computes the cost based on `stationId` and `totalKwh`.
* If `totalKwh` is not provided, it is calculated for given transaction.
*
* @param stationId - The identifier of the station.
* @param transactionDbId - The identifier of the transaction.
* @param totalKwh - Optional. The total kilowatt-hours.
*
* @returns A promise that resolves to the total cost.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/CostCalculator.ts#L36-L47 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CostNotifier.notifyWhileActive | notifyWhileActive(
stationId: string,
transactionId: string,
tenantId: string,
intervalSeconds: number,
): void {
this._logger.debug(
`Scheduling periodic cost notifications for ${stationId} station, ${transactionId} transaction, ${tenantId} tenant`,
);
this.schedule(
this._key(stationId, transactionId),
() => this._tryNotify(stationId, transactionId, tenantId),
intervalSeconds,
);
} | /**
* Repeatedly sends a CostUpdated call for an ongoing transaction based on the intervalSeconds.
* Stops sending requests once the transaction becomes inactive.
*
* @param {string} stationId - The identifier of the client connection.
* @param {string} transactionId - The identifier of the transaction.
* @param {number} intervalSeconds - The costUpdated interval in seconds.
* @param {string} tenantId - The identifier of the tenant.
* @return {void} This function does not return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/CostNotifier.ts#L34-L48 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | StatusNotificationService.processStatusNotification | async processStatusNotification(
stationId: string,
statusNotificationRequest: StatusNotificationRequest,
) {
const chargingStation =
await this._locationRepository.readChargingStationByStationId(stationId);
if (chargingStation) {
await this._locationRepository.addStatusNotificationToChargingStation(
stationId,
statusNotificationRequest,
);
} else {
this._logger.warn(
`Charging station ${stationId} not found. Status notification cannot be associated with a charging station.`,
);
}
const component = await this._componentRepository.readOnlyOneByQuery({
where: {
name: 'Connector',
},
include: [
{
model: Evse,
where: {
id: statusNotificationRequest.evseId,
connectorId: statusNotificationRequest.connectorId,
},
},
{
model: Variable,
where: {
name: 'AvailabilityState',
},
},
],
});
const variable = component?.variables?.[0];
if (!component || !variable) {
this._logger.warn(
'Missing component or variable for status notification. Status notification cannot be assigned to device model.',
);
} else {
const reportDataType: ReportDataType = {
component: component,
variable: variable,
variableAttribute: [
{
value: statusNotificationRequest.connectorStatus,
},
],
};
await this._deviceModelRepository.createOrUpdateDeviceModelByStationId(
reportDataType,
stationId,
statusNotificationRequest.timestamp,
);
}
} | /**
* Stores an internal record of the incoming status, then updates the device model for the updated connector.
*
* @param {string} stationId - The Charging Station sending the status notification request
* @param {StatusNotificationRequest} statusNotificationRequest
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/StatusNotificationService.ts#L41-L99 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TransactionsModuleApi.constructor | constructor(
transactionModule: TransactionsModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(transactionModule, server, logger);
} | /**
* Constructor for the class.
*
* @param {TransactionModule} transactionModule - The transaction module.
* @param {FastifyInstance} server - The server instance.
* @param {Logger<ILogObj>} [logger] - Optional logger.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/api.ts#L49-L55 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TransactionsModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix =
this._module.config.modules.transactions.endpointPrefix;
return super._toMessagePath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link CallAction} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link CallAction}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/api.ts#L151-L155 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TransactionsModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix =
this._module.config.modules.transactions.endpointPrefix;
return super._toDataPath(input, endpointPrefix);
} | /**
* Overrides superclass method to generate the URL path based on the input {@link Namespace} and the module's endpoint prefix configuration.
*
* @param {CallAction} input - The input {@link Namespace}.
* @return {string} - The generated URL path.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/api.ts#L163-L167 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TransactionsModuleApi.buildTariff | private buildTariff(request: UpsertTariffRequest): Tariff {
return Tariff.newInstance({
id: request.id,
currency: request.currency,
pricePerKwh: request.pricePerKwh,
pricePerMin: request.pricePerMin,
pricePerSession: request.pricePerSession,
taxRate: request.taxRate,
authorizationAmount: request.authorizationAmount,
paymentFee: request.paymentFee,
});
} | // TODO: move to service layer | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/api.ts#L170-L181 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TransactionsModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
fileAccess: IFileAccess,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
transactionEventRepository?: ITransactionEventRepository,
authorizeRepository?: IAuthorizationRepository,
deviceModelRepository?: IDeviceModelRepository,
componentRepository?: CrudRepository<Component>,
locationRepository?: ILocationRepository,
tariffRepository?: ITariffRepository,
reservationRepository?: IReservationRepository,
authorizers?: IAuthorizer[],
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.Transactions,
logger,
);
const timer = new Timer();
this._logger.info('Initializing...');
if (!deasyncPromise(this._initHandler(this._requests, this._responses))) {
throw new Error(
'Could not initialize module due to failure in handler initialization.',
);
}
this._fileAccess = fileAccess;
this._transactionEventRepository =
transactionEventRepository ||
new sequelize.SequelizeTransactionEventRepository(config, logger);
this._authorizeRepository =
authorizeRepository ||
new sequelize.SequelizeAuthorizationRepository(config, logger);
this._deviceModelRepository =
deviceModelRepository ||
new sequelize.SequelizeDeviceModelRepository(config, logger);
this._componentRepository =
componentRepository ||
new SequelizeRepository<Component>(config, Component.MODEL_NAME, logger);
this._locationRepository =
locationRepository ||
new sequelize.SequelizeLocationRepository(config, logger);
this._tariffRepository =
tariffRepository ||
new sequelize.SequelizeTariffRepository(config, logger);
this._reservationRepository =
reservationRepository ||
new sequelize.SequelizeReservationRepository(config, logger);
this._authorizers = authorizers || [];
this._signedMeterValuesUtil = new SignedMeterValuesUtil(
fileAccess,
config,
this._logger,
);
this._sendCostUpdatedOnMeterValue =
config.modules.transactions.sendCostUpdatedOnMeterValue;
this._costUpdatedInterval = config.modules.transactions.costUpdatedInterval;
this._transactionService = new TransactionService(
this._transactionEventRepository,
this._authorizeRepository,
this._authorizers,
this._logger,
);
this._statusNotificationService = new StatusNotificationService(
this._componentRepository,
this._deviceModelRepository,
this._locationRepository,
this._logger,
);
this._costCalculator = new CostCalculator(
this._tariffRepository,
this._transactionService,
this._logger,
);
this._costNotifier = new CostNotifier(
this,
this._transactionEventRepository,
this._costCalculator,
this._logger,
);
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link TransactionsModule}.
*
* @param {SystemConfig} config - The `config` contains configuration settings for the module.
*
* @param {ICache} [cache] - The cache instance which is shared among the modules & Central System to pass information such as blacklisted actions or boot status.
*
* @param {IFileAccess} [fileAccess] - The `fileAccess` allows access to the configured file storage.
*
* @param {IMessageSender} [sender] - The `sender` parameter is an optional parameter that represents an instance of the {@link IMessageSender} interface.
* It is used to send messages from the central system to external systems or devices. If no `sender` is provided, a default {@link RabbitMqSender} instance is created and used.
*
* @param {IMessageHandler} [handler] - The `handler` parameter is an optional parameter that represents an instance of the {@link IMessageHandler} interface.
* It is used to handle incoming messages and dispatch them to the appropriate methods or functions. If no `handler` is provided, a default {@link RabbitMqReceiver} instance is created and used.
*
* @param {Logger<ILogObj>} [logger] - The `logger` parameter is an optional parameter that represents an instance of {@link Logger<ILogObj>}.
* It is used to propagate system-wide logger settings and will serve as the parent logger for any sub-component logging. If no `logger` is provided, a default {@link Logger<ILogObj>} instance is created and used.
*
* @param {ITransactionEventRepository} [transactionEventRepository] - An optional parameter of type {@link ITransactionEventRepository} which represents a repository for accessing and manipulating transaction event data.
* If no `transactionEventRepository` is provided, a default {@link sequelize:transactionEventRepository} instance
* is created and used.
*
* @param {IAuthorizationRepository} [authorizeRepository] - An optional parameter of type {@link IAuthorizationRepository} which represents a repository for accessing and manipulating authorization data.
* If no `authorizeRepository` is provided, a default {@link sequelize:authorizeRepository} instance is
* created and used.
*
* @param {IDeviceModelRepository} [deviceModelRepository] - An optional parameter of type {@link IDeviceModelRepository} which represents a repository for accessing and manipulating variable attribute data.
* If no `deviceModelRepository` is provided, a default {@link sequelize:deviceModelRepository} instance is
* created and used.
*
* @param {CrudRepository<Component>} [componentRepository] - An optional parameter of type {@link CrudRepository<Component>} which represents a repository for accessing and manipulating component data.
* If no `componentRepository` is provided, a default {@link sequelize:componentRepository} instance is
* created and used.
*
* @param {ILocationRepository} [locationRepository] - An optional parameter of type {@link ILocationRepository} which represents a repository for accessing and manipulating location and charging station data.
* If no `locationRepository` is provided, a default {@link sequelize:locationRepository} instance is
* created and used.
*
* @param {CrudRepository<Component>} [componentRepository] - An optional parameter of type {@link CrudRepository<Component>} which represents a repository for accessing and manipulating component data.
* If no `componentRepository` is provided, a default {@link sequelize:componentRepository} instance is
* created and used.
*
* @param {ILocationRepository} [locationRepository] - An optional parameter of type {@link ILocationRepository} which represents a repository for accessing and manipulating location and charging station data.
* If no `locationRepository` is provided, a default {@link sequelize:locationRepository} instance is
* created and used.
*
* @param {ITariffRepository} [tariffRepository] - An optional parameter of type {@link ITariffRepository} which
* represents a repository for accessing and manipulating tariff data.
* If no `tariffRepository` is provided, a default {@link sequelize:tariffRepository} instance is
* created and used.
*
* @param {IReservationRepository} [reservationRepository] - An optional parameter of type {@link IReservationRepository}
* which represents a repository for accessing and manipulating reservation data.
* If no `reservationRepository` is provided, a default {@link sequelize:reservationRepository} instance is created and used.
*
* @param {IAuthorizer[]} [authorizers] - An optional parameter of type {@link IAuthorizer[]} which represents
* a list of authorizers that can be used to authorize requests.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Transactions/src/module/module.ts#L154-L252 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CitrineOSServer.constructor | constructor(
appName: string,
config: SystemConfig,
server?: FastifyInstance,
ajv?: Ajv,
cache?: ICache,
fileAccess?: IFileAccess,
) {
// Set system config
// TODO: Create and export config schemas for each util module, such as amqp, redis, kafka, etc, to avoid passing them possibly invalid configuration
if (!config.util.messageBroker.amqp) {
throw new Error(
'This server implementation requires amqp configuration for rabbitMQ.',
);
}
this.appName = appName;
this._config = config;
this._server =
server || fastify().withTypeProvider<JsonSchemaToTsProvider>();
// enable cors
(this._server as any).register(cors, {
origin: true, // This can be customized to specify allowed origins
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Specify allowed HTTP methods
});
// Add health check
this.initHealthCheck();
// Create Ajv JSON schema validator instance
this._ajv = this.initAjv(ajv);
this.addAjvFormats();
// Initialize parent logger
this._logger = this.initLogger();
// Set cache implementation
this._cache = this.initCache(cache);
// Initialize Swagger if enabled
this.initSwagger();
// Add Directus Message API flow creation if enabled
let directusUtil: DirectusUtil | undefined = undefined;
if (this._config.util.directus?.generateFlows) {
directusUtil = new DirectusUtil(this._config, this._logger);
this._server.addHook('onRoute', (routeOptions: RouteOptions) => {
directusUtil!.addDirectusMessageApiFlowsFastifyRouteHook(
routeOptions,
this._server.getSchemas(),
);
});
this._server.addHook('onReady', async () => {
this._logger?.info('Directus actions initialization finished');
});
}
// Initialize File Access Implementation
this._fileAccess = this.initFileAccess(fileAccess, directusUtil);
// Register AJV for schema validation
this.registerAjv();
// Initialize repository store
this.initRepositoryStore();
this.initIdGenerator();
this.initCertificateAuthorityService();
this.initSmartChargingService();
// Initialize module & API
// Always initialize API after SwaggerUI
this.initSystem();
} | // todo rename event group to type | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/Server/src/index.ts#L120-L194 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | fastifySchemaCompiler | const fastifySchemaCompiler: FastifySchemaCompiler<any> = (
routeSchema: FastifyRouteSchemaDef<any>,
) => this._ajv?.compile(routeSchema.schema) as FastifyValidationResult; | // todo type schema instead of any | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/Server/src/index.ts#L335-L337 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CitrineOSServer.constructor | constructor(
config: SystemConfig,
server?: FastifyInstance,
ajv?: Ajv,
cache?: ICache,
) {
// Set system config
// TODO: Create and export config schemas for each util module, such as amqp, redis, kafka, etc, to avoid passing them possibly invalid configuration
if (!config.util.messageBroker.amqp) {
throw new Error(
'This server implementation requires amqp configuration for rabbitMQ.',
);
}
this._config = config;
// Create server instance
this._server =
server || fastify().withTypeProvider<JsonSchemaToTsProvider>();
// Add health check
this._server.get('/health', async () => ({ status: 'healthy' }));
// Create Ajv JSON schema validator instance
this._ajv =
ajv ||
new Ajv({
removeAdditional: 'all',
useDefaults: true,
coerceTypes: 'array',
strict: false,
});
addFormats(this._ajv, { mode: 'fast', formats: ['date-time'] });
// Initialize parent logger
this._logger = new Logger<ILogObj>({
name: 'CitrineOS Logger',
minLevel: systemConfig.logLevel,
hideLogPositionForProduction: systemConfig.env === 'production',
// Disable colors for cloud deployment as some cloude logging environments such as cloudwatch can not interpret colors
stylePrettyLogs: process.env.DEPLOYMENT_TARGET != 'cloud',
});
// Force sync database
sequelize.DefaultSequelizeInstance.getInstance(
this._config,
this._logger,
true,
);
// Set cache implementation
this._cache =
cache ||
(this._config.util.cache.redis
? new RedisCache({
socket: {
host: this._config.util.cache.redis.host,
port: this._config.util.cache.redis.port,
},
})
: new MemoryCache());
// Initialize Swagger if enabled
if (this._config.util.swagger) {
initSwagger(this._config, this._server);
}
// Add Directus Message API flow creation if enabled
if (this._config.util.directus?.generateFlows) {
const directusUtil = new DirectusUtil(this._config, this._logger);
this._server.addHook(
'onRoute',
directusUtil.addDirectusMessageApiFlowsFastifyRouteHook.bind(
directusUtil,
),
);
this._server.addHook('onReady', async () => {
this._logger.info('Directus actions initialization finished');
});
}
// Register AJV for schema validation
this._server.setValidatorCompiler(({ schema, method, url, httpPart }) =>
this._ajv.compile(schema),
);
this._authenticator = new Authenticator(
new UnknownStationFilter(
new sequelize.LocationRepository(this._config, this._logger),
this._logger,
),
new ConnectedStationFilter(this._cache, this._logger),
new BasicAuthenticationFilter(
new sequelize.DeviceModelRepository(this._config, this._logger),
this._logger,
),
this._logger,
);
const router = new MessageRouterImpl(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
async (identifier: string, message: string) => false,
this._logger,
this._ajv,
);
this._networkConnection = new WebsocketNetworkConnection(
this._config,
this._cache,
this._authenticator,
router,
this._logger,
);
const api = new AdminApi(router, this._server, this._logger);
process.on('SIGINT', this.shutdown.bind(this));
process.on('SIGTERM', this.shutdown.bind(this));
process.on('SIGQUIT', this.shutdown.bind(this));
} | /**
* Constructor for the class.
*
* @param {FastifyInstance} server - optional Fastify server instance
* @param {Ajv} ajv - optional Ajv JSON schema validator instance
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/Swarm/src/index.ts#L80-L201 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ModuleService.constructor | constructor(
config: SystemConfig,
appName: string,
server?: FastifyInstance,
ajv?: Ajv,
cache?: ICache,
) {
// Set system config
// TODO: Create and export config schemas for each util module, such as amqp, redis, kafka, etc, to avoid passing them possibly invalid configuration
if (!config.util.messageBroker.amqp) {
throw new Error(
'This server implementation requires amqp configuration for rabbitMQ.',
);
}
this._config = config;
// Create server instance
this._server =
server || fastify().withTypeProvider<JsonSchemaToTsProvider>();
// Add health check
this._server.get('/health', async () => ({ status: 'healthy' }));
// Create Ajv JSON schema validator instance
this._ajv =
ajv ||
new Ajv({
removeAdditional: 'all',
useDefaults: true,
coerceTypes: 'array',
strict: false,
});
addFormats(this._ajv, { mode: 'fast', formats: ['date-time'] });
// Initialize parent logger
this._logger = new Logger<ILogObj>({
name: 'CitrineOS Logger',
minLevel: systemConfig.logLevel,
hideLogPositionForProduction: systemConfig.env === 'production',
});
// Set cache implementation
this._cache =
cache ||
(this._config.util.cache.redis
? new RedisCache({
socket: {
host: this._config.util.cache.redis.host,
port: this._config.util.cache.redis.port,
},
})
: new MemoryCache());
// Initialize Swagger if enabled
if (this._config.util.swagger) {
initSwagger(this._config, this._server);
}
// Add Directus Message API flow creation if enabled
if (this._config.util.directus?.generateFlows) {
const directusUtil = new DirectusUtil(this._config, this._logger);
this._server.addHook(
'onRoute',
directusUtil.addDirectusMessageApiFlowsFastifyRouteHook.bind(
directusUtil,
),
);
}
// Register AJV for schema validation
this._server.setValidatorCompiler(({ schema, method, url, httpPart }) =>
this._ajv.compile(schema),
);
// Initialize module & API
// Always initialize API after SwaggerUI
switch (appName) {
case EventGroup.Certificates:
if (this._config.modules.certificates) {
this._module = new CertificatesModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new CertificatesModuleApi(
this._module as CertificatesModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('Certificates module started...');
this._host = this._config.modules.certificates.host as string;
this._port = this._config.modules.certificates.port as number;
break;
} else throw new Error('No config for Certificates module');
case EventGroup.Configuration:
if (this._config.modules.configuration) {
this._module = new ConfigurationModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new ConfigurationModuleApi(
this._module as ConfigurationModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('Configuration module started...');
this._host = this._config.modules.configuration.host as string;
this._port = this._config.modules.configuration.port as number;
break;
} else throw new Error('No config for Configuration module');
case EventGroup.EVDriver:
if (this._config.modules.evdriver) {
this._module = new EVDriverModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new EVDriverModuleApi(
this._module as EVDriverModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('EVDriver module started...');
this._host = this._config.modules.evdriver.host as string;
this._port = this._config.modules.evdriver.port as number;
break;
} else throw new Error('No config for EVDriver module');
case EventGroup.Monitoring:
if (this._config.modules.monitoring) {
this._module = new MonitoringModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new MonitoringModuleApi(
this._module as MonitoringModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('Monitoring module started...');
this._host = this._config.modules.monitoring.host as string;
this._port = this._config.modules.monitoring.port as number;
break;
} else throw new Error('No config for Monitoring module');
case EventGroup.Reporting:
if (this._config.modules.reporting) {
this._module = new ReportingModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new ReportingModuleApi(
this._module as ReportingModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('Reporting module started...');
this._host = this._config.modules.reporting.host as string;
this._port = this._config.modules.reporting.port as number;
break;
} else throw new Error('No config for Reporting module');
case EventGroup.SmartCharging:
if (this._config.modules.smartcharging) {
this._module = new SmartChargingModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new SmartChargingModuleApi(
this._module as SmartChargingModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('SmartCharging module started...');
this._host = this._config.modules.smartcharging.host as string;
this._port = this._config.modules.smartcharging.port as number;
break;
} else throw new Error('No config for SmartCharging module');
case EventGroup.Tenant:
if (this._config.modules.tenant) {
this._module = new TenantModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new TenantModuleApi(
this._module as TenantModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('Tenant module started...');
this._host = this._config.modules.tenant.host as string;
this._port = this._config.modules.tenant.port as number;
break;
} else throw new Error('No config for Tenant module');
case EventGroup.Transactions:
if (this._config.modules.transactions) {
this._module = new TransactionsModule(
this._config,
this._cache,
this._createSender(),
this._createHandler(),
this._logger,
);
this._api = new TransactionsModuleApi(
this._module as TransactionsModule,
this._server,
this._logger,
);
// TODO: take actions to make sure module has correct subscriptions and log proof
this._logger.info('Transactions module started...');
this._host = this._config.modules.transactions.host as string;
this._port = this._config.modules.transactions.port as number;
break;
} else throw new Error('No config for Transactions module');
default:
throw new Error('Unhandled module type: ' + appName);
}
process.on('SIGINT', this.shutdown.bind(this));
process.on('SIGTERM', this.shutdown.bind(this));
process.on('SIGQUIT', this.shutdown.bind(this));
} | /**
* Constructor for the class.
*
* @param {FastifyInstance} server - optional Fastify server instance
* @param {Ajv} ajv - optional Ajv JSON schema validator instance
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/Swarm/src/index.ts#L265-L509 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
himalaya-ui | github_2023 | red-ninjas | typescript | getScaleAmount | const getScaleAmount = (orignalSize: number, scaleAmount: number) => {
return `${parseInt(String(orignalSize * scaleAmount))}px`;
}; | /**
* Calculates amount to scale cursor in px3
* @param {number} orignalSize - starting size
* @param {number} scaleAmount - Amount to scale
* @returns {String} Scale amount in px
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/animated-cursor/animated-cursor.tsx#L130-L132 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | fetchData | const fetchData = async () => {
if (searchFunction == undefined) {
return [];
}
const data = await searchFunction(input);
setResults(data);
setPreventHover(true);
itemsRef.current?.scrollTo(0, 0);
return data;
}; | // declare the data fetching function | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/search/search.tsx#L90-L100 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | hue2rgb | const hue2rgb = (p: number, q: number, t: number) => {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}; | // tslint:disable-next-line:no-shadowed-variable | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/themes/utils/color.ts#L53-L70 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | ChartWidget._applyAutoSizeOptions | private _applyAutoSizeOptions(options: DeepPartial<ChartOptionsInternal<HorzScaleItem>>): void {
if (options.autoSize === undefined && this._observer && (options.width !== undefined || options.height !== undefined)) {
warn(`You should turn autoSize off explicitly before specifying sizes; try adding options.autoSize: false to new options`);
return;
}
if (options.autoSize && !this._observer) {
// installing observer will override resize if successful
this._installObserver();
}
if (options.autoSize === false && this._observer !== null) {
this._uninstallObserver();
}
if (!options.autoSize && (options.width !== undefined || options.height !== undefined)) {
this.resize(options.width || this._width, options.height || this._height);
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/chart-widget.ts#L315-L332 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | ChartWidget._traverseLayout | private _traverseLayout(ctx: CanvasRenderingContext2D | null): Size {
let totalWidth = 0;
let totalHeight = 0;
const firstPane = this._paneWidgets[0];
const drawPriceAxises = (position: 'left' | 'right', targetX: number) => {
let targetY = 0;
for (let paneIndex = 0; paneIndex < this._paneWidgets.length; paneIndex++) {
const paneWidget = this._paneWidgets[paneIndex];
const priceAxisWidget = ensureNotNull(position === 'left' ? paneWidget.leftPriceAxisWidget() : paneWidget.rightPriceAxisWidget());
const bitmapSize = priceAxisWidget.getBitmapSize();
if (ctx !== null) {
priceAxisWidget.drawBitmap(ctx, targetX, targetY);
}
targetY += bitmapSize.height;
// if (paneIndex < this._paneWidgets.length - 1) {
// const separator = this._paneSeparators[paneIndex];
// const separatorBitmapSize = separator.getBitmapSize();
// if (ctx !== null) {
// separator.drawBitmap(ctx, targetX, targetY);
// }
// targetY += separatorBitmapSize.height;
// }
}
};
// draw left price scale if exists
if (this._isLeftAxisVisible()) {
drawPriceAxises('left', 0);
const leftAxisBitmapWidth = ensureNotNull(firstPane.leftPriceAxisWidget()).getBitmapSize().width;
totalWidth += leftAxisBitmapWidth;
}
for (let paneIndex = 0; paneIndex < this._paneWidgets.length; paneIndex++) {
const paneWidget = this._paneWidgets[paneIndex];
const bitmapSize = paneWidget.getBitmapSize();
if (ctx !== null) {
paneWidget.drawBitmap(ctx, totalWidth, totalHeight);
}
totalHeight += bitmapSize.height;
// if (paneIndex < this._paneWidgets.length - 1) {
// const separator = this._paneSeparators[paneIndex];
// const separatorBitmapSize = separator.getBitmapSize();
// if (ctx !== null) {
// separator.drawBitmap(ctx, totalWidth, totalHeight);
// }
// totalHeight += separatorBitmapSize.height;
// }
}
const firstPaneBitmapWidth = firstPane.getBitmapSize().width;
totalWidth += firstPaneBitmapWidth;
// draw right price scale if exists
if (this._isRightAxisVisible()) {
drawPriceAxises('right', totalWidth);
const rightAxisBitmapWidth = ensureNotNull(firstPane.rightPriceAxisWidget()).getBitmapSize().width;
totalWidth += rightAxisBitmapWidth;
}
const drawStub = (position: 'left' | 'right', targetX: number, targetY: number) => {
const stub = ensureNotNull(position === 'left' ? this._timeAxisWidget.leftStub() : this._timeAxisWidget.rightStub());
stub.drawBitmap(ensureNotNull(ctx), targetX, targetY);
};
// draw time scale and stubs
if (this._options.timeScale.visible) {
const timeAxisBitmapSize = this._timeAxisWidget.getBitmapSize();
if (ctx !== null) {
let targetX = 0;
if (this._isLeftAxisVisible()) {
drawStub('left', targetX, totalHeight);
targetX = ensureNotNull(firstPane.leftPriceAxisWidget()).getBitmapSize().width;
}
this._timeAxisWidget.drawBitmap(ctx, targetX, totalHeight);
targetX += timeAxisBitmapSize.width;
if (this._isRightAxisVisible()) {
drawStub('right', targetX, totalHeight);
}
}
totalHeight += timeAxisBitmapSize.height;
}
return size({
width: totalWidth,
height: totalHeight,
});
} | /**
* Traverses the widget's layout (pane and axis child widgets),
* draws the screenshot (if rendering context is passed) and returns the screenshot bitmap size
*
* @param ctx - if passed, used to draw the screenshot of widget
* @returns screenshot bitmap size
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/chart-widget.ts#L341-L431 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | ChartWidget._adjustSizeImpl | private _adjustSizeImpl(): void {
let totalStretch = 0;
let leftPriceAxisWidth = 0;
let rightPriceAxisWidth = 0;
for (const paneWidget of this._paneWidgets) {
if (this._isLeftAxisVisible()) {
leftPriceAxisWidth = Math.max(
leftPriceAxisWidth,
ensureNotNull(paneWidget.leftPriceAxisWidget()).optimalWidth(),
this._options.leftPriceScale.minimumWidth,
);
}
if (this._isRightAxisVisible()) {
rightPriceAxisWidth = Math.max(
rightPriceAxisWidth,
ensureNotNull(paneWidget.rightPriceAxisWidget()).optimalWidth(),
this._options.rightPriceScale.minimumWidth,
);
}
totalStretch += paneWidget.stretchFactor();
}
leftPriceAxisWidth = suggestPriceScaleWidth(leftPriceAxisWidth);
rightPriceAxisWidth = suggestPriceScaleWidth(rightPriceAxisWidth);
const width = this._width;
const height = this._height;
const paneWidth = Math.max(width - leftPriceAxisWidth - rightPriceAxisWidth, 0);
// const separatorCount = this._paneSeparators.length;
// const separatorHeight = SEPARATOR_HEIGHT;
const separatorsHeight = 0; // separatorHeight * separatorCount;
const timeAxisVisible = this._options.timeScale.visible;
let timeAxisHeight = timeAxisVisible ? Math.max(this._timeAxisWidget.optimalHeight(), this._options.timeScale.minimumHeight) : 0;
timeAxisHeight = suggestTimeScaleHeight(timeAxisHeight);
const otherWidgetHeight = separatorsHeight + timeAxisHeight;
const totalPaneHeight = height < otherWidgetHeight ? 0 : height - otherWidgetHeight;
const stretchPixels = totalPaneHeight / totalStretch;
let accumulatedHeight = 0;
for (let paneIndex = 0; paneIndex < this._paneWidgets.length; ++paneIndex) {
const paneWidget = this._paneWidgets[paneIndex];
paneWidget.setState(this._model.panes()[paneIndex]);
let paneHeight = 0;
let calculatePaneHeight = 0;
if (paneIndex === this._paneWidgets.length - 1) {
calculatePaneHeight = totalPaneHeight - accumulatedHeight;
} else {
calculatePaneHeight = Math.round(paneWidget.stretchFactor() * stretchPixels);
}
paneHeight = Math.max(calculatePaneHeight, 2);
accumulatedHeight += paneHeight;
paneWidget.setSize(size({ width: paneWidth, height: paneHeight }));
if (this._isLeftAxisVisible()) {
paneWidget.setPriceAxisSize(leftPriceAxisWidth, 'left');
}
if (this._isRightAxisVisible()) {
paneWidget.setPriceAxisSize(rightPriceAxisWidth, 'right');
}
if (paneWidget.state()) {
this._model.setPaneHeight(paneWidget.state(), paneHeight);
}
}
this._timeAxisWidget.setSizes(
size({ width: timeAxisVisible ? paneWidth : 0, height: timeAxisHeight }),
timeAxisVisible ? leftPriceAxisWidth : 0,
timeAxisVisible ? rightPriceAxisWidth : 0,
);
this._model.setWidth(paneWidth);
if (this._leftPriceAxisWidth !== leftPriceAxisWidth) {
this._leftPriceAxisWidth = leftPriceAxisWidth;
}
if (this._rightPriceAxisWidth !== rightPriceAxisWidth) {
this._rightPriceAxisWidth = rightPriceAxisWidth;
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/chart-widget.ts#L434-L520 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | ChartWidget._syncGuiWithModel | private _syncGuiWithModel(): void {
const panes = this._model.panes();
const targetPaneWidgetsCount = panes.length;
const actualPaneWidgetsCount = this._paneWidgets.length;
// Remove (if needed) pane widgets and separators
for (let i = targetPaneWidgetsCount; i < actualPaneWidgetsCount; i++) {
const paneWidget = ensureDefined(this._paneWidgets.pop());
this._tableElement.removeChild(paneWidget.getElement());
paneWidget.clicked().unsubscribeAll(this);
paneWidget.dblClicked().unsubscribeAll(this);
paneWidget.destroy();
// const paneSeparator = this._paneSeparators.pop();
// if (paneSeparator !== undefined) {
// this._destroySeparator(paneSeparator);
// }
}
// Create (if needed) new pane widgets and separators
for (let i = actualPaneWidgetsCount; i < targetPaneWidgetsCount; i++) {
const paneWidget = new PaneWidget(this, panes[i]);
paneWidget.clicked().subscribe(this._onPaneWidgetClicked.bind(this), this);
paneWidget.dblClicked().subscribe(this._onPaneWidgetDblClicked.bind(this), this);
this._paneWidgets.push(paneWidget);
// create and insert separator
// if (i > 1) {
// const paneSeparator = new PaneSeparator(this, i - 1, i, true);
// this._paneSeparators.push(paneSeparator);
// this._tableElement.insertBefore(paneSeparator.getElement(), this._timeAxisWidget.getElement());
// }
// insert paneWidget
this._tableElement.insertBefore(paneWidget.getElement(), this._timeAxisWidget.getElement());
}
for (let i = 0; i < targetPaneWidgetsCount; i++) {
const state = panes[i];
const paneWidget = this._paneWidgets[i];
if (paneWidget.state() !== state) {
paneWidget.setState(state);
} else {
paneWidget.updatePriceAxisWidgetsStates();
}
}
this._updateTimeAxisVisibility();
this._adjustSizeImpl();
} | // } | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/chart-widget.ts#L694-L744 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | MouseEventHandler._onMobileSafariDoubleClick | private _onFirefoxOutsideMouseUp = (mouseUpEvent: MouseEvent) => {
this._mouseUpHandler(mouseUpEvent);
} | /**
* Safari doesn't fire touchstart/mousedown events on double tap since iOS 13.
* There are two possible solutions:
* 1) Call preventDefault in touchEnd handler. But it also prevents click event from firing.
* 2) Add listener on dblclick event that fires with the preceding mousedown/mouseup.
* https://developer.apple.com/forums/thread/125073
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/mouse-event-handler.ts | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | MouseEventHandler._touchEndHandler | private _touchEndHandler(touchEndEvent: TouchEvent): void {
let touch = touchWithId(touchEndEvent.changedTouches, ensureNotNull(this._activeTouchId));
if (touch === null && touchEndEvent.touches.length === 0) {
// something went wrong, somehow we missed the required touchend event
// probably the browser has not sent this event
touch = touchEndEvent.changedTouches[0];
}
if (touch === null) {
return;
}
this._activeTouchId = null;
this._lastTouchEventTimeStamp = eventTimeStamp(touchEndEvent);
this._clearLongTapTimeout();
this._touchMoveStartPosition = null;
if (this._unsubscribeRootTouchEvents) {
this._unsubscribeRootTouchEvents();
this._unsubscribeRootTouchEvents = null;
}
const compatEvent = this._makeCompatEvent(touchEndEvent, touch);
this._processTouchEvent(compatEvent, this._handler.touchEndEvent);
++this._tapCount;
if (this._tapTimeoutId && this._tapCount > 1) {
// check that both clicks are near enough
const { manhattanDistance } = this._touchMouseMoveWithDownInfo(getPosition(touch), this._tapPosition);
if (manhattanDistance < Constants.DoubleTapManhattanDistance && !this._cancelTap) {
this._processTouchEvent(compatEvent, this._handler.doubleTapEvent);
}
this._resetTapTimeout();
} else {
if (!this._cancelTap) {
this._processTouchEvent(compatEvent, this._handler.tapEvent);
// do not fire mouse events if tap handler was executed
// prevent click event on new dom element (who appeared after tap)
if (this._handler.tapEvent) {
preventDefault(touchEndEvent);
}
}
}
// prevent, for example, safari's dblclick-to-zoom or fast-click after long-tap
// we handle mouseDoubleClickEvent here ourselves
if (this._tapCount === 0) {
preventDefault(touchEndEvent);
}
if (touchEndEvent.touches.length === 0) {
if (this._longTapActive) {
this._longTapActive = false;
// prevent native click event
preventDefault(touchEndEvent);
}
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/mouse-event-handler.ts#L387-L445 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | comparePrimitiveZOrder | function comparePrimitiveZOrder(item: SeriesPrimitivePaneViewZOrder, reference?: SeriesPrimitivePaneViewZOrder): boolean {
return !reference || (item === 'top' && reference !== 'top') || (item === 'normal' && reference === 'bottom');
} | // returns true if item is above reference | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/pane-hit-test.ts#L26-L28 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | hitTestPaneView | function hitTestPaneView(paneViews: readonly IPaneView[], x: Coordinate, y: Coordinate): HitTestPaneViewResult | null {
for (const paneView of paneViews) {
const renderer = paneView.renderer();
if (renderer !== null && renderer.hitTest) {
const result = renderer.hitTest(x, y);
if (result !== null) {
return {
view: paneView,
object: result,
};
}
}
}
return null;
} | /**
* Performs a hit test on a collection of pane views to determine which view and object
* is located at a given coordinate (x, y) and returns the matching pane view and
* hit-tested result object, or null if no match is found.
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/pane-hit-test.ts#L66-L81 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PaneWidget._pressedMouseTouchMoveEvent | private _pressedMouseTouchMoveEvent(event: TouchMouseEvent): void {
if (this._state === null) {
return;
}
const model = this._model();
const timeScale = model.timeScale();
if (timeScale.isEmpty()) {
return;
}
const chartOptions = this._chart.options();
const scrollOptions = chartOptions.handleScroll;
const kineticScrollOptions = chartOptions.kineticScroll;
if ((!scrollOptions.pressedMouseMove || event.isTouch) && ((!scrollOptions.horzTouchDrag && !scrollOptions.vertTouchDrag) || !event.isTouch)) {
return;
}
const priceScale = this._state.defaultPriceScale();
const now = performance.now();
if (this._startScrollingPos === null && !this._preventScroll(event)) {
this._startScrollingPos = {
x: event.clientX,
y: event.clientY,
timestamp: now,
localX: event.localX,
localY: event.localY,
};
}
if (
this._startScrollingPos !== null &&
!this._isScrolling &&
(this._startScrollingPos.x !== event.clientX || this._startScrollingPos.y !== event.clientY)
) {
if ((event.isTouch && kineticScrollOptions.touch) || (!event.isTouch && kineticScrollOptions.mouse)) {
const barSpacing = timeScale.barSpacing();
this._scrollXAnimation = new KineticAnimation(
KineticScrollConstants.MinScrollSpeed / barSpacing,
KineticScrollConstants.MaxScrollSpeed / barSpacing,
KineticScrollConstants.DumpingCoeff,
KineticScrollConstants.ScrollMinMove / barSpacing,
);
this._scrollXAnimation.addPosition(timeScale.rightOffset() as Coordinate, this._startScrollingPos.timestamp);
} else {
this._scrollXAnimation = null;
}
if (!priceScale.isEmpty()) {
model.startScrollPrice(this._state, priceScale, event.localY);
}
model.startScrollTime(event.localX);
this._isScrolling = true;
}
if (this._isScrolling) {
// this allows scrolling not default price scales
if (!priceScale.isEmpty()) {
model.scrollPriceTo(this._state, priceScale, event.localY);
}
model.scrollTimeTo(event.localX);
if (this._scrollXAnimation !== null) {
this._scrollXAnimation.addPosition(timeScale.rightOffset() as Coordinate, now);
}
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/gui/pane-widget.ts#L714-L784 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | ChartModel.zoomTime | public zoomTime(pointX: Coordinate, scale: number): void {
const timeScale = this.timeScale();
if (timeScale.isEmpty() || scale === 0) {
return;
}
const timeScaleWidth = timeScale.width();
pointX = Math.max(1, Math.min(pointX, timeScaleWidth)) as Coordinate;
timeScale.zoom(pointX, scale);
this.recalculateAllPanes();
} | /**
* Zoom in/out the chart (depends on scale value).
*
* @param pointX - X coordinate of the point to apply the zoom (the point which should stay on its place)
* @param scale - Zoom value. Negative value means zoom out, positive - zoom in.
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/chart-model.ts#L680-L692 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | DataLayer._replaceTimeScalePoints | private _replaceTimeScalePoints(newTimePoints: InternalTimeScalePoint[]): number {
let firstChangedPointIndex = -1;
// search the first different point and "syncing" time weight by the way
for (let index = 0; index < this._sortedTimePoints.length && index < newTimePoints.length; ++index) {
const oldPoint = this._sortedTimePoints[index];
const newPoint = newTimePoints[index];
if (this._horzScaleBehavior.key(oldPoint.time) !== this._horzScaleBehavior.key(newPoint.time)) {
firstChangedPointIndex = index;
break;
}
// re-assign point's time weight for points if time is the same (and all prior times was the same)
newPoint.timeWeight = oldPoint.timeWeight;
assignIndexToPointData(newPoint.pointData, index as TimePointIndex);
}
if (firstChangedPointIndex === -1 && this._sortedTimePoints.length !== newTimePoints.length) {
// the common part of the prev and the new points are the same
// so the first changed point is the next after the common part
firstChangedPointIndex = Math.min(this._sortedTimePoints.length, newTimePoints.length);
}
if (firstChangedPointIndex === -1) {
// if no time scale changed, then do nothing
return -1;
}
// if time scale points are changed that means that we need to make full update to all series (with clearing points)
// but first we need to synchronize indexes and re-fill time weights
for (let index = firstChangedPointIndex; index < newTimePoints.length; ++index) {
assignIndexToPointData(newTimePoints[index].pointData, index as TimePointIndex);
}
// re-fill time weights for point after the first changed one
this._horzScaleBehavior.fillWeightsForPoints(newTimePoints, firstChangedPointIndex);
this._sortedTimePoints = newTimePoints;
return firstChangedPointIndex;
} | /**
* Sets new time scale and make indexes valid for all series
*
* @returns The index of the first changed point or `-1` if there is no change.
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/data-layer.ts#L379-L420 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PlotList.last | public last(): PlotRowType | null {
return this.size() > 0 ? this._items[this._items.length - 1] : null;
} | // @returns Last row | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/plot-list.ts#L46-L48 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PriceScale.setMode | public setMode(newMode: Partial<PriceScaleState>): void {
const oldMode = this.mode();
let priceRange: PriceRangeImpl | null = null;
if (newMode.autoScale !== undefined) {
this._options.autoScale = newMode.autoScale;
}
if (newMode.mode !== undefined) {
this._options.mode = newMode.mode;
if (newMode.mode === PriceScaleMode.Percentage || newMode.mode === PriceScaleMode.IndexedTo100) {
this._options.autoScale = true;
}
// TODO: Remove after making rebuildTickMarks lazy
this._invalidatedForRange.isValid = false;
}
// define which scale converted from
if (oldMode.mode === PriceScaleMode.Logarithmic && newMode.mode !== oldMode.mode) {
if (canConvertPriceRangeFromLog(this._priceRange, this._logFormula)) {
priceRange = convertPriceRangeFromLog(this._priceRange, this._logFormula);
if (priceRange !== null) {
this.setPriceRange(priceRange);
}
} else {
this._options.autoScale = true;
}
}
// define which scale converted to
if (newMode.mode === PriceScaleMode.Logarithmic && newMode.mode !== oldMode.mode) {
priceRange = convertPriceRangeToLog(this._priceRange, this._logFormula);
if (priceRange !== null) {
this.setPriceRange(priceRange);
}
}
const modeChanged = oldMode.mode !== this._options.mode;
if (modeChanged && (oldMode.mode === PriceScaleMode.Percentage || this.isPercentage())) {
this.updateFormatter();
}
if (modeChanged && (oldMode.mode === PriceScaleMode.IndexedTo100 || this.isIndexedTo100())) {
this.updateFormatter();
}
if (newMode.isInverted !== undefined && oldMode.isInverted !== newMode.isInverted) {
this._options.invertScale = newMode.isInverted;
this._onIsInvertedChanged();
}
this._modeChanged.fire(oldMode, this.mode());
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/price-scale.ts#L314-L368 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PriceScale._formatterSource | private _formatterSource(): IPriceDataSource | null {
return this._dataSources[0] || null;
} | /**
* @returns The {@link IPriceDataSource} that will be used as the "formatter source" (take minMove for formatter).
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/price-scale.ts#L834-L836 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PriceScale._recalculatePriceRangeImpl | private _recalculatePriceRangeImpl(): void {
const visibleBars = this._invalidatedForRange.visibleBars;
if (visibleBars === null) {
return;
}
let priceRange: PriceRangeImpl | null = null;
const sources = this.sourcesForAutoScale();
let marginAbove = 0;
let marginBelow = 0;
for (const source of sources) {
if (!source.visible()) {
continue;
}
const firstValue = source.firstValue();
if (firstValue === null) {
continue;
}
const autoScaleInfo = source.autoscaleInfo(visibleBars.left(), visibleBars.right());
let sourceRange = autoScaleInfo && autoScaleInfo.priceRange();
if (sourceRange !== null) {
switch (this._options.mode) {
case PriceScaleMode.Logarithmic:
sourceRange = convertPriceRangeToLog(sourceRange, this._logFormula);
break;
case PriceScaleMode.Percentage:
sourceRange = toPercentRange(sourceRange, firstValue.value);
break;
case PriceScaleMode.IndexedTo100:
sourceRange = toIndexedTo100Range(sourceRange, firstValue.value);
break;
}
if (priceRange === null) {
priceRange = sourceRange;
} else {
priceRange = priceRange.merge(ensureNotNull(sourceRange));
}
if (autoScaleInfo !== null) {
const margins = autoScaleInfo.margins();
if (margins !== null) {
marginAbove = Math.max(marginAbove, margins.above);
marginBelow = Math.max(marginAbove, margins.below);
}
}
}
}
if (marginAbove !== this._marginAbove || marginBelow !== this._marginBelow) {
this._marginAbove = marginAbove;
this._marginBelow = marginBelow;
this._marksCache = null;
this._invalidateInternalHeightCache();
}
if (priceRange !== null) {
// keep current range is new is empty
if (priceRange.minValue() === priceRange.maxValue()) {
const formatterSource = this._formatterSource();
const minMove = formatterSource === null || this.isPercentage() || this.isIndexedTo100() ? 1 : formatterSource.minMove();
// if price range is degenerated to 1 point let's extend it by 10 min move values
// to avoid incorrect range and empty (blank) scale (in case of min tick much greater than 1)
const extendValue = 5 * minMove;
if (this.isLog()) {
priceRange = convertPriceRangeFromLog(priceRange, this._logFormula);
}
priceRange = new PriceRangeImpl(priceRange.minValue() - extendValue, priceRange.maxValue() + extendValue);
if (this.isLog()) {
priceRange = convertPriceRangeToLog(priceRange, this._logFormula);
}
}
if (this.isLog()) {
const rawRange = convertPriceRangeFromLog(priceRange, this._logFormula);
const newLogFormula = logFormulaForPriceRange(rawRange);
if (!logFormulasAreSame(newLogFormula, this._logFormula)) {
const rawSnapshot = this._priceRangeSnapshot !== null ? convertPriceRangeFromLog(this._priceRangeSnapshot, this._logFormula) : null;
this._logFormula = newLogFormula;
priceRange = convertPriceRangeToLog(rawRange, newLogFormula);
if (rawSnapshot !== null) {
this._priceRangeSnapshot = convertPriceRangeToLog(rawSnapshot, newLogFormula);
}
}
}
this.setPriceRange(priceRange);
} else {
// reset empty to default
if (this._priceRange === null) {
this.setPriceRange(new PriceRangeImpl(-0.5, 0.5));
this._logFormula = logFormulaForPriceRange(null);
}
}
this._invalidatedForRange.isValid = true;
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/price-scale.ts#L892-L997 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | TimeScale.visibleStrictRange | public visibleStrictRange(): RangeImpl<TimePointIndex> | null {
this._updateVisibleRange();
return this._visibleRange.strictRange();
} | // strict range: integer indices of the bars in the visible range rounded in more wide direction | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/time-scale.ts#L343-L346 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | TimeScale.marks | public marks(): TimeMark[] | null {
if (this.isEmpty()) {
return null;
}
if (this._timeMarksCache !== null) {
return this._timeMarksCache;
}
const spacing = this._barSpacing;
const fontSize = this._model.options().layout.fontSize;
const pixelsPer8Characters = (fontSize + 4) * 5;
const pixelsPerCharacter = pixelsPer8Characters / defaultTickMarkMaxCharacterLength;
const maxLabelWidth = pixelsPerCharacter * (this._options.tickMarkMaxCharacterLength || defaultTickMarkMaxCharacterLength);
const indexPerLabel = Math.round(maxLabelWidth / spacing);
const visibleBars = ensureNotNull(this.visibleStrictRange());
const firstBar = Math.max(visibleBars.left(), visibleBars.left() - indexPerLabel);
const lastBar = Math.max(visibleBars.right(), visibleBars.right() - indexPerLabel);
const items = this._tickMarks.build(spacing, maxLabelWidth);
// according to indexPerLabel value this value means "earliest index which _might be_ used as the second label on time scale"
const earliestIndexOfSecondLabel = (this._firstIndex() as number) + indexPerLabel;
// according to indexPerLabel value this value means "earliest index which _might be_ used as the second last label on time scale"
const indexOfSecondLastLabel = (this._lastIndex() as number) - indexPerLabel;
const isAllScalingAndScrollingDisabled = this._isAllScalingAndScrollingDisabled();
const isLeftEdgeFixed = this._options.fixLeftEdge || isAllScalingAndScrollingDisabled;
const isRightEdgeFixed = this._options.fixRightEdge || isAllScalingAndScrollingDisabled;
let targetIndex = 0;
for (const tm of items) {
if (!(firstBar <= tm.index && tm.index <= lastBar)) {
continue;
}
let label: TimeMark;
if (targetIndex < this._labels.length) {
label = this._labels[targetIndex];
label.coord = this.indexToCoordinate(tm.index);
label.label = this._formatLabel(tm);
label.weight = tm.weight;
} else {
label = {
needAlignCoordinate: false,
coord: this.indexToCoordinate(tm.index),
label: this._formatLabel(tm),
weight: tm.weight,
};
this._labels.push(label);
}
if (this._barSpacing > maxLabelWidth / 2 && !isAllScalingAndScrollingDisabled) {
// if there is enough space then let's show all tick marks as usual
label.needAlignCoordinate = false;
} else {
// if a user is able to scroll after a tick mark then show it as usual, otherwise the coordinate might be aligned
// if the index is for the second (last) label or later (earlier) then most likely this label might be displayed without correcting the coordinate
label.needAlignCoordinate = (isLeftEdgeFixed && tm.index <= earliestIndexOfSecondLabel) || (isRightEdgeFixed && tm.index >= indexOfSecondLastLabel);
}
targetIndex++;
}
this._labels.length = targetIndex;
this._timeMarksCache = this._labels;
return this._labels;
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/time-scale.ts#L490-L563 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | TimeScale.zoom | public zoom(zoomPoint: Coordinate, scale: number): void {
const floatIndexAtZoomPoint = this._coordinateToFloatIndex(zoomPoint);
const barSpacing = this.barSpacing();
const newBarSpacing = barSpacing + scale * (barSpacing / 10);
// zoom in/out bar spacing
this.setBarSpacing(newBarSpacing);
if (!this._options.rightBarStaysOnScroll) {
// and then correct right offset to move index under zoomPoint back to its coordinate
this.setRightOffset(this.rightOffset() + (floatIndexAtZoomPoint - this._coordinateToFloatIndex(zoomPoint)));
}
} | /**
* Zoom in/out the scale around a `zoomPoint` on `scale` value.
*
* @param zoomPoint - X coordinate of the point to apply the zoom.
* If `rightBarStaysOnScroll` option is disabled, then will be used to restore right offset.
* @param scale - Zoom value (in 1/10 parts of current bar spacing).
* Negative value means zoom out, positive - zoom in.
*/ | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/time-scale.ts#L588-L601 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | weightToTickMarkType | function weightToTickMarkType(weight: TickMarkWeight, timeVisible: boolean, secondsVisible: boolean): TickMarkType {
switch (weight) {
case TickMarkWeight.LessThanSecond:
case TickMarkWeight.Second:
return timeVisible ? (secondsVisible ? TickMarkType.TimeWithSeconds : TickMarkType.Time) : TickMarkType.DayOfMonth;
case TickMarkWeight.Minute1:
case TickMarkWeight.Minute5:
case TickMarkWeight.Minute30:
case TickMarkWeight.Hour1:
case TickMarkWeight.Hour3:
case TickMarkWeight.Hour6:
case TickMarkWeight.Hour12:
return timeVisible ? TickMarkType.Time : TickMarkType.DayOfMonth;
case TickMarkWeight.Day:
return TickMarkType.DayOfMonth;
case TickMarkWeight.Month:
return TickMarkType.Month;
case TickMarkWeight.Year:
return TickMarkType.Year;
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/model/horz-scale-behavior-time/horz-scale-behavior-time.ts#L132-L156 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PaneRendererBars._drawImpl | protected override _drawImpl({ context: ctx, horizontalPixelRatio, verticalPixelRatio }: BitmapCoordinatesRenderingScope): void {
if (this._data === null || this._data.bars.length === 0 || this._data.visibleRange === null) {
return;
}
this._barWidth = this._calcBarWidth(horizontalPixelRatio);
// grid and crosshair have line width = Math.floor(pixelRatio)
// if this value is odd, we have to make bars' width odd
// if this value is even, we have to make bars' width even
// in order of keeping crosshair-over-bar drawing symmetric
if (this._barWidth >= 2) {
const lineWidth = Math.max(1, Math.floor(horizontalPixelRatio));
if (lineWidth % 2 !== this._barWidth % 2) {
this._barWidth--;
}
}
// if scale is compressed, bar could become less than 1 CSS pixel
this._barLineWidth = this._data.thinBars ? Math.min(this._barWidth, Math.floor(horizontalPixelRatio)) : this._barWidth;
let prevColor: string | null = null;
const drawOpenClose = this._barLineWidth <= this._barWidth && this._data.barSpacing >= Math.floor(1.5 * horizontalPixelRatio);
for (let i = this._data.visibleRange.from; i < this._data.visibleRange.to; ++i) {
const bar = this._data.bars[i];
if (prevColor !== bar.barColor) {
ctx.fillStyle = bar.barColor;
prevColor = bar.barColor;
}
const bodyWidthHalf = Math.floor(this._barLineWidth * 0.5);
const bodyCenter = Math.round(bar.x * horizontalPixelRatio);
const bodyLeft = bodyCenter - bodyWidthHalf;
const bodyWidth = this._barLineWidth;
const bodyRight = bodyLeft + bodyWidth - 1;
const high = Math.min(bar.highY, bar.lowY);
const low = Math.max(bar.highY, bar.lowY);
const bodyTop = Math.round(high * verticalPixelRatio) - bodyWidthHalf;
const bodyBottom = Math.round(low * verticalPixelRatio) + bodyWidthHalf;
const bodyHeight = Math.max(bodyBottom - bodyTop, this._barLineWidth);
ctx.fillRect(bodyLeft, bodyTop, bodyWidth, bodyHeight);
const sideWidth = Math.ceil(this._barWidth * 1.5);
if (drawOpenClose) {
if (this._data.openVisible) {
const openLeft = bodyCenter - sideWidth;
let openTop = Math.max(bodyTop, Math.round(bar.openY * verticalPixelRatio) - bodyWidthHalf);
let openBottom = openTop + bodyWidth - 1;
if (openBottom > bodyTop + bodyHeight - 1) {
openBottom = bodyTop + bodyHeight - 1;
openTop = openBottom - bodyWidth + 1;
}
ctx.fillRect(openLeft, openTop, bodyLeft - openLeft, openBottom - openTop + 1);
}
const closeRight = bodyCenter + sideWidth;
let closeTop = Math.max(bodyTop, Math.round(bar.closeY * verticalPixelRatio) - bodyWidthHalf);
let closeBottom = closeTop + bodyWidth - 1;
if (closeBottom > bodyTop + bodyHeight - 1) {
closeBottom = bodyTop + bodyHeight - 1;
closeTop = closeBottom - bodyWidth + 1;
}
ctx.fillRect(bodyRight + 1, closeTop, closeRight - bodyRight, closeBottom - closeTop + 1);
}
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/renderers/bars-renderer.ts#L35-L108 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | PaneRendererHistogram._fillPrecalculatedCache | private _fillPrecalculatedCache(pixelRatio: number): void {
if (this._data === null || this._data.items.length === 0 || this._data.visibleRange === null) {
this._precalculatedCache = [];
return;
}
const spacing = Math.ceil(this._data.barSpacing * pixelRatio) <= showSpacingMinimalBarWidth ? 0 : Math.max(1, Math.floor(pixelRatio));
const columnWidth = Math.round(this._data.barSpacing * pixelRatio) - spacing;
this._precalculatedCache = new Array(this._data.visibleRange.to - this._data.visibleRange.from);
for (let i = this._data.visibleRange.from; i < this._data.visibleRange.to; i++) {
const item = this._data.items[i];
// force cast to avoid ensureDefined call
const x = Math.round(item.x * pixelRatio);
let left: number;
let right: number;
if (columnWidth % 2) {
const halfWidth = (columnWidth - 1) / 2;
left = x - halfWidth;
right = x + halfWidth;
} else {
// shift pixel to left
const halfWidth = columnWidth / 2;
left = x - halfWidth;
right = x + halfWidth - 1;
}
this._precalculatedCache[i - this._data.visibleRange.from] = {
left,
right,
roundedCenter: x,
center: item.x * pixelRatio,
time: item.time,
};
}
// correct positions
for (let i = this._data.visibleRange.from + 1; i < this._data.visibleRange.to; i++) {
const current = this._precalculatedCache[i - this._data.visibleRange.from];
const prev = this._precalculatedCache[i - this._data.visibleRange.from - 1];
if (current.time !== prev.time + 1) {
continue;
}
if (current.left - prev.right !== spacing + 1) {
// have to align
if (prev.roundedCenter > prev.center) {
// prev wasshifted to left, so add pixel to right
prev.right = current.left - spacing - 1;
} else {
// extend current to left
current.left = prev.right + spacing + 1;
}
}
}
let minWidth = Math.ceil(this._data.barSpacing * pixelRatio);
for (let i = this._data.visibleRange.from; i < this._data.visibleRange.to; i++) {
const current = this._precalculatedCache[i - this._data.visibleRange.from];
// this could happen if barspacing < 1
if (current.right < current.left) {
current.right = current.left;
}
const width = current.right - current.left + 1;
minWidth = Math.min(width, minWidth);
}
if (spacing > 0 && minWidth < alignToMinimalWidthLimit) {
for (let i = this._data.visibleRange.from; i < this._data.visibleRange.to; i++) {
const current = this._precalculatedCache[i - this._data.visibleRange.from];
const width = current.right - current.left + 1;
if (width > minWidth) {
if (current.roundedCenter > current.center) {
current.right -= 1;
} else {
current.left += 1;
}
}
}
}
} | // eslint-disable-next-line complexity | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/renderers/histogram-renderer.ts#L76-L155 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | SeriesHorizontalBaseLinePaneView.constructor | public constructor(series: ISeries<SeriesType>) {
super(series);
} | // eslint-disable-next-line no-useless-constructor | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/views/pane/series-horizontal-base-line-pane-view.ts#L9-L11 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | fillSizeAndY | function fillSizeAndY(
rendererItem: SeriesMarkerRendererDataItem,
marker: InternalSeriesMarker<TimePointIndex>,
seriesData: BarPrices | BarPrice,
offsets: Offsets,
textHeight: number,
shapeMargin: number,
priceScale: PriceScale,
timeScale: ITimeScale,
firstValue: number,
): void {
const inBarPrice = isNumber(seriesData) ? seriesData : seriesData.close;
const highPrice = isNumber(seriesData) ? seriesData : seriesData.high;
const lowPrice = isNumber(seriesData) ? seriesData : seriesData.low;
const sizeMultiplier = isNumber(marker.size) ? Math.max(marker.size, 0) : 1;
const shapeSize = calculateShapeHeight(timeScale.barSpacing()) * sizeMultiplier;
const halfSize = shapeSize / 2;
rendererItem.size = shapeSize;
switch (marker.position) {
case 'inBar': {
rendererItem.y = priceScale.priceToCoordinate(inBarPrice, firstValue);
if (rendererItem.text !== undefined) {
rendererItem.text.y = (rendererItem.y + halfSize + shapeMargin + textHeight * (0.5 + Constants.TextMargin)) as Coordinate;
}
return;
}
case 'aboveBar': {
rendererItem.y = (priceScale.priceToCoordinate(highPrice, firstValue) - halfSize - offsets.aboveBar) as Coordinate;
if (rendererItem.text !== undefined) {
rendererItem.text.y = (rendererItem.y - halfSize - textHeight * (0.5 + Constants.TextMargin)) as Coordinate;
offsets.aboveBar += textHeight * (1 + 2 * Constants.TextMargin);
}
offsets.aboveBar += shapeSize + shapeMargin;
return;
}
case 'belowBar': {
rendererItem.y = (priceScale.priceToCoordinate(lowPrice, firstValue) + halfSize + offsets.belowBar) as Coordinate;
if (rendererItem.text !== undefined) {
rendererItem.text.y = (rendererItem.y + halfSize + shapeMargin + textHeight * (0.5 + Constants.TextMargin)) as Coordinate;
offsets.belowBar += textHeight * (1 + 2 * Constants.TextMargin);
}
offsets.belowBar += shapeSize + shapeMargin;
return;
}
}
ensureNever(marker.position);
} | // eslint-disable-next-line max-params | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/views/pane/series-markers-pane-view.ts#L30-L78 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | SeriesPriceLinePaneView.constructor | public constructor(series: ISeries<SeriesType>) {
super(series);
} | // eslint-disable-next-line no-useless-constructor | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/use-charts/views/pane/series-price-line-pane-view.ts#L8-L10 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
himalaya-ui | github_2023 | red-ninjas | typescript | update | const update: ContextHandlerWhere<S> = (_key, _next) => {}; | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/red-ninjas/himalaya-ui/blob/84a7de5ee37e1ebfc43c892461dba8518a27b9fc/src/components/utils/use-context-state/create-ui-context.tsx#L16-L16 | 84a7de5ee37e1ebfc43c892461dba8518a27b9fc |
dockge | github_2023 | louislam | typescript | AgentManager.add | async add(url : string, username : string, password : string) : Promise<Agent> {
let bean = R.dispense("agent") as Agent;
bean.url = url;
bean.username = username;
bean.password = password;
await R.store(bean);
return bean;
} | /**
*
* @param url
* @param username
* @param password
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/agent-manager.ts#L80-L87 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | AgentManager.remove | async remove(url : string) {
let bean = await R.findOne("agent", " url = ? ", [
url,
]);
if (bean) {
await R.trash(bean);
let endpoint = bean.endpoint;
this.disconnect(endpoint);
this.sendAgentList();
delete this.agentSocketList[endpoint];
} else {
throw new Error("Agent not found");
}
} | /**
*
* @param url
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/agent-manager.ts#L93-L107 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.readDBConfig | static readDBConfig() : DBConfig {
const dbConfigString = fs.readFileSync(path.join(this.server.config.dataDir, "db-config.json")).toString("utf-8");
const dbConfig = JSON.parse(dbConfigString);
if (typeof dbConfig !== "object") {
throw new Error("Invalid db-config.json, it must be an object");
}
if (typeof dbConfig.type !== "string") {
throw new Error("Invalid db-config.json, type must be a string");
}
return dbConfig;
} | /**
* Read the database config
* @throws {Error} If the config is invalid
* @typedef {string|undefined} envString
* @returns {{type: "sqlite"} | {type:envString, hostname:envString, port:envString, database:envString, username:envString, password:envString}} Database config
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L60-L72 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.writeDBConfig | static writeDBConfig(dbConfig : DBConfig) {
fs.writeFileSync(path.join(this.server.config.dataDir, "db-config.json"), JSON.stringify(dbConfig, null, 4));
} | /**
* @typedef {string|undefined} envString
* @param dbConfig the database configuration that should be written
* @returns {void}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L79-L81 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.connect | static async connect(autoloadModels = true) {
const acquireConnectionTimeout = 120 * 1000;
let dbConfig : DBConfig;
try {
dbConfig = this.readDBConfig();
Database.dbConfig = dbConfig;
} catch (err) {
if (err instanceof Error) {
log.warn("db", err.message);
}
dbConfig = {
type: "sqlite",
};
this.writeDBConfig(dbConfig);
}
let config = {};
log.info("db", `Database Type: ${dbConfig.type}`);
if (dbConfig.type === "sqlite") {
this.sqlitePath = path.join(this.server.config.dataDir, "dockge.db");
Dialect.prototype._driver = () => sqlite;
config = {
client: Dialect,
connection: {
filename: Database.sqlitePath,
acquireConnectionTimeout: acquireConnectionTimeout,
},
useNullAsDefault: true,
pool: {
min: 1,
max: 1,
idleTimeoutMillis: 120 * 1000,
propagateCreateError: false,
acquireTimeoutMillis: acquireConnectionTimeout,
}
};
} else {
throw new Error("Unknown Database type: " + dbConfig.type);
}
const knexInstance = knex(config);
// @ts-ignore
R.setup(knexInstance);
if (process.env.SQL_LOG === "1") {
R.debug(true);
}
// Auto map the model to a bean object
R.freeze(true);
if (autoloadModels) {
R.autoloadModels("./backend/models", "ts");
}
if (dbConfig.type === "sqlite") {
await this.initSQLite();
}
} | /**
* Connect to the database
* @param {boolean} autoloadModels Should models be automatically loaded?
* @param {boolean} noLog Should logs not be output?
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L89-L152 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.initSQLite | static async initSQLite() {
await R.exec("PRAGMA foreign_keys = ON");
// Change to WAL
await R.exec("PRAGMA journal_mode = WAL");
await R.exec("PRAGMA cache_size = -12000");
await R.exec("PRAGMA auto_vacuum = INCREMENTAL");
// This ensures that an operating system crash or power failure will not corrupt the database.
// FULL synchronous is very safe, but it is also slower.
// Read more: https://sqlite.org/pragma.html#pragma_synchronous
await R.exec("PRAGMA synchronous = NORMAL");
log.debug("db", "SQLite config:");
log.debug("db", await R.getAll("PRAGMA journal_mode"));
log.debug("db", await R.getAll("PRAGMA cache_size"));
log.debug("db", "SQLite Version: " + await R.getCell("SELECT sqlite_version()"));
} | /**
@returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L157-L173 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.patch | static async patch() {
// Using knex migrations
// https://knexjs.org/guide/migrations.html
// https://gist.github.com/NigelEarle/70db130cc040cc2868555b29a0278261
try {
await R.knex.migrate.latest({
directory: Database.knexMigrationsPath,
});
} catch (e) {
if (e instanceof Error) {
// Allow missing patch files for downgrade or testing pr.
if (e.message.includes("the following files are missing:")) {
log.warn("db", e.message);
log.warn("db", "Database migration failed, you may be downgrading Dockge.");
} else {
log.error("db", "Database migration failed");
throw e;
}
}
}
} | /**
* Patch the database
* @returns {void}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L179-L199 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.close | static async close() {
const listener = () => {
Database.noReject = false;
};
process.addListener("unhandledRejection", listener);
log.info("db", "Closing the database");
// Flush WAL to main database
if (Database.dbConfig.type === "sqlite") {
await R.exec("PRAGMA wal_checkpoint(TRUNCATE)");
}
while (true) {
Database.noReject = true;
await R.close();
await sleep(2000);
if (Database.noReject) {
break;
} else {
log.info("db", "Waiting to close the database");
}
}
log.info("db", "Database closed");
process.removeListener("unhandledRejection", listener);
} | /**
* Special handle, because tarn.js throw a promise reject that cannot be caught
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L205-L232 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.getSize | static getSize() {
if (Database.dbConfig.type === "sqlite") {
log.debug("db", "Database.getSize()");
const stats = fs.statSync(Database.sqlitePath);
log.debug("db", stats);
return stats.size;
}
return 0;
} | /**
* Get the size of the database (SQLite only)
* @returns {number} Size of database
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L238-L246 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | Database.shrink | static async shrink() {
if (Database.dbConfig.type === "sqlite") {
await R.exec("VACUUM");
}
} | /**
* Shrink the database
* @returns {Promise<void>}
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/database.ts#L252-L256 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.constructor | constructor() {
// Catch unexpected errors here
let unexpectedErrorHandler = (error : unknown) => {
console.trace(error);
console.error("If you keep encountering errors, please report to https://github.com/louislam/dockge");
};
process.addListener("unhandledRejection", unexpectedErrorHandler);
process.addListener("uncaughtException", unexpectedErrorHandler);
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = "production";
}
// Log NODE ENV
log.info("server", "NODE_ENV: " + process.env.NODE_ENV);
// Default stacks directory
let defaultStacksDir;
if (process.platform === "win32") {
defaultStacksDir = "./stacks";
} else {
defaultStacksDir = "/opt/stacks";
}
// Define all possible arguments
let args = parse<Arguments>({
sslKey: {
type: String,
optional: true,
},
sslCert: {
type: String,
optional: true,
},
sslKeyPassphrase: {
type: String,
optional: true,
},
port: {
type: Number,
optional: true,
},
hostname: {
type: String,
optional: true,
},
dataDir: {
type: String,
optional: true,
},
stacksDir: {
type: String,
optional: true,
}
});
this.config = args as Config;
// Load from environment variables or default values if args are not set
this.config.sslKey = args.sslKey || process.env.DOCKGE_SSL_KEY || undefined;
this.config.sslCert = args.sslCert || process.env.DOCKGE_SSL_CERT || undefined;
this.config.sslKeyPassphrase = args.sslKeyPassphrase || process.env.DOCKGE_SSL_KEY_PASSPHRASE || undefined;
this.config.port = args.port || Number(process.env.DOCKGE_PORT) || 5001;
this.config.hostname = args.hostname || process.env.DOCKGE_HOSTNAME || undefined;
this.config.dataDir = args.dataDir || process.env.DOCKGE_DATA_DIR || "./data/";
this.config.stacksDir = args.stacksDir || process.env.DOCKGE_STACKS_DIR || defaultStacksDir;
this.stacksDir = this.config.stacksDir;
log.debug("server", this.config);
this.packageJSON = packageJSON as PackageJson;
try {
this.indexHTML = fs.readFileSync("./frontend-dist/index.html").toString();
} catch (e) {
// "dist/index.html" is not necessary for development
if (process.env.NODE_ENV !== "development") {
log.error("server", "Error: Cannot find 'frontend-dist/index.html', did you install correctly?");
process.exit(1);
}
}
// Create express
this.app = express();
// Create HTTP server
if (this.config.sslKey && this.config.sslCert) {
log.info("server", "Server Type: HTTPS");
this.httpServer = https.createServer({
key: fs.readFileSync(this.config.sslKey),
cert: fs.readFileSync(this.config.sslCert),
passphrase: this.config.sslKeyPassphrase,
}, this.app);
} else {
log.info("server", "Server Type: HTTP");
this.httpServer = http.createServer(this.app);
}
// Binding Routers
for (const router of this.routerList) {
this.app.use(router.create(this.app, this));
}
// Static files
this.app.use("/", expressStaticGzip("frontend-dist", {
enableBrotli: true,
}));
// Universal Route Handler, must be at the end of all express routes.
this.app.get("*", async (_request, response) => {
response.send(this.indexHTML);
});
// Allow all CORS origins in development
let cors = undefined;
if (isDev) {
cors = {
origin: "*",
};
}
// Create Socket.io
this.io = new socketIO.Server(this.httpServer, {
cors,
allowRequest: (req, callback) => {
let isOriginValid = true;
const bypass = isDev || process.env.UPTIME_KUMA_WS_ORIGIN_CHECK === "bypass";
if (!bypass) {
let host = req.headers.host;
// If this is set, it means the request is from the browser
let origin = req.headers.origin;
// If this is from the browser, check if the origin is allowed
if (origin) {
try {
let originURL = new URL(origin);
if (host !== originURL.host) {
isOriginValid = false;
log.error("auth", `Origin (${origin}) does not match host (${host}), IP: ${req.socket.remoteAddress}`);
}
} catch (e) {
// Invalid origin url, probably not from browser
isOriginValid = false;
log.error("auth", `Invalid origin url (${origin}), IP: ${req.socket.remoteAddress}`);
}
} else {
log.info("auth", `Origin is not set, IP: ${req.socket.remoteAddress}`);
}
} else {
log.debug("auth", "Origin check is bypassed");
}
callback(null, isOriginValid);
}
});
this.io.on("connection", async (socket: Socket) => {
let dockgeSocket = socket as DockgeSocket;
dockgeSocket.instanceManager = new AgentManager(dockgeSocket);
dockgeSocket.emitAgent = (event : string, ...args : unknown[]) => {
let obj = args[0];
if (typeof(obj) === "object") {
let obj2 = obj as LooseObject;
obj2.endpoint = dockgeSocket.endpoint;
}
dockgeSocket.emit("agent", event, ...args);
};
if (typeof(socket.request.headers.endpoint) === "string") {
dockgeSocket.endpoint = socket.request.headers.endpoint;
} else {
dockgeSocket.endpoint = "";
}
if (dockgeSocket.endpoint) {
log.info("server", "Socket connected (agent), as endpoint " + dockgeSocket.endpoint);
} else {
log.info("server", "Socket connected (direct)");
}
this.sendInfo(dockgeSocket, true);
if (this.needSetup) {
log.info("server", "Redirect to setup page");
dockgeSocket.emit("setup");
}
// Create socket handlers (original, no agent support)
for (const socketHandler of this.socketHandlerList) {
socketHandler.create(dockgeSocket, this);
}
// Create Agent Socket
let agentSocket = new AgentSocket();
// Create agent socket handlers
for (const socketHandler of this.agentSocketHandlerList) {
socketHandler.create(dockgeSocket, this, agentSocket);
}
// Create agent proxy socket handlers
this.agentProxySocketHandler.create2(dockgeSocket, this, agentSocket);
// ***************************
// Better do anything after added all socket handlers here
// ***************************
log.debug("auth", "check auto login");
if (await Settings.get("disableAuth")) {
log.info("auth", "Disabled Auth: auto login to admin");
this.afterLogin(dockgeSocket, await R.findOne("user") as User);
dockgeSocket.emit("autoLogin");
} else {
log.debug("auth", "need auth");
}
// Socket disconnect
dockgeSocket.on("disconnect", () => {
log.info("server", "Socket disconnected!");
dockgeSocket.instanceManager.disconnectAll();
});
});
this.io.on("disconnect", () => {
});
if (isDev) {
setInterval(() => {
log.debug("terminal", "Terminal count: " + Terminal.getTerminalCount());
}, 5000);
}
} | /**
*
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L86-L322 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | unexpectedErrorHandler | let unexpectedErrorHandler = (error : unknown) => {
console.trace(error);
console.error("If you keep encountering errors, please report to https://github.com/louislam/dockge");
}; | // Catch unexpected errors here | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L88-L91 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.serve | async serve() {
// Create all the necessary directories
this.initDataDir();
// Connect to database
try {
await Database.init(this);
} catch (e) {
if (e instanceof Error) {
log.error("server", "Failed to prepare your database: " + e.message);
}
process.exit(1);
}
// First time setup if needed
let jwtSecretBean = await R.findOne("setting", " `key` = ? ", [
"jwtSecret",
]);
if (! jwtSecretBean) {
log.info("server", "JWT secret is not found, generate one.");
jwtSecretBean = await this.initJWTSecret();
log.info("server", "Stored JWT secret into database");
} else {
log.debug("server", "Load JWT secret from database.");
}
this.jwtSecret = jwtSecretBean.value;
const userCount = (await R.knex("user").count("id as count").first()).count;
log.debug("server", "User count: " + userCount);
// If there is no record in user table, it is a new Dockge instance, need to setup
if (userCount == 0) {
log.info("server", "No user, need setup");
this.needSetup = true;
}
// Listen
this.httpServer.listen(this.config.port, this.config.hostname, () => {
if (this.config.hostname) {
log.info( "server", `Listening on ${this.config.hostname}:${this.config.port}`);
} else {
log.info("server", `Listening on ${this.config.port}`);
}
// Run every 10 seconds
Cron("*/10 * * * * *", {
protect: true, // Enabled over-run protection.
}, () => {
//log.debug("server", "Cron job running");
this.sendStackList(true);
});
checkVersion.startInterval();
});
gracefulShutdown(this.httpServer, {
signals: "SIGINT SIGTERM",
timeout: 30000, // timeout: 30 secs
development: false, // not in dev mode
forceExit: true, // triggers process.exit() at the end of shutdown process
onShutdown: this.shutdownFunction, // shutdown function (async) - e.g. for cleanup DB, ...
finally: this.finalFunction, // finally function (sync) - e.g. for logging
});
} | /**
*
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L345-L412 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.sendInfo | async sendInfo(socket : Socket, hideVersion = false) {
let versionProperty;
let latestVersionProperty;
let isContainer;
if (!hideVersion) {
versionProperty = packageJSON.version;
latestVersionProperty = checkVersion.latestVersion;
isContainer = (process.env.DOCKGE_IS_CONTAINER === "1");
}
socket.emit("info", {
version: versionProperty,
latestVersion: latestVersionProperty,
isContainer,
primaryHostname: await Settings.get("primaryHostname"),
//serverTimezone: await this.getTimezone(),
//serverTimezoneOffset: this.getTimezoneOffset(),
});
} | /**
* Emits the version information to the client.
* @param socket Socket.io socket instance
* @param hideVersion Should we hide the version information in the response?
* @returns
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L420-L439 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.getClientIP | async getClientIP(socket : Socket) : Promise<string> {
let clientIP = socket.client.conn.remoteAddress;
if (clientIP === undefined) {
clientIP = "";
}
if (await Settings.get("trustProxy")) {
const forwardedFor = socket.client.conn.request.headers["x-forwarded-for"];
if (typeof forwardedFor === "string") {
return forwardedFor.split(",")[0].trim();
} else if (typeof socket.client.conn.request.headers["x-real-ip"] === "string") {
return socket.client.conn.request.headers["x-real-ip"];
}
}
return clientIP.replace(/^::ffff:/, "");
} | /**
* Get the IP of the client connected to the socket
* @param {Socket} socket Socket to query
* @returns IP of client
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L446-L463 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.getTimezone | async getTimezone() {
// From process.env.TZ
try {
if (process.env.TZ) {
this.checkTimezone(process.env.TZ);
return process.env.TZ;
}
} catch (e) {
if (e instanceof Error) {
log.warn("timezone", e.message + " in process.env.TZ");
}
}
const timezone = await Settings.get("serverTimezone");
// From Settings
try {
log.debug("timezone", "Using timezone from settings: " + timezone);
if (timezone) {
this.checkTimezone(timezone);
return timezone;
}
} catch (e) {
if (e instanceof Error) {
log.warn("timezone", e.message + " in settings");
}
}
// Guess
try {
const guess = dayjs.tz.guess();
log.debug("timezone", "Guessing timezone: " + guess);
if (guess) {
this.checkTimezone(guess);
return guess;
} else {
return "UTC";
}
} catch (e) {
// Guess failed, fall back to UTC
log.debug("timezone", "Guessed an invalid timezone. Use UTC as fallback");
return "UTC";
}
} | /**
* Attempt to get the current server timezone
* If this fails, fall back to environment variables and then make a
* guess.
* @returns {Promise<string>} Current timezone
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L471-L514 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.getTimezoneOffset | getTimezoneOffset() {
return dayjs().format("Z");
} | /**
* Get the current offset
* @returns {string} Time offset
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L520-L522 | d451e06e8428f1bf987595bf51d65f82241294cd |
dockge | github_2023 | louislam | typescript | DockgeServer.checkTimezone | checkTimezone(timezone : string) {
try {
dayjs.utc("2013-11-18 11:55").tz(timezone).format();
} catch (e) {
throw new Error("Invalid timezone:" + timezone);
}
} | /**
* Throw an error if the timezone is invalid
* @param {string} timezone Timezone to test
* @returns {void}
* @throws The timezone is invalid
*/ | https://github.com/louislam/dockge/blob/d451e06e8428f1bf987595bf51d65f82241294cd/backend/dockge-server.ts#L530-L536 | d451e06e8428f1bf987595bf51d65f82241294cd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.