repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
javavscode | github_2023 | oracle | typescript | URI.file | static file(path: string): URI {
let authority = _empty;
// normalize to fwd-slashes on windows,
// on other systems bwd-slashes are valid
// filename character, eg /f\oo/ba\r.txt
if (isWindows) {
path = path.replace(/\\/g, _slash);
}
// check for authority as used in UNC shares
// or use the path as given
if (path[0] === _slash && path[1] === _slash) {
const idx = path.indexOf(_slash, 2);
if (idx === -1) {
authority = path.substring(2);
path = _slash;
} else {
authority = path.substring(2, idx);
path = path.substring(idx) || _slash;
}
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return new _URI('file', authority, path, _empty, _empty);
} | /**
* Creates a new URI from a file system path, e.g. `c:\my\files`,
* `/usr/home`, or `\\server\share\some\path`.
*
* The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
* as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
* `URI.parse('file://' + path)` because the path might contain characters that are
* interpreted (# and ?). See the following sample:
* ```ts
const good = URI.file('/coding/c#/project1');
good.scheme === 'file';
good.path === '/coding/c#/project1';
good.fragment === '';
const bad = URI.parse('file://' + '/coding/c#/project1');
bad.scheme === 'file';
bad.path === '/coding/c'; // path is now broken
bad.fragment === '/project1';
```
*
* @param path A file system path (see `URI#fsPath`)
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L379-L404 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | URI.toString | toString(skipEncoding = false): string {
return _asFormatted(this, skipEncoding);
} | /**
* Creates a string representation for this URI. It's guaranteed that calling
* `URI.parse` with the result of this function creates an URI which is equal
* to this URI.
*
* * The result shall *not* be used for display purposes but for externalization or transport.
* * The result will be encoded using the percentage encoding and encoding happens mostly
* ignore the scheme-specific encoding rules.
*
* @param skipEncoding Do not encode the result, default is `false`
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L436-L438 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | _makeFsPath | function _makeFsPath(uri: URI): string {
let value: string;
if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
// unc path: file://shares/c$/far/boo
value = `//${uri.authority}${uri.path}`;
} else if (
uri.path.charCodeAt(0) === CharCode.Slash &&
((uri.path.charCodeAt(1) >= CharCode.A && uri.path.charCodeAt(1) <= CharCode.Z) ||
(uri.path.charCodeAt(1) >= CharCode.a && uri.path.charCodeAt(1) <= CharCode.z)) &&
uri.path.charCodeAt(2) === CharCode.Colon
) {
// windows drive letter: file:///c:/far/boo
value = uri.path[1].toLowerCase() + uri.path.substr(2);
} else {
// other path
value = uri.path;
}
if (isWindows) {
value = value.replace(/\//g, '\\');
}
return value;
} | /**
* Compute `fsPath` for the given uri
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L666-L687 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | _asFormatted | function _asFormatted(uri: URI, skipEncoding: boolean): string {
const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal;
let res = '';
let { authority, path } = uri;
const { scheme, query, fragment } = uri;
if (scheme) {
res += scheme;
res += ':';
}
if (authority || scheme === 'file') {
res += _slash;
res += _slash;
}
if (authority) {
let idx = authority.indexOf('@');
if (idx !== -1) {
// <user>@<auth>
const userinfo = authority.substr(0, idx);
authority = authority.substr(idx + 1);
idx = userinfo.indexOf(':');
if (idx === -1) {
res += encoder(userinfo, false);
} else {
// <user>:<pass>@<auth>
res += encoder(userinfo.substr(0, idx), false);
res += ':';
res += encoder(userinfo.substr(idx + 1), false);
}
res += '@';
}
authority = authority.toLowerCase();
idx = authority.indexOf(':');
if (idx === -1) {
res += encoder(authority, false);
} else {
// <auth>:<port>
res += encoder(authority.substr(0, idx), false);
res += authority.substr(idx);
}
}
if (path) {
// lower-case windows drive letters in /C:/fff or C:/fff
if (path.length >= 3 && path.charCodeAt(0) === CharCode.Slash && path.charCodeAt(2) === CharCode.Colon) {
const code = path.charCodeAt(1);
if (code >= CharCode.A && code <= CharCode.Z) {
path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3
}
} else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) {
const code = path.charCodeAt(0);
if (code >= CharCode.A && code <= CharCode.Z) {
path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3
}
}
// encode the rest of the path
res += encoder(path, true);
}
if (query) {
res += '?';
res += encoder(query, false);
}
if (fragment) {
res += '#';
res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
}
return res;
} | /**
* Create the external version of a uri
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L692-L758 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | TreeViewService.fetchImageUri | async fetchImageUri(nodeData: NodeInfoRequest.Data): Promise<vscode.Uri | string | ThemeIcon | undefined> {
let res: vscode.Uri | string | ThemeIcon | undefined = this.imageUri(nodeData);
if (res) {
return res;
}
if (!nodeData?.iconDescriptor) {
return undefined;
}
let ci: CachedImage | undefined;
ci = this.images.get(nodeData.iconDescriptor.baseUri);
if (ci != null) {
return ci?.iconUri;
}
const p: GetResourceParams = {
acceptEncoding: ['base64'],
uri: nodeData.iconDescriptor.baseUri
};
let iconData = await this.client.sendRequest(NodeInfoRequest.getresource, p);
if (!iconData?.content) {
return undefined;
}
let iconString = `data: ${iconData.contentType || 'image/png'};${iconData.encoding || 'base64'},${iconData.content}`;
ci = new CachedImage(nodeData.iconDescriptor.baseUri, vscode.Uri.parse(iconString), undefined);
this.images.set(nodeData.iconDescriptor.baseUri, ci);
return ci.iconUri;
} | /**
* Requests an image data from the LSP server.
* @param nodeData
* @returns icon specification or undefined
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/views/projects.ts#L242-L268 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | VisualizerProvider.wrap | async wrap<X>(fn: (pending: Visualizer[]) => Thenable<X>): Promise<X> {
let arr: Visualizer[] = [];
try {
return await fn(arr);
} finally {
this.releaseVisualizersAndFire(arr);
}
} | /**
* Wraps code that queries individual Visualizers so that blocked changes are fired after
* the code terminated.
*
* Usage:
* wrap(() => { ... code ... ; queryVisualizer(vis, () => { ... })});
* @param fn the code to execute
* @returns value of the code function
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/views/projects.ts#L568-L575 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | VisualizerProvider.visualizerList | private visualizerList(arr: Visualizer[]): string {
let s = "";
for (let v of arr) {
s += v.idstring() + " ";
}
return s;
} | /**
* Just creates a string list from visualizer IDs. Diagnostics only.
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/views/projects.ts#L580-L586 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | VisualizerProvider.releaseVisualizersAndFire | private releaseVisualizersAndFire(list: Visualizer[] | undefined) {
if (!list) {
list = Array.from(this.delayedFire);
}
if (doLog) {
this.log.appendLine(`Done with ${this.visualizerList(list)}`);
}
// v can be in list several times, each push increased its counter, so we need to decrease it.
for (let v of list) {
if (this.treeData?.get(Number(v.id || -1)) === v) {
if (--v.pendingQueries) {
if (doLog) {
this.log.appendLine(`${v.idstring()} has pending ${v.pendingQueries} queries`);
}
continue;
}
if (v.pendingChange) {
if (doLog) {
this.log.appendLine(`Fire delayed change on ${v.idstring()}`);
}
this.fireItemChange(v);
v.pendingChange = false;
}
}
this.delayedFire.delete(v);
}
if (doLog) {
this.log.appendLine("Pending queue: " + this.visualizerList(Array.from(this.delayedFire)));
this.log.appendLine("---------------");
}
} | /**
* Do not use directly, use wrap(). Fires delayed events for visualizers that have no pending queries.
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/views/projects.ts#L591-L621 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | VisualizerProvider.queryVisualizer | async queryVisualizer<X>(element: Visualizer | undefined, pending: Visualizer[], fn: () => Promise<X>): Promise<X> {
if (!element) {
return fn();
}
this.delayedFire.add(element);
pending.push(element);
element.pendingQueries++;
if (doLog) {
this.log.appendLine(`Delaying visualizer ${element.idstring()}, queries = ${element.pendingQueries}`)
}
return fn();
} | /**
* Should wrap calls to NBLS for individual visualizers (info, children). Puts visualizer on the delayed fire list.
* Must be itself wrapped in wrap() -- wrap(... queryVisualizer()).
* @param element visualizer to be queried, possibly undefined (new item is expected)
* @param fn code to execute
* @returns code's result
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/views/projects.ts#L630-L641 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
wanderlust | github_2023 | krishnaacharyaa | typescript | isRedisEnabled | function isRedisEnabled() {
return getRedisClient() !== null;
} | // Helper function to check if Redis is available | https://github.com/krishnaacharyaa/wanderlust/blob/778bec3cf698538839d39c6eb4c5643c3aa7d60d/backend/utils/cache-posts.ts#L5-L7 | 778bec3cf698538839d39c6eb4c5643c3aa7d60d |
text-to-cad-ui | github_2023 | KittyCAD | typescript | fromLocalStorage | function fromLocalStorage<T = unknown>(storageKey: string, fallbackValue: T) {
if (browser) {
const storedValue = window.localStorage.getItem(storageKey)
if (storedValue !== 'undefined' && storedValue !== null) {
return typeof fallbackValue === 'object' ? JSON.parse(storedValue) : storedValue
}
}
return fallbackValue
} | // Get value from localStorage if in browser and the value is stored, otherwise fallback | https://github.com/KittyCAD/text-to-cad-ui/blob/d9aeac11f79fbb8332fdfddc82bff5509190827b/src/lib/stores.ts#L90-L100 | d9aeac11f79fbb8332fdfddc82bff5509190827b |
text-to-cad-ui | github_2023 | KittyCAD | typescript | signOut | function signOut() {
cookies.delete(AUTH_COOKIE_NAME, { domain: DOMAIN, path: '/' })
throw redirect(303, '/')
} | /**
* Shared sign out function
*/ | https://github.com/KittyCAD/text-to-cad-ui/blob/d9aeac11f79fbb8332fdfddc82bff5509190827b/src/routes/(sidebarLayout)/+layout.server.ts#L58-L61 | d9aeac11f79fbb8332fdfddc82bff5509190827b |
wxlivespy | github_2023 | fire4nt | typescript | WXDataDecoder.decodeDataFromResponse | static decodeDataFromResponse(
requestHeaders: Record<string, string>,
requestData: any,
responseData: any,
): DecodedData | null {
const decodedMessages = {} as DecodedData;
decodedMessages.host_info = {} as HostInfo;
decodedMessages.host_info.wechat_uin = requestHeaders['x-wechat-uin'];
decodedMessages.host_info.finder_username = requestData.finderUsername;
// 可能出现 responseData.data.liveInfo 为 undefined 的情况
if (responseData.data.liveInfo === undefined) {
if (responseData.data.msgList.length === 0 && responseData.data.appMsgList.length === 0) {
return null;
}
throw new Error('liveInfo is undefined, but msgList or appMsgList is not empty');
}
decodedMessages.live_info = WXDataDecoder.liveInfoFromObject(responseData.data.liveInfo, decodedMessages.host_info);
decodedMessages.events = responseData.data.msgList.reduce((acc: LiveMessage[], o: any) => {
acc.push(WXDataDecoder.liveMessageFromMsg(o));
// todo save message to log file.
// saveData(o, gm, config.log_path);
return acc;
}, []);
decodedMessages.events = responseData.data.appMsgList.reduce((acc: LiveMessage[], o: any) => {
const gm = WXDataDecoder.liveMessageFromAppMsg(o);
const decodedPayload = Buffer.from(o.payload, 'base64').toString();
const giftPayload = JSON.parse(decodedPayload);
o.payload = giftPayload;
acc.push(gm);
// todo save message to log file.
// saveData(o, gm, config.log_path);
return acc;
}, decodedMessages.events);
return decodedMessages;
} | // } | https://github.com/fire4nt/wxlivespy/blob/10351334a5dd48f7e9cd06482cf91fde066176a6/src/main/WXDataDecoder.ts#L126-L163 | 10351334a5dd48f7e9cd06482cf91fde066176a6 |
wxlivespy | github_2023 | fire4nt | typescript | SpyConfig.getProp | public getProp<K extends keyof ConfigProps>(key: K): ConfigProps[K] {
return this.config[key];
} | // Step 2: Implement generic getProp and setProp methods | https://github.com/fire4nt/wxlivespy/blob/10351334a5dd48f7e9cd06482cf91fde066176a6/src/main/config.ts#L51-L53 | 10351334a5dd48f7e9cd06482cf91fde066176a6 |
wxlivespy | github_2023 | fire4nt | typescript | getForwardURL | const getForwardURL = async () => {
const url = await window.electron.ipcRenderer.getForwardUrl();
// setFormData(configFromMain);
setForwardURL(url);
}; | // Fetch config from main process when component is mounted | https://github.com/fire4nt/wxlivespy/blob/10351334a5dd48f7e9cd06482cf91fde066176a6/src/renderer/EventPanel.tsx#L24-L28 | 10351334a5dd48f7e9cd06482cf91fde066176a6 |
wxlivespy | github_2023 | fire4nt | typescript | getLiveStatusURL | const getLiveStatusURL = async () => {
const httpServerPort = await window.electron.ipcRenderer.getConfig('http_server_port');
liveStatusUrl = `http://localhost:${httpServerPort}/getLiveStatus`;
log.info(liveStatusUrl);
}; | // window.electron.ipcRenderer.once('wxlive-status', (arg) => { | https://github.com/fire4nt/wxlivespy/blob/10351334a5dd48f7e9cd06482cf91fde066176a6/src/renderer/StatusPanel.tsx#L42-L46 | 10351334a5dd48f7e9cd06482cf91fde066176a6 |
citrineos-core | github_2023 | citrineos | typescript | findCaseInsensitiveMatch | function findCaseInsensitiveMatch<T>(
obj: Record<string, T>,
targetKey: string,
): string | undefined {
const lowerTargetKey = targetKey.toLowerCase();
return Object.keys(obj).find((key) => key.toLowerCase() === lowerTargetKey);
} | /**
* Finds a case-insensitive match for a key in an object.
* @param obj The object to search.
* @param targetKey The target key.
* @returns The matching key or undefined.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/config/defineConfig.ts#L21-L27 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | mergeConfigFromEnvVars | function mergeConfigFromEnvVars<T extends Record<string, any>>(
defaultConfig: T,
envVars: NodeJS.ProcessEnv,
configKeyMap: Record<string, any>,
): T {
const config: T = { ...defaultConfig };
for (const [fullEnvKey, value] of Object.entries(envVars)) {
if (!value) {
continue;
}
const lowercaseEnvKey = fullEnvKey.toLowerCase();
if (lowercaseEnvKey.startsWith(CITRINE_ENV_VAR_PREFIX)) {
const envKeyWithoutPrefix = lowercaseEnvKey.substring(
CITRINE_ENV_VAR_PREFIX.length,
);
const path = envKeyWithoutPrefix.split('_');
let currentConfigPart: Record<string, any> = config;
let currentConfigKeyMap: Record<string, any> = configKeyMap;
for (let i = 0; i < path.length - 1; i++) {
const part = path[i];
const matchingKey = findCaseInsensitiveMatch(currentConfigKeyMap, part);
if (matchingKey && typeof currentConfigPart[matchingKey] === 'object') {
currentConfigPart = currentConfigPart[matchingKey];
currentConfigKeyMap = currentConfigKeyMap[matchingKey];
} else {
currentConfigPart[part] = {};
currentConfigPart = currentConfigPart[part];
currentConfigKeyMap = currentConfigKeyMap[part];
}
}
const finalPart = path[path.length - 1];
const keyToUse =
currentConfigKeyMap[finalPart.toLowerCase()] || finalPart;
try {
currentConfigPart[keyToUse] = JSON.parse(value as string);
} catch {
console.debug(
`Mapping '${value}' as string for environment variable '${fullEnvKey}'`,
);
currentConfigPart[keyToUse] = value;
}
}
}
return config as T;
} | /**
* Merges configuration from environment variables into the default configuration. Allows any to keep it as generic as possible.
* @param defaultConfig The default configuration.
* @param envVars The environment variables.
* @returns The merged configuration.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/config/defineConfig.ts#L70-L120 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | validateFinalConfig | function validateFinalConfig(finalConfig: SystemConfigInput) {
if (!finalConfig.data.sequelize.username) {
throw new Error(
'CITRINEOS_DATA_SEQUELIZE_USERNAME must be set if username not provided in config',
);
}
if (!finalConfig.data.sequelize.password) {
throw new Error(
'CITRINEOS_DATA_SEQUELIZE_PASSWORD must be set if password not provided in config',
);
}
} | /**
* Validates the system configuration to ensure required properties are set.
* @param finalConfig The final system configuration.
* @throws Error if required properties are not set.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/config/defineConfig.ts#L127-L138 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | _handler | const _handler = async (
request: FastifyRequest<{
Body: OcppRequest;
Querystring: Record<string, any>;
}>,
): Promise<IMessageConfirmation> => {
const { identifier, tenantId, callbackUrl, ...extraQueries } =
request.query;
return method.call(
this,
identifier,
tenantId,
request.body,
callbackUrl,
Object.keys(extraQueries).length > 0 ? extraQueries : undefined,
);
}; | /**
* Executes the handler function for the given request.
*
* @param {FastifyRequest<{ Body: OcppRequest, Querystring: IMessageQuerystring }>} request - The request object containing the body and querystring.
* @return {Promise<IMessageConfirmation>} The promise that resolves to the message confirmation.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/interfaces/api/AbstractModuleApi.ts#L132-L148 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | _handler | const _handler = async (
request: FastifyRequest<{
Body: object;
Querystring: object;
}>,
reply: FastifyReply,
): Promise<unknown> =>
(
method.call(this, request, reply) as Promise<
undefined | string | object
>
).catch((err) => {
// TODO: figure out better error codes & messages
this._logger.error('Error in handling data route', err);
const statusCode = err.statusCode ? err.statusCode : 500;
reply.status(statusCode).send(err);
}); | /**
* Handles the request and returns a Promise resolving to an object.
*
* @param {FastifyRequest<{ Body: object, Querystring: object }>} request - the request object
* @param {FastifyReply} reply - the reply object
* @return {Promise<any>} - a Promise resolving to an object
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/interfaces/api/AbstractModuleApi.ts#L242-L258 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | cleanSchema | const cleanSchema = (obj: any) => {
if (typeof obj !== 'object' || obj === null) return;
// Remove specific unknown keys
for (const unknownKey of ['comment', 'javaType', 'tsEnumNames']) {
if (unknownKey in obj) {
delete obj[unknownKey];
}
}
// Remove `additionalItems` if `items` is not an array
if (
'items' in obj &&
!Array.isArray(obj.items) &&
'additionalItems' in obj
) {
delete obj.additionalItems;
}
// Remove `additionalProperties` if `type` is not "object"
if ('additionalProperties' in obj && obj.type !== 'object') {
delete obj.additionalProperties;
}
// Recursively process nested objects
for (const key in obj) {
if (typeof obj[key] === 'object') {
cleanSchema(obj[key]);
}
}
}; | // Use structuredClone for a true deep copy | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/interfaces/api/AbstractModuleApi.ts#L394-L424 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Message.constructor | constructor(
origin: MessageOrigin,
eventGroup: EventGroup,
action: CallAction,
state: MessageState,
context: IMessageContext,
payload: T,
) {
this._origin = origin;
this._eventGroup = eventGroup;
this._action = action;
this._state = state;
this._context = context;
this._payload = payload;
} | /**
* Constructs a new instance of Message.
*
* @param {MessageOrigin} origin - The origin of the message.
* @param {EventGroup} eventGroup - The event group of the message.
* @param {CallAction} action - The action of the message.
* @param {MessageState} state - The state of the message.
* @param {IMessageContext} context - The context of the message.
* @param {T} payload - The payload of the message.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/interfaces/messages/Message.ts#L68-L82 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Message.origin | get origin(): MessageOrigin {
return this._origin;
} | /**
* Getter & Setter
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/interfaces/messages/Message.ts#L87-L89 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Money.roundToCurrencyScale | roundToCurrencyScale(): Money {
const newAmount = this._amount.round(
this.currency.scale,
0, // RoundDown
);
return this.withAmount(newAmount);
} | /**
* Rounds the amount down to match the currency's defined scale.
* This method could be used when converting an amount to its final monetary value.
*
* @returns {Money} A new Money instance with the amount rounded down to the currency's scale.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/money/Money.ts#L50-L56 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | MeterValueUtils.getTotalKwh | public static getTotalKwh(meterValues: MeterValueType[]): number {
const filteredValues = this.filterValidMeterValues(meterValues);
const timestampToKwhMap = this.getTimestampToKwhMap(filteredValues);
const sortedValues =
this.getSortedKwhByTimestampAscending(timestampToKwhMap);
return this.calculateTotalKwh(sortedValues);
} | /**
* Calculate the total Kwh
*
* @param {array} meterValues - meterValues of a transaction.
* @return {number} total Kwh based on the overall values (i.e., without phase) in the simpledValues.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/00_Base/src/util/MeterValueUtils.ts#L21-L27 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | TlsCertificatesRequest.constructor | constructor(certificateChain: string[], privateKey: string, rootCA?: string, subCAKey?: string) {
this.certificateChain = certificateChain;
this.privateKey = privateKey;
this.rootCA = rootCA;
this.subCAKey = subCAKey;
} | // file id for the private key of sub CA for signing charging station certificate | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/interfaces/dtos/TlsCertificatesRequest.ts#L12-L17 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeAuthorizationRepository._updateIdToken | private async _updateIdToken(value: IdTokenType, transaction?: Transaction): Promise<IdToken> {
const [savedIdTokenModel] = await IdToken.findOrCreate({
where: { idToken: value.idToken, type: value.type },
transaction,
});
const additionalInfoIds: number[] = [];
// Create any additionalInfos that don't exist,
// and any relations between them and the IdToken that don't exist
if (value.additionalInfo) {
for (const valueAdditionalInfo of value.additionalInfo) {
const [savedAdditionalInfo] = await AdditionalInfo.findOrCreate({
where: {
additionalIdToken: valueAdditionalInfo.additionalIdToken,
type: valueAdditionalInfo.type,
},
transaction,
});
await IdTokenAdditionalInfo.findOrCreate({
where: {
idTokenId: savedIdTokenModel.id,
additionalInfoId: savedAdditionalInfo.id,
},
transaction,
});
additionalInfoIds.push(savedAdditionalInfo.id);
}
}
// Remove all associations between idToken and additionalInfo that no longer exist
await IdTokenAdditionalInfo.destroy({
where: {
idTokenId: savedIdTokenModel.id,
additionalInfoId: { [Op.notIn]: additionalInfoIds },
},
transaction,
});
return savedIdTokenModel.reload({ include: [AdditionalInfo], transaction });
} | /**
* Private Methods
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/Authorization.ts#L138-L179 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeBootRepository.manageSetVariables | private async manageSetVariables(setVariableIds: number[], stationId: string, bootConfigId: string): Promise<VariableAttribute[]> {
const managedSetVariables: VariableAttribute[] = [];
// Unassigns variables
await this.variableAttributes.updateAllByQuery(
{ bootConfigId: null },
{
where: {
stationId,
},
},
);
// Assigns variables, or throws an error if variable with id does not exist
for (const setVariableId of setVariableIds) {
const setVariable: VariableAttribute | undefined = await this.variableAttributes.updateByKey({ bootConfigId }, setVariableId.toString());
if (!setVariable) {
// When this is called from createOrUpdateByKey, this code should be impossible to reach
// Since the boot object would have already been upserted with the pendingBootSetVariableIds as foreign keys
// And if they were not valid foreign keys, it would have thrown an error
throw new Error('SetVariableId does not exist ' + setVariableId);
} else {
managedSetVariables.push(setVariable);
}
}
return managedSetVariables;
} | /**
* Private Methods
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/Boot.ts#L68-L92 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeDeviceModelRepository.createSetVariableDataType | private createSetVariableDataType(input: VariableAttribute): SetVariableDataType {
if (!input.value) {
throw new Error('Value must be present to generate SetVariableDataType from VariableAttribute');
} else {
return {
attributeType: input.type,
attributeValue: input.value,
component: {
...input.component,
},
variable: {
...input.variable,
},
};
}
} | /**
* Private Methods
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/DeviceModel.ts#L419-L434 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeSecurityEventRepository.generateTimestampQuery | private generateTimestampQuery(from?: string, to?: string): any {
if (!from && !to) {
return {};
}
if (!from && to) {
return { timestamp: { [Op.lte]: to } };
}
if (from && !to) {
return { timestamp: { [Op.gte]: from } };
}
return { timestamp: { [Op.between]: [from, to] } };
} | /**
* Private Methods
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/SecurityEvent.ts#L45-L56 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeSubscriptionRepository.create | create(value: Subscription): Promise<Subscription> {
const { ...rawSubscription } = value;
rawSubscription.id = null;
return super.create(Subscription.build({ ...rawSubscription }));
} | /**
* Creates a new {@link Subscription} in the database.
* Input is assumed to not have an id, and id will be removed if present.
* Object is rebuilt to ensure access to essential {@link Model} function {@link Model.save()} (Model is extended by Subscription).
*
* @param value {@link Subscription} object which may have been deserialized from JSON
* @returns Saved {@link Subscription} if successful, undefined otherwise
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/Subscription.ts#L25-L29 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeTransactionEventRepository.createOrUpdateTransactionByTransactionEventAndStationId | async createOrUpdateTransactionByTransactionEventAndStationId(value: TransactionEventRequest, stationId: string): Promise<Transaction> {
let evse: Evse | undefined;
if (value.evse) {
[evse] = await this.evse.readOrCreateByQuery({
where: {
id: value.evse.id,
connectorId: value.evse.connectorId ? value.evse.connectorId : null,
},
});
}
return await this.s.transaction(async (sequelizeTransaction) => {
let finalTransaction: Transaction;
let created = false;
const existingTransaction = await this.transaction.readOnlyOneByQuery({
where: {
stationId,
transactionId: value.transactionInfo.transactionId,
},
transaction: sequelizeTransaction,
});
if (existingTransaction) {
finalTransaction = await existingTransaction.update(
{
isActive: value.eventType !== TransactionEventEnumType.Ended,
...value.transactionInfo,
},
{
transaction: sequelizeTransaction,
},
);
} else {
const newTransaction = Transaction.build({
stationId,
isActive: value.eventType !== TransactionEventEnumType.Ended,
...(evse ? { evseDatabaseId: evse.databaseId } : {}),
...value.transactionInfo,
});
finalTransaction = await newTransaction.save({ transaction: sequelizeTransaction });
created = true;
}
const transactionDatabaseId = finalTransaction.id;
let event = TransactionEvent.build({
stationId,
transactionDatabaseId,
...value,
});
if (value.idToken && value.idToken.type !== IdTokenEnumType.NoAuthorization) {
// TODO: ensure that Authorization is passed into this method if idToken exists
// At this point, token MUST already be authorized and thus exist in the database
// It can be either the primary idToken of an Authorization or a group idToken
const idToken = await this.idToken.readOnlyOneByQuery({
where: {
idToken: value.idToken.idToken,
type: value.idToken.type,
},
transaction: sequelizeTransaction,
});
if (!idToken) {
// TODO: Log Warning...
// TODO: Save raw transaction event in TransactionEvent model
} else {
event.idTokenId = idToken.id;
}
}
event = await event.save({ transaction: sequelizeTransaction });
if (value.meterValue && value.meterValue.length > 0) {
await Promise.all(
value.meterValue.map(async (meterValue) => {
const savedMeterValue = await MeterValue.create(
{
transactionEventId: event.id,
transactionDatabaseId: transactionDatabaseId,
...meterValue,
},
{ transaction: sequelizeTransaction },
);
this.meterValue.emit('created', [savedMeterValue]);
}),
);
}
await event.reload({ include: [MeterValue], transaction: sequelizeTransaction });
this.emit('created', [event]);
const allMeterValues = await this.meterValue.readAllByQuery({
where: {
transactionDatabaseId,
},
});
await finalTransaction.update({ totalKwh: MeterValueUtils.getTotalKwh(allMeterValues) }, { transaction: sequelizeTransaction });
await finalTransaction.reload({
include: [{ model: TransactionEvent, as: Transaction.TRANSACTION_EVENTS_ALIAS, include: [IdToken] }, MeterValue, Evse],
transaction: sequelizeTransaction,
});
this.transaction.emit(created ? 'created' : 'updated', [finalTransaction]);
return finalTransaction;
});
} | /**
* @param value TransactionEventRequest received from charging station. Will be used to create TransactionEvent,
* MeterValues, and either create or update Transaction. IdTokens (and associated AdditionalInfo) and EVSEs are
* assumed to already exist and will not be created as part of this call.
*
* @param stationId StationId of charging station which sent TransactionEventRequest.
*
* @returns Saved TransactionEvent
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/TransactionEvent.ts#L48-L155 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SequelizeTransactionEventRepository.readAllTransactionsByStationIdAndEvseAndChargingStates | async readAllTransactionsByStationIdAndEvseAndChargingStates(stationId: string, evse?: EVSEType, chargingStates?: ChargingStateEnumType[] | undefined): Promise<Transaction[]> {
const includeObj = evse
? [
{
model: Evse,
where: { id: evse.id, connectorId: evse.connectorId ? evse.connectorId : null },
},
]
: [];
return await this.transaction
.readAllByQuery({
where: { stationId, ...(chargingStates ? { chargingState: { [Op.in]: chargingStates } } : {}) },
include: includeObj,
})
.then((row) => row as Transaction[]);
} | /**
* @param stationId StationId of the charging station where the transaction took place.
* @param evse Evse where the transaction took place.
* @param chargingStates Optional list of {@link ChargingStateEnumType}s the transactions must be in.
* If not present, will grab transactions regardless of charging state. If not present, will grab transactions
* without charging states, such as transactions started when a parking bay occupancy detector detects
* an EV (trigger reason "EVDetected")
*
* @returns List of transactions which meet the requirements.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/01_Data/src/layers/sequelize/repository/TransactionEvent.ts#L186-L201 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificateAuthorityService.getCertificateChain | async getCertificateChain(
csrString: string,
stationId: string,
certificateType?: CertificateSigningUseEnumType | null,
): Promise<string> {
this._logger.info(
`Getting certificate chain for certificateType: ${certificateType} and stationId: ${stationId}`,
);
switch (certificateType) {
case CertificateSigningUseEnumType.V2GCertificate: {
const signedCert = await this._v2gClient.getSignedCertificate(
extractEncodedContentFromCSR(csrString),
);
const caCerts = await this._v2gClient.getCACertificates();
return this._createCertificateChainWithoutRootCA(signedCert, caCerts);
}
case CertificateSigningUseEnumType.ChargingStationCertificate: {
return await this._chargingStationClient.getCertificateChain(csrString);
}
default: {
throw new Error(`Unsupported certificate type: ${certificateType}`);
}
}
} | /**
* Retrieves the certificate chain for V2G- and Charging Station certificates.
*
* @param {string} csrString - The Certificate Signing Request string.
* @param {string} stationId - The station identifier.
* @param {CertificateSigningUseEnumType} [certificateType] - The type of certificate to retrieve.
* @return {Promise<string>} The certificate chain without the root certificate.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/CertificateAuthority.ts#L69-L93 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificateAuthorityService.validateCertificateChainPem | public async validateCertificateChainPem(
certificateChainPem: string,
): Promise<AuthorizeCertificateStatusEnumType> {
const certificatePems: string[] =
parseCertificateChainPem(certificateChainPem);
this._logger.debug(
`Found ${certificatePems.length} certificates in chain.`,
);
if (certificatePems.length < 1) {
return AuthorizeCertificateStatusEnumType.NoCertificateAvailable;
}
try {
// Find the root certificate of the certificate chain
const rootCerts: string[] = await this._v2gClient.getRootCertificates();
const lastCertInChain = new X509();
lastCertInChain.readCertPEM(certificatePems[certificatePems.length - 1]);
let rootCertPem;
for (const rootCert of rootCerts) {
const root = new X509();
root.readCertPEM(rootCert);
if (
root.getSubjectString() === lastCertInChain.getIssuerString() &&
root.getExtSubjectKeyIdentifier().kid.hex ===
lastCertInChain.getExtAuthorityKeyIdentifier().kid.hex
) {
rootCertPem = rootCert;
break;
}
}
if (!rootCertPem) {
this._logger.error(
`Cannot find root certificate for certificate ${lastCertInChain}`,
);
return AuthorizeCertificateStatusEnumType.NoCertificateAvailable;
} else {
certificatePems.push(rootCertPem);
}
// OCSP validation for each certificate
for (let i = 0; i < certificatePems.length - 1; i++) {
const subjectCert = new X509();
subjectCert.readCertPEM(certificatePems[i]);
this._logger.debug(`Subject Certificate: ${subjectCert.getInfo()}`);
const notAfter = moment(subjectCert.getNotAfter(), dateTimeFormat);
if (notAfter.isBefore(moment())) {
return AuthorizeCertificateStatusEnumType.CertificateExpired;
}
const ocspUrls = subjectCert.getExtAIAInfo()?.ocsp;
if (ocspUrls && ocspUrls.length > 0) {
const ocspRequest = new OCSPRequest({
reqList: [
{
issuerCert: certificatePems[i + 1],
subjectCert: certificatePems[i],
},
],
});
this._logger.debug(`OCSP response URL: ${ocspUrls[0]}`);
const ocspResponse = KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo(
await sendOCSPRequest(ocspRequest, ocspUrls[0]),
);
const certStatus = ocspResponse.certStatus;
if (certStatus === 'revoked') {
return AuthorizeCertificateStatusEnumType.CertificateRevoked;
} else if (certStatus !== 'good') {
return AuthorizeCertificateStatusEnumType.NoCertificateAvailable;
}
} else {
this._logger.error(
`Certificate ${certificatePems[i]} has no OCSP URL.`,
);
return AuthorizeCertificateStatusEnumType.CertChainError;
}
}
} catch (error) {
this._logger.error(`Failed to validate certificate chain: ${error}`);
return AuthorizeCertificateStatusEnumType.NoCertificateAvailable;
}
return AuthorizeCertificateStatusEnumType.Accepted;
} | /*
* Validate the certificate chain using real time OCSP check.
*
* @param certificateChainPem - certificate chain pem
* @return AuthorizeCertificateStatusEnumType
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/CertificateAuthority.ts#L155-L239 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificateAuthorityService._createCertificateChainWithoutRootCA | private _createCertificateChainWithoutRootCA(
signedCert: string,
caCerts: string,
): string {
let certificateChain = '';
// Add Cert
const leafRaw = extractCertificateArrayFromEncodedString(signedCert)[0];
if (leafRaw) {
certificateChain += createPemBlock(
'CERTIFICATE',
Buffer.from(leafRaw.toSchema().toBER(false)).toString('base64'),
);
} else {
throw new Error(
`Cannot extract leaf certificate from the pem: ${signedCert}`,
);
}
// Add Chain without Root CA Certificate
const chainWithoutRoot = extractCertificateArrayFromEncodedString(
caCerts,
).slice(0, -1);
chainWithoutRoot.forEach((certItem) => {
const cert = certItem as Certificate;
certificateChain += createPemBlock(
'CERTIFICATE',
Buffer.from(cert.toSchema().toBER(false)).toString('base64'),
);
});
return certificateChain;
} | /**
* Create a certificate chain including leaf and sub CA certificates except for the root certificate.
*
* @param {string} signedCert - The leaf certificate.
* @param {string} caCerts - CA certificates.
* @return {string} The certificate chain pem.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/CertificateAuthority.ts#L281-L312 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Acme.getRootCACertificate | async getRootCACertificate(): Promise<string> {
const response = await fetch(
`https://letsencrypt.org/certs/${this._preferredChain.file}.pem`,
);
if (!response.ok && response.status !== 304) {
throw new Error(
`Failed to fetch certificate: ${response.status}: ${await response.text()}`,
);
}
return await response.text();
} | /**
* Get LetsEncrypt Root CA certificate, ISRG Root X1.
* @return {Promise<string>} The CA certificate pem.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/acme.ts#L82-L94 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Acme.signCertificateByExternalCA | async signCertificateByExternalCA(csrString: string): Promise<string> {
const folderPath =
'/usr/local/apps/citrineos/Server/src/assets/.well-known/acme-challenge';
const cert = await this._client?.auto({
csr: csrString,
email: this._email,
termsOfServiceAgreed: true,
preferredChain: this._preferredChain.name,
challengePriority: ['http-01'],
skipChallengeVerification: true,
challengeCreateFn: async (authz, challenge, keyAuthorization) => {
this._logger.debug('Triggered challengeCreateFn()');
const filePath = `${folderPath}/${challenge.token}`;
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
this._logger.debug(`Directory created: ${folderPath}`);
} else {
this._logger.debug(`Directory already exists: ${folderPath}`);
}
const fileContents = keyAuthorization;
this._logger.debug(
`Creating challenge response ${fileContents} for ${authz.identifier.value} at path: ${filePath}`,
);
fs.writeFileSync(filePath, fileContents);
},
challengeRemoveFn: async (_authz, _challenge, _keyAuthorization) => {
this._logger.debug(
`Triggered challengeRemoveFn(). Would remove "${folderPath}`,
);
fs.rmSync(folderPath, { recursive: true, force: true });
},
});
if (!cert) {
throw new Error('Failed to get signed certificate');
}
this._logger.debug(`Certificate singed by external CA: ${cert}`);
return cert;
} | /**
* Retrieves a signed certificate based on the provided CSR.
* The returned certificate will be signed by Let's Encrypt, ISRG Root X1.
* which is listed in https://ccadb.my.salesforce-sites.com/mozilla/CAAIdentifiersReport
*
* @param {string} csrString - The certificate signing request.
* @return {Promise<string>} The signed certificate.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/acme.ts#L104-L143 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Acme.getCertificateChain | async getCertificateChain(csrString: string): Promise<string> {
const [serverId, [certChain, subCAPrivateKey]] =
this._securityCertChainKeyMap.entries().next().value;
this._logger.debug(
`Found certificate chain in server ${serverId}: ${certChain}`,
);
const certChainArray: string[] = parseCertificateChainPem(certChain);
if (certChainArray.length < 2) {
throw new Error(
`The size of the chain is ${certChainArray.length}. Sub CA certificate for signing not found`,
);
}
this._logger.info(`Found Sub CA certificate: ${certChainArray[1]}`);
const signedCertPem: string = createSignedCertificateFromCSR(
csrString,
certChainArray[1],
subCAPrivateKey,
).getPEM();
// Generate and return certificate chain for signed certificate
certChainArray[0] = signedCertPem.replace(/\n+$/, '');
return certChainArray.join('\n');
} | /**
* Get sub CA from the certificate chain.
* Use it to sign certificate based on the CSR string.
*
* @param {string} csrString - The Certificate Signing Request (CSR) string.
* @return {Promise<string>} - The signed certificate followed by sub CA in PEM format.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/acme.ts#L152-L176 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Hubject.getSignedCertificate | async getSignedCertificate(csrString: string): Promise<string> {
const url = `${this._baseUrl}/cpo/simpleenroll/${this._isoVersion}`;
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/pkcs10',
Authorization: await this._getAuthorizationToken(this._tokenUrl),
'Content-Type': 'application/pkcs10',
},
body: csrString,
});
if (response.status !== 200) {
throw new Error(
`Get signed certificate response is unexpected: ${response.status}: ${await response.text()}`,
);
}
return await response.text();
} | /**
* Retrieves a signed certificate based on the provided CSR.
* DOC: https://hubject.stoplight.io/docs/open-plugncharge/486f0b8b3ded4-simple-enroll-iso-15118-2-and-iso-15118-20
*
* @param {string} csrString - The certificate signing request from SignCertificateRequest.
* @return {Promise<string>} The signed certificate without header and footer.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/hubject.ts#L38-L57 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Hubject.getCACertificates | async getCACertificates(): Promise<string> {
const url = `${this._baseUrl}/cpo/cacerts/${this._isoVersion}`;
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/pkcs10, application/pkcs7',
Authorization: await this._getAuthorizationToken(this._tokenUrl),
'Content-Transfer-Encoding': 'application/pkcs10',
},
});
if (response.status !== 200) {
throw new Error(
`Get CA certificates response is unexpected: ${response.status}: ${await response.text()}`,
);
}
return await response.text();
} | /**
* Retrieves the CA certificates including sub CAs and root CA.
* DOC: https://hubject.stoplight.io/docs/open-plugncharge/e246aa213bc22-obtaining-ca-certificates-iso-15118-2-and-iso-15118-20
*
* @return {Promise<string>} The CA certificates.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/hubject.ts#L65-L83 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Hubject.getRootCertificates | async getRootCertificates(): Promise<string[]> {
const url = `${this._baseUrl}/v1/root/rootCerts`;
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: await this._getAuthorizationToken(this._tokenUrl),
},
});
if (response.status !== 200) {
throw new Error(
`Get root certificates response is unexpected: ${response.status}: ${await response.text()}`,
);
}
const certificates: string[] = [];
const rootCertificatesResponse: RootCertificatesResponse = JSON.parse(
await response.text(),
);
for (const root of rootCertificatesResponse.RootCertificateCollection
.rootCertificates) {
certificates.push(createPemBlock('CERTIFICATE', root.caCertificate));
}
return certificates;
} | /**
* Retrieves all root certificates from Hubject.
* Refer to https://hubject.stoplight.io/docs/open-plugncharge/fdc9bdfdd4fb2-get-all-root-certificates
*
* @return {Promise<string[]>} Array of root certificate.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/hubject.ts#L146-L172 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Hubject._parseBearerToken | private _parseBearerToken(token: string): string {
let tokenValue: string = token.split('Bearer ')[1];
tokenValue = tokenValue.split('\n')[0];
return 'Bearer ' + tokenValue;
} | /**
* Parses the Bearer token from the input token
* which is expected to be in the format of "XXXXBearer <token>\nXXXXX"
*
* @param {string} token - The input token string to parse.
* @return {string} The parsed Bearer token string.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/certificate/client/hubject.ts#L191-L195 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection.sendMessage | sendMessage(identifier: string, message: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
this._cache
.get(identifier, CacheNamespace.Connections)
.then((clientConnection) => {
if (clientConnection) {
const websocketConnection =
this._identifierConnections.get(identifier);
if (
websocketConnection &&
websocketConnection.readyState === WebSocket.OPEN
) {
websocketConnection.send(message, (error) => {
if (error) {
this._logger.error('On message send error', error);
reject(error); // Reject the promise with the error
} else {
resolve(true); // Resolve the promise with true indicating success
}
});
} else {
const errorMsg =
'Websocket connection is not ready - ' + identifier;
this._logger.fatal(errorMsg);
websocketConnection?.close(1011, errorMsg);
reject(new Error(errorMsg)); // Reject with a new error
}
} else {
const errorMsg =
'Cannot identify client connection for ' + identifier;
// This can happen when a charging station disconnects in the moment a message is trying to send.
// Retry logic on the message sender might not suffice as charging station might connect to different instance.
this._logger.error(errorMsg);
this._identifierConnections
.get(identifier)
?.close(
1011,
'Failed to get connection information for ' + identifier,
);
reject(new Error(errorMsg)); // Reject with a new error
}
})
.catch(reject); // In case `_cache.get` fails
});
} | /**
* Send a message to the charging station specified by the identifier.
*
* @param {string} identifier - The identifier of the client.
* @param {string} message - The message to send.
* @return {boolean} True if the method sends the message successfully, false otherwise.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L124-L168 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection.updateTlsCertificates | updateTlsCertificates(
serverId: string,
tlsKey: string,
tlsCertificateChain: string,
rootCA?: string,
): void {
let httpsServer = this._httpServersMap.get(serverId);
if (httpsServer && httpsServer instanceof https.Server) {
const secureContextOptions: SecureContextOptions = {
key: tlsKey,
cert: tlsCertificateChain,
};
if (rootCA) {
secureContextOptions.ca = rootCA;
}
httpsServer.setSecureContext(secureContextOptions);
this._logger.info(
`Updated TLS certificates in SecureContextOptions for server ${serverId}`,
);
} else {
throw new TypeError(`Server ${serverId} is not a https server.`);
}
} | /**
* Updates certificates for a specific server with the provided TLS key, certificate chain, and optional
* root CA.
*
* @param {string} serverId - The ID of the server to update.
* @param {string} tlsKey - The TLS key to set.
* @param {string} tlsCertificateChain - The TLS certificate chain to set.
* @param {string} [rootCA] - The root CA to set (optional).
* @return {void} void
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L185-L208 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._upgradeRequest | private async _upgradeRequest(
req: http.IncomingMessage,
socket: Duplex,
head: Buffer,
wss: WebSocketServer,
websocketServerConfig: WebsocketServerConfig,
) {
// Failed mTLS and TLS requests are rejected by the server before getting this far
this._logger.debug('On upgrade request', req.method, req.url, req.headers);
try {
const { identifier } = await this._authenticator.authenticate(req, {
securityProfile: websocketServerConfig.securityProfile,
allowUnknownChargingStations:
websocketServerConfig.allowUnknownChargingStations,
});
// Register client
const registered = await this._cache.set(
identifier,
websocketServerConfig.id,
CacheNamespace.Connections,
);
if (!registered) {
this._logger.fatal('Failed to register websocket client', identifier);
return false;
} else {
this._logger.debug(
'Successfully registered websocket client',
identifier,
);
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
} catch (error) {
this._logger.warn(error);
this._rejectUpgradeUnauthorized(socket);
}
} | /**
* Method to validate websocket upgrade requests and pass them to the socket server.
*
* @param {IncomingMessage} req - The request object.
* @param {Duplex} socket - Websocket duplex stream.
* @param {Buffer} head - Websocket buffer.
* @param {WebSocketServer} wss - Websocket server.
* @param {WebsocketServerConfig} websocketServerConfig - websocket server config.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L235-L275 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._rejectUpgradeUnauthorized | private _rejectUpgradeUnauthorized(socket: Duplex) {
socket.write('HTTP/1.1 401 Unauthorized\r\n');
socket.write(
'WWW-Authenticate: Basic realm="Access to the WebSocket", charset="UTF-8"\r\n',
);
socket.write('\r\n');
socket.end();
socket.destroy();
} | /**
* Utility function to reject websocket upgrade requests with 401 status code.
* @param socket - Websocket duplex stream.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L281-L289 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._handleProtocols | private _handleProtocols(
protocols: Set<string>,
req: http.IncomingMessage,
wsServerProtocol: string,
) {
// Only supports configured protocol version
if (protocols.has(wsServerProtocol)) {
return wsServerProtocol;
}
this._logger.error(
`Protocol mismatch. Supported protocols: [${[...protocols].join(', ')}], but requested protocol: '${wsServerProtocol}' not supported.`,
);
// Reject the client trying to connect
return false;
} | /**
* Internal method to handle new client connection and ensures supported protocols are used.
*
* @param {Set<string>} protocols - The set of protocols to handle.
* @param {IncomingMessage} req - The request object.
* @param {string} wsServerProtocol - The websocket server protocol.
* @return {boolean|string} - Returns the protocol version if successful, otherwise false.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L299-L313 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._onConnection | private async _onConnection(
ws: WebSocket,
pingInterval: number,
req: http.IncomingMessage,
): Promise<void> {
// Pause the WebSocket event emitter until broker is established
ws.pause();
const identifier = this._getClientIdFromUrl(req.url as string);
this._identifierConnections.set(identifier, ws);
try {
// Get IP address of client
const ip =
req.headers['x-forwarded-for']?.toString().split(',')[0].trim() ||
req.socket.remoteAddress ||
'N/A';
const port = req.socket.remotePort as number;
this._logger.info('Client websocket connected', identifier, ip, port);
this._router.registerConnection(identifier);
this._logger.info(
'Successfully connected new charging station.',
identifier,
);
// Register all websocket events
this._registerWebsocketEvents(identifier, ws, pingInterval);
// Resume the WebSocket event emitter after events have been subscribed to
ws.resume();
} catch (error) {
this._logger.fatal(
'Failed to subscribe to message broker for ',
identifier,
);
ws.close(1011, 'Failed to subscribe to message broker for ' + identifier);
}
} | /**
* Internal method to handle the connection event when a WebSocket connection is established.
* This happens after successful protocol exchange with client.
*
* @param {WebSocket} ws - The WebSocket object representing the connection.
* @param {number} pingInterval - The ping interval in seconds.
* @param {IncomingMessage} req - The request object associated with the connection.
* @return {void}
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L324-L363 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._registerWebsocketEvents | private _registerWebsocketEvents(
identifier: string,
ws: WebSocket,
pingInterval: number,
): void {
ws.onerror = (event: ErrorEvent) => {
this._logger.error(
'Connection error encountered for',
identifier,
event.error,
event.message,
event.type,
);
ws.close(1011, event.message);
};
ws.onmessage = (event: MessageEvent) => {
this._onMessage(identifier, event.data.toString());
};
ws.once('close', () => {
// Unregister client
this._logger.info('Connection closed for', identifier);
this._cache.remove(identifier, CacheNamespace.Connections);
this._identifierConnections.delete(identifier);
this._router.deregisterConnection(identifier);
});
ws.on('ping', async (message) => {
this._logger.debug(
`Ping received for ${identifier} with message ${JSON.stringify(message)}`,
);
ws.pong(message);
});
ws.on('pong', async () => {
this._logger.debug('Pong received for', identifier);
const clientConnection: string | null = await this._cache.get(
identifier,
CacheNamespace.Connections,
);
if (clientConnection) {
// Remove expiration for connection and send ping to client in pingInterval seconds.
await this._cache.set(
identifier,
clientConnection,
CacheNamespace.Connections,
);
this._ping(identifier, ws, pingInterval);
} else {
this._logger.debug(
'Pong received for',
identifier,
'but client is not alive',
);
ws.close(1011, 'Client is not alive');
}
});
this._ping(identifier, ws, pingInterval);
} | /**
* Internal method to register event listeners for the WebSocket connection.
*
* @param {string} identifier - The unique identifier for the connection.
* @param {WebSocket} ws - The WebSocket object representing the connection.
* @param {number} pingInterval - The ping interval in seconds.
* @return {void} This function does not return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L373-L433 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._onMessage | private _onMessage(identifier: string, message: string): void {
this._router.onMessage(identifier, message, new Date());
} | /**
* Internal method to handle the incoming message from the websocket client.
*
* @param {string} identifier - The client identifier.
* @param {string} message - The incoming message from the client.
* @return {void} This function does not return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L442-L444 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._onError | private _onError(wss: WebSocketServer, error: Error): void {
this._logger.error(error);
// TODO: Try to recover the Websocket server
} | /**
* Internal method to handle the error event for the WebSocket server.
*
* @param {WebSocketServer} wss - The WebSocket server instance.
* @param {Error} error - The error object.
* @return {void} This function does not return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L453-L456 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._onClose | private _onClose(wss: WebSocketServer): void {
this._logger.debug('Websocket Server closed');
// TODO: Try to recover the Websocket server
} | /**
* Internal method to handle the event when the WebSocketServer is closed.
*
* @param {WebSocketServer} wss - The WebSocketServer instance.
* @return {void} This function does not return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L464-L467 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._ping | private async _ping(
identifier: string,
ws: WebSocket,
pingInterval: number,
): Promise<void> {
setTimeout(async () => {
const clientConnection: string | null = await this._cache.get(
identifier,
CacheNamespace.Connections,
);
if (clientConnection) {
this._logger.debug('Pinging client', identifier);
// Set connection expiration and send ping to client
await this._cache.set(
identifier,
clientConnection,
CacheNamespace.Connections,
pingInterval * 2,
);
ws.ping();
} else {
ws.close(1011, 'Client is not alive');
}
}, pingInterval * 1000);
} | /**
* Internal method to execute a ping operation on a WebSocket connection after a delay of 60 seconds.
*
* @param {string} identifier - The identifier of the client connection.
* @param {WebSocket} ws - The WebSocket connection to ping.
* @param {number} pingInterval - The ping interval in milliseconds.
* @return {void} This function does not return anything.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L477-L501 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | WebsocketNetworkConnection._getClientIdFromUrl | private _getClientIdFromUrl(url: string): string {
return url.split('/').pop() as string;
} | /**
*
* @param url Http upgrade request url used by charger
* @returns Charger identifier
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/networkconnection/WebsocketNetworkConnection.ts#L507-L509 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubReceiver.constructor | constructor(
config: SystemConfig,
logger?: Logger<ILogObj>,
module?: IModule,
cache?: ICache,
) {
super(config, logger, module);
this._cache = cache || new MemoryCache();
this._client = new PubSub({
servicePath: this._config.util.messageBroker.pubsub?.servicePath,
});
} | /**
* Constructor
*
* @param topicPrefix Custom topic prefix, defaults to "ocpp"
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/receiver.ts#L50-L61 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubReceiver.subscribe | subscribe(
identifier: string,
actions?: CallAction[],
filter?: { [k: string]: string },
): Promise<boolean> {
const topicName = `${this._config.util.messageBroker.pubsub?.topicPrefix}-${this._config.util.messageBroker.pubsub?.topicName}`;
// Check if topic exists, if not create it
return this._client
.topic(topicName)
.exists()
.then(([exists]) => {
if (exists) {
return this._client.topic(topicName);
} else {
return this._client.createTopic(topicName).then(([newTopic]) => {
this._logger.debug(`Topic ${newTopic.name} created.`);
return newTopic;
});
}
})
.then((topic) =>
this._subscribe(identifier, topic, actions, filter).then((name) => {
// TODO: fix issue with multiple subscriptions overwriting cache values
this._cache.set(
`${PubSubReceiver.CACHE_PREFIX}${identifier}`,
name,
CacheNamespace.Other,
);
return name !== undefined;
}),
)
.catch((error) => {
this._logger.error(error);
return false;
});
} | /**
* The init method will create a subscription for each action in the {@link CallAction} array.
*
* @param actions All actions to subscribe to
* @param stateFilter Optional filter for the subscription via {@link MessageState}, must be used to prevent looping of messages in Google PubSub
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/receiver.ts#L70-L106 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubReceiver.shutdown | shutdown() {
this._subscriptions.forEach((subscription) => {
subscription.close().then(() => {
subscription.delete().then(() => {
this._logger.debug(`Subscription ${subscription.name} deleted.`);
});
});
});
} | /**
* Shutdown the receiver by closing all subscriptions and deleting them.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/receiver.ts#L137-L145 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubReceiver._onMessage | protected async _onMessage(message: PubSubMessage): Promise<void> {
try {
const parsed = plainToInstance(
Message<OcppRequest | OcppResponse | OcppError>,
<Message<OcppRequest | OcppResponse | OcppError>>(
JSON.parse(message.data.toString())
),
);
await this.handle(parsed, message.id);
} catch (error) {
if (error instanceof RetryMessageError) {
this._logger.warn('Retrying message: ', error.message);
// Retryable error, usually ongoing call with station when trying to send new call
message.nack();
return;
} else {
this._logger.error('Error while processing message:', error, message);
}
}
message.ack();
} | /**
* Underlying PubSub message handler.
*
* @param message The PubSubMessage to process
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/receiver.ts#L152-L172 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubReceiver._subscribe | private _subscribe(
identifier: string,
topic: Topic,
actions?: CallAction[],
filter?: { [k: string]: string },
): Promise<string> {
// Generate topic name
const subscriptionName = `${topic.name.split('/').pop()}-${identifier}-${Date.now()}`;
// Create message filter based on actions
const actionFragments: string[] = [];
const hasActionFilter: boolean =
actions !== undefined && actions.length > 0;
if (hasActionFilter) {
for (const action of actions as CallAction[]) {
// Convert into action index due to PubSub limits of 256 characters in filter string
const index: number = Object.keys(CallAction).indexOf(
action.toString(),
);
actionFragments.push(`attributes.action="${index}"`);
}
}
// Create message filter
const filterFragments: string[] = [];
if (filter) {
for (const key in filter) {
if (filter[key]) {
filterFragments.push(`attributes.${key}="${filter[key]}"`);
}
}
}
const actionFilterString = `(${actionFragments.join(' OR ')})`;
const otherFilterString = filterFragments.join(' AND ');
const filterString = `${otherFilterString} ${hasActionFilter ? 'AND ' + actionFilterString : ''}`;
this._logger.debug('Using filter:', filterString);
// Create subscription with filter
return topic
.createSubscription(subscriptionName, {
enableExactlyOnceDelivery: true,
filter: filterString,
})
.then(([subscription]) => {
this._logger.debug(`Subscription ${subscription.name} created.`);
subscription.on('message', this._onMessage.bind(this));
this._subscriptions.push(subscription);
return subscription.name;
});
} | /**
*
* @param action
* @param stateFilter
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/receiver.ts#L184-L235 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubSender.constructor | constructor(config: SystemConfig, logger?: Logger<ILogObj>) {
super(config, logger);
this._client = new PubSub({
servicePath: this._config.util.messageBroker.pubsub?.servicePath,
});
} | /**
* Constructor
*
* @param topicPrefix Custom topic prefix, defaults to "ocpp"
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/sender.ts#L38-L44 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubSender.sendRequest | sendRequest(
message: IMessage<OcppRequest>,
payload?: OcppRequest,
): Promise<IMessageConfirmation> {
return this.send(message, payload, MessageState.Request);
} | /**
* Convenience method to send a request message.
*
* @param message The {@link IMessage} to send
* @param payload The payload to send
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/sender.ts#L53-L58 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubSender.sendResponse | sendResponse(
message: IMessage<OcppResponse | OcppError>,
payload?: OcppResponse | OcppError,
): Promise<IMessageConfirmation> {
return this.send(message, payload, MessageState.Response);
} | /**
* Convenience method to send a confirmation message.
* @param message The {@link IMessage} to send
* @param payload The payload to send
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/sender.ts#L66-L71 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubSender.send | send(
message: IMessage<OcppRequest | OcppResponse | OcppError>,
payload?: OcppRequest | OcppResponse | OcppError,
state?: MessageState,
): Promise<IMessageConfirmation> {
if (payload) {
message.payload = payload;
}
if (state) {
message.state = state;
}
if (!message.state) {
throw new Error('Message state must be set');
}
if (!message.payload) {
throw new Error('Message payload must be set');
}
const topicName = `${this._config.util.messageBroker.pubsub?.topicPrefix}-${this._config.util.messageBroker.pubsub?.topicName}`;
// Convert into action index due to PubSub limits of 256 characters in filter string
const actionIndex: number = Object.keys(CallAction).indexOf(
message.action.toString(),
);
this._logger.debug(`Publishing to ${topicName}:`, message);
return this._client
.topic(topicName)
.publishMessage({
json: message,
attributes: {
origin: message.origin.toString(),
eventGroup: message.eventGroup.toString(),
action: actionIndex.toString(),
state: message.state.toString(),
...message.context,
},
})
.then((result) => ({ success: true, result }))
.catch((error) => ({ success: false, error }));
} | /**
* Publishes the given message to Google PubSub.
*
* @param message The {@link IMessage} to publish
* @param payload The payload to within the {@link IMessage}
* @param state The {@link MessageState} of the {@link IMessage}
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/sender.ts#L81-L123 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | PubSubSender.shutdown | shutdown(): void {
// Nothing to do
} | /**
* Interface implementation
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/google-pubsub/sender.ts#L128-L130 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | KafkaReceiver._onMessage | private async _onMessage(
{ topic, partition, message }: EachMessagePayload,
consumer: Consumer,
): Promise<void> {
this._logger.debug(
`Received message ${message.value?.toString()} on topic ${topic} partition ${partition}`,
);
try {
const messageValue = message.value;
if (messageValue) {
const parsed = plainToInstance(
Message<OcppRequest | OcppResponse | OcppError>,
messageValue.toString(),
);
await this.handle(parsed, message.key?.toString());
}
} catch (error) {
if (error instanceof RetryMessageError) {
this._logger.warn('Retrying message: ', error.message);
// Retryable error, usually ongoing call with station when trying to send new call
return;
} else {
this._logger.error('Error while processing message:', error, message);
}
}
await consumer.commitOffsets([
{ topic, partition, offset: message.offset },
]);
} | /**
* Underlying Kafka message handler.
*
* @param message The PubSub message to process
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/kafka/receiver.ts#L143-L171 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | KafkaSender.constructor | constructor(config: SystemConfig, logger?: Logger<ILogObj>) {
super(config, logger);
this._client = new Kafka({
brokers: config.util.messageBroker.kafka?.brokers || [],
ssl: true,
sasl: {
mechanism: 'plain',
username: config.util.messageBroker.kafka?.sasl.username || '',
password: config.util.messageBroker.kafka?.sasl.password || '',
},
});
this._producers = new Array<Producer>();
this._topicName = `${this._config.util.messageBroker.kafka?.topicPrefix}-${this._config.util.messageBroker.kafka?.topicName}`;
const admin: Admin = this._client.admin();
admin
.connect()
.then(() => admin.listTopics())
.then((topics) => {
if (
!topics ||
topics.filter((topic) => topic === this._topicName).length === 0
) {
this._client
.admin()
.createTopics({ topics: [{ topic: this._topicName }] })
.then(() => {
this._logger.debug(`Topic ${this._topicName} created.`);
});
}
})
.then(() => admin.disconnect());
} | /**
* Constructor
*
* @param topicPrefix Custom topic prefix, defaults to "ocpp"
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/kafka/sender.ts#L39-L72 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | KafkaSender.sendRequest | sendRequest(
message: IMessage<OcppRequest>,
payload?: OcppRequest,
): Promise<IMessageConfirmation> {
return this.send(message, payload, MessageState.Request);
} | /**
* Convenience method to send a request message.
*
* @param message The {@link IMessage} to send
* @param payload The payload to send
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/kafka/sender.ts#L81-L86 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | KafkaSender.sendResponse | sendResponse(
message: IMessage<OcppResponse | OcppError>,
payload?: OcppResponse | OcppError,
): Promise<IMessageConfirmation> {
return this.send(message, payload, MessageState.Response);
} | /**
* Convenience method to send a confirmation message.
* @param message The {@link IMessage} to send
* @param payload The payload to send
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/kafka/sender.ts#L94-L99 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | KafkaSender.send | send(
message: IMessage<OcppRequest | OcppResponse | OcppError>,
payload?: OcppRequest | OcppResponse | OcppError,
state?: MessageState,
): Promise<IMessageConfirmation> {
if (payload) {
message.payload = payload;
}
if (state) {
message.state = state;
}
if (!message.state) {
throw new Error('Message state must be set');
}
if (!message.payload) {
throw new Error('Message payload must be set');
}
this._logger.debug(`Publishing to ${this._topicName}:`, message);
const producer = this._client.producer();
return producer
.connect()
.then(() =>
producer.send({
topic: this._topicName,
messages: [
{
headers: {
origin: message.origin.toString(),
eventGroup: message.eventGroup.toString(),
action: message.action.toString(),
state: message.state.toString(),
...message.context,
},
value: JSON.stringify(message),
},
],
}),
)
.then(() => this._producers.push(producer))
.then((result) => ({ success: true, result }))
.catch((error) => ({ success: false, error }));
} | /**
* Publishes the given message to Google PubSub.
*
* @param message The {@link IMessage} to publish
* @param payload The payload to within the {@link IMessage}
* @param state The {@link MessageState} of the {@link IMessage}
* @returns
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/kafka/sender.ts#L109-L155 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | KafkaSender.shutdown | shutdown(): void {
this._producers.forEach((producer) => {
producer.disconnect();
});
} | /**
* Interface implementation
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/kafka/sender.ts#L160-L164 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqReceiver.subscribe | async subscribe(
identifier: string,
actions?: CallAction[],
filter?: { [k: string]: string },
): Promise<boolean> {
// If actions are a defined but empty list, it is likely a module
// with no available actions and should not have a queue.
//
// If actions are undefined, it is likely a charger,
// which is "allowed" not to have actions.
if (actions && actions.length === 0) {
this._logger.debug(
`Skipping queue binding for module ${identifier} as there are no available actions.`,
);
return true;
}
const exchange = this._config.util.messageBroker.amqp?.exchange as string;
const queueName = `${RabbitMqReceiver.QUEUE_PREFIX}${identifier}_${Date.now()}`;
// Ensure that filter includes the x-match header set to all
filter = filter
? {
'x-match': 'all',
...filter,
}
: { 'x-match': 'all' };
const channel = this._channel || (await this._connect());
this._channel = channel;
// Assert exchange and queue
await channel.assertExchange(exchange, 'headers', { durable: false });
await channel.assertQueue(queueName, {
durable: false,
autoDelete: true,
exclusive: false,
});
// Bind queue based on provided actions and filters
if (actions && actions.length > 0) {
for (const action of actions) {
this._logger.debug(
`Bind ${queueName} on ${exchange} for ${action} with filter ${JSON.stringify(filter)}.`,
);
await channel.bindQueue(queueName, exchange, '', { action, ...filter });
}
} else {
this._logger.debug(
`Bind ${queueName} on ${exchange} with filter ${JSON.stringify(filter)}.`,
);
await channel.bindQueue(queueName, exchange, '', filter);
}
// Start consuming messages
await channel.consume(queueName, (msg) => this._onMessage(msg, channel));
// Define cache key
const cacheKey = `${RabbitMqReceiver.CACHE_PREFIX}${identifier}`;
// Retrieve cached queue names
const cachedQueues = await this._cache
.get<Array<string>>(cacheKey, CacheNamespace.Other, () => Array<string>)
.then((value) => {
if (value) {
value.push(queueName);
return value;
}
return new Array<string>(queueName);
});
// Add queue name to cache
await this._cache.set(
cacheKey,
JSON.stringify(cachedQueues),
CacheNamespace.Other,
);
return true;
} | /**
* Binds queue to an exchange given identifier and optional actions and filter.
* Note: Due to the nature of AMQP 0-9-1 model, if you need to filter for the identifier, you **MUST** provide it in the filter object.
*
* @param {string} identifier - The identifier of the channel to subscribe to.
* @param {CallAction[]} actions - Optional. An array of actions to filter the messages.
* @param {{ [k: string]: string; }} filter - Optional. An object representing the filter to apply on the messages.
* @return {Promise<boolean>} A promise that resolves to true if the subscription is successful, false otherwise.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/receiver.ts#L68-L148 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqReceiver._connect | protected _connect(): Promise<amqplib.Channel> {
return amqplib
.connect(this._config.util.messageBroker.amqp?.url || '')
.then((connection) => {
this._connection = connection;
return connection.createChannel();
})
.then((channel) => {
// Add listener for channel errors
channel.on('error', (err) => {
this._logger.error('AMQP channel error', err);
// TODO: add recovery logic
});
return channel;
});
} | /**
* Connect to RabbitMQ
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/receiver.ts#L193-L208 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqReceiver._onMessage | protected async _onMessage(
message: amqplib.ConsumeMessage | null,
channel: amqplib.Channel,
): Promise<void> {
if (message) {
try {
this._logger.debug(
'_onMessage:Received message:',
message.properties,
message.content.toString(),
);
const parsed = plainToInstance(
Message<OcppRequest | OcppResponse | OcppError>,
<Message<OcppRequest | OcppResponse | OcppError>>(
JSON.parse(message.content.toString())
),
);
await this.handle(parsed, message.properties);
} catch (error) {
if (error instanceof RetryMessageError) {
this._logger.warn('Retrying message: ', error.message);
// Retryable error, usually ongoing call with station when trying to send new call
channel.nack(message);
return;
} else {
this._logger.error('Error while processing message:', error, message);
}
}
channel.ack(message);
}
} | /**
* Underlying RabbitMQ message handler.
*
* @param message The AMQPMessage to process
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/receiver.ts#L215-L245 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqSender.constructor | constructor(config: SystemConfig, logger?: Logger<ILogObj>) {
super(config, logger);
this._connect().then((channel) => {
this._channel = channel;
});
} | /**
* Constructor for the class.
*
* @param {SystemConfig} config - The system configuration.
* @param {Logger<ILogObj>} [logger] - The logger object.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/sender.ts#L45-L51 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqSender.sendRequest | sendRequest(
message: IMessage<OcppRequest>,
payload?: OcppRequest | undefined,
): Promise<IMessageConfirmation> {
return this.send(message, payload, MessageState.Request);
} | /**
* Sends a request message with an optional payload and returns a promise that resolves to the confirmation message.
*
* @param {IMessage<OcppRequest>} message - The message to be sent.
* @param {OcppRequest | undefined} payload - The optional payload to be sent with the message.
* @return {Promise<IMessageConfirmation>} A promise that resolves to the confirmation message.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/sender.ts#L64-L69 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqSender.sendResponse | sendResponse(
message: IMessage<OcppResponse | OcppError>,
payload?: OcppResponse | OcppError,
): Promise<IMessageConfirmation> {
return this.send(message, payload, MessageState.Response);
} | /**
* Sends a response message and returns a promise of the message confirmation.
*
* @param {IMessage<OcppResponse | OcppError>} message - The message to send.
* @param {OcppResponse | OcppError} payload - The payload to include in the response.
* @return {Promise<IMessageConfirmation>} - A promise that resolves to the message confirmation.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/sender.ts#L78-L83 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqSender.send | async send(
message: IMessage<OcppRequest | OcppResponse | OcppError>,
payload?: OcppRequest | OcppResponse | OcppError,
state?: MessageState,
): Promise<IMessageConfirmation> {
if (payload) {
message.payload = payload;
}
if (state) {
message.state = state;
}
if (!message.state) {
return { success: false, payload: 'Message state must be set' };
}
if (!message.payload) {
return { success: false, payload: 'Message payload must be set' };
}
const exchange = this._config.util.messageBroker.amqp?.exchange as string;
const channel = this._channel || (await this._connect());
this._channel = channel;
this._logger.debug(`Publishing to ${exchange}:`, message);
const success = channel.publish(
exchange || '',
'',
Buffer.from(JSON.stringify(instanceToPlain(message)), 'utf-8'),
{
contentEncoding: 'utf-8',
contentType: 'application/json',
headers: {
origin: message.origin.toString(),
eventGroup: message.eventGroup.toString(),
action: message.action.toString(),
state: message.state.toString(),
...message.context,
},
},
);
return { success };
} | /**
* Sends a message and returns a promise that resolves to a message confirmation.
*
* @param {IMessage<OcppRequest | OcppResponse | OcppError>} message - The message to be sent.
* @param {OcppRequest | OcppResponse | OcppError} [payload] - The payload to be included in the message.
* @param {MessageState} [state] - The state of the message.
* @return {Promise<IMessageConfirmation>} - A promise that resolves to a message confirmation.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/sender.ts#L93-L137 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqSender.shutdown | shutdown(): Promise<void> {
return Promise.resolve();
} | /**
* Shuts down the sender by closing the client.
*
* @return {Promise<void>} A promise that resolves when the client is closed.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/sender.ts#L144-L146 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | RabbitMqSender._connect | protected _connect(): Promise<amqplib.Channel> {
return amqplib
.connect(this._config.util.messageBroker.amqp?.url || '')
.then(async (connection) => {
this._connection = connection;
return connection.createChannel();
})
.then((channel) => {
// Add listener for channel errors
channel.on('error', (err) => {
this._logger.error('AMQP channel error', err);
// TODO: add recovery logic
});
return channel;
});
} | /**
* Connect to RabbitMQ
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/queue/rabbit-mq/sender.ts#L155-L170 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SignedMeterValuesUtil.constructor | constructor(
fileAccess: IFileAccess,
config: SystemConfig,
logger: Logger<ILogObj>,
) {
this._fileAccess = fileAccess;
this._logger = logger;
this._chargingStationSecurityInfoRepository =
new sequelize.SequelizeChargingStationSecurityInfoRepository(
config,
logger,
);
this._signedMeterValuesConfiguration =
config.modules.transactions.signedMeterValuesConfiguration;
} | /**
* @param {IFileAccess} [fileAccess] - The `fileAccess` allows access to the configured file storage.
*
* @param {SystemConfig} config - The `config` contains the current system configuration settings.
*
* @param {Logger<ILogObj>} [logger] - The `logger` represents an instance of {@link Logger<ILogObj>}.
*
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/security/SignedMeterValuesUtil.ts#L36-L51 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | SignedMeterValuesUtil.validateMeterValues | public async validateMeterValues(
stationId: string,
meterValues: [MeterValueType, ...MeterValueType[]],
): Promise<boolean> {
for (const meterValue of meterValues) {
for (const sampledValue of meterValue.sampledValue) {
if (sampledValue.signedMeterValue) {
const validMeterValues = await this.validateSignedSampledValue(
stationId,
sampledValue.signedMeterValue,
);
if (!validMeterValues) {
return false;
}
}
}
}
return true;
} | /**
* Checks the validity of a meter value.
*
* If a meter value is unsigned, it is valid.
*
* If a meter value is signed, it is valid if:
* - SignedMeterValuesConfig is configured
* AND
* - The incoming signed meter value's signing method matches the configured signing method
* AND
* - The incoming signed meter value's public key is empty but there is a public key stored for that charging station
* OR
* - The incoming signed meter value's public key isn't empty and it matches the configured public key
*
* @param stationId - The charging station the meter values belong to
* @param meterValues - The list of meter values
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/security/SignedMeterValuesUtil.ts#L70-L89 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | OcppTransformObject | function OcppTransformObject({
swaggerObject,
openapiObject,
}: {
swaggerObject: Partial<OpenAPIV2.Document>;
openapiObject: Partial<OpenAPIV3.Document | OpenAPIV3_1.Document>;
}) {
console.log('OcppTransformObject: Transforming OpenAPI object...');
if (openapiObject.paths && openapiObject.components) {
for (const pathKey in openapiObject.paths) {
const path: OpenAPIV3.PathsObject = openapiObject.paths[
pathKey
] as OpenAPIV3.PathsObject;
if (path) {
for (const methodKey in path) {
const method: OpenAPIV3.OperationObject = path[
methodKey
] as OpenAPIV3.OperationObject;
if (method) {
// Set tags based on path key if tags were not passed in
if (!method.tags) {
method.tags = pathKey
.split('/')
.slice(2, -1)
.map((tag) => tag.charAt(0).toUpperCase() + tag.slice(1));
}
}
}
}
}
}
return openapiObject;
} | /**
* This transformation is used to set default tags
*
* @param {object} swaggerObject - The original Swagger object to be transformed.
* @param {object} openapiObject - The original OpenAPI object to be transformed.
* @return {object} The transformed OpenAPI object.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/util/swagger.ts#L28-L60 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Timer.difference | get difference(): bigint | null {
return this.timerEnd ? this.timerEnd - this.timerStart : null;
} | /**
* Calculates and returns the difference between the timer end and start values.
*
* @return {bigint | null} The difference between the timer end and start values, or null if either value is missing.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/util/timer.ts#L34-L36 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | Timer.end | end(): bigint | null {
this.timerEnd = BigInt(new Date().getTime());
return this.difference;
} | /**
* Ends the timer and returns the time difference.
*
* @returns The time difference between the start and end of the timer.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/02_Util/src/util/timer.ts#L43-L46 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificatesModuleApi.constructor | constructor(
certificatesModule: CertificatesModule,
server: FastifyInstance,
fileAccess: IFileAccess,
networkConnection: WebsocketNetworkConnection,
websocketServersConfig: WebsocketServerConfig[],
logger?: Logger<ILogObj>,
) {
super(certificatesModule, server, logger);
this._fileAccess = fileAccess;
this._networkConnection = networkConnection;
this._websocketServersConfig = websocketServersConfig;
} | /**
* Constructs a new instance of the class.
*
* @param {CertificatesModule} certificatesModule - The Certificates module.
* @param {FastifyInstance} server - The Fastify server instance.
* @param {Logger<ILogObj>} [logger] - The logger instance.
* @param {IFileAccess} fileAccess - The FileAccess
* @param {WebsocketNetworkConnection} networkConnection - The NetworkConnection
* @param {WebsocketServerConfig[]} websocketServersConfig - Configuration for websocket servers
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Certificates/src/module/api.ts#L77-L89 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificatesModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix =
this._module.config.modules.certificates?.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/Certificates/src/module/api.ts#L447-L451 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificatesModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix =
this._module.config.modules.certificates?.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/Certificates/src/module/api.ts#L459-L463 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificatesModuleApi._generateSubCACertificateSignedByCAServer | private async _generateSubCACertificateSignedByCAServer(
certificate: Certificate,
): Promise<[string, string]> {
const [csrPem, privateKeyPem] = generateCSR(certificate);
const signedCertificate =
await this._module.certificateAuthorityService.signedSubCaCertificateByExternalCA(
csrPem,
);
return [signedCertificate, privateKeyPem];
} | /**
* Generates a sub CA certificate signed by a CA server.
*
* @param {Certificate} certificate - The certificate information used for generating the root certificate.
* @return {Promise<[string, string]>} An array containing the signed certificate and the private key.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Certificates/src/module/api.ts#L566-L575 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificatesModuleApi._storeCertificateAndKey | private async _storeCertificateAndKey(
certificateEntity: Certificate,
certPem: string,
keyPem: string,
filePrefix: PemType,
filePath?: string,
): Promise<Certificate> {
// Store certificate and private key in file storage
certificateEntity.privateKeyFileId = await this._fileAccess.uploadFile(
`${filePrefix}_Key_${certificateEntity.serialNumber}.pem`,
Buffer.from(keyPem),
filePath,
);
certificateEntity.certificateFileId = await this._fileAccess.uploadFile(
`${filePrefix}_Certificate_${certificateEntity.serialNumber}.pem`,
Buffer.from(certPem),
filePath,
);
// Store certificate in db
const certObj = new jsrsasign.X509();
certObj.readCertPEM(certPem);
certificateEntity.issuerName = certObj.getIssuerString();
return await this._module.certificateRepository.createOrUpdateCertificate(
certificateEntity,
);
} | /**
* Store certificate in file storage and db.
* @param certificateEntity certificate to be stored in db
* @param certPem certificate pem to be stored in file storage
* @param keyPem private key pem to be stored in file storage
* @param filePrefix prefix for file name to be stored in file storage
* @param filePath file path in file storage (For directus files, it is the folder id)
* @return certificate stored in db
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Certificates/src/module/api.ts#L586-L611 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | CertificatesModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender: IMessageSender,
handler: IMessageHandler,
logger?: Logger<ILogObj>,
deviceModelRepository?: IDeviceModelRepository,
certificateRepository?: ICertificateRepository,
locationRepository?: ILocationRepository,
certificateAuthorityService?: CertificateAuthorityService,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.Certificates,
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, logger);
this._certificateRepository =
certificateRepository ||
new sequelize.SequelizeCertificateRepository(config, logger);
this._installedCertificateRepository =
new sequelize.SequelizeInstalledCertificateRepository(config, logger);
this._locationRepository =
locationRepository ||
new sequelize.SequelizeLocationRepository(config, logger);
this._certificateAuthorityService =
certificateAuthorityService ||
new CertificateAuthorityService(config, this._logger);
this._logger.info(`Initialized in ${timer.end()}ms...`);
} | /**
* This is the constructor function that initializes the {@link CertificatesModule}.
*
* @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 {ICertificateRepository} [certificateRepository] - An optional parameter of type {@link ICertificateRepository} which
* represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link sequelize.CertificateRepository} instance is created and used.
*
* @param {ILocationRepository} [locationRepository] - An optional parameter of type {@link ILocationRepository} which
* represents a repository for accessing and manipulating variable data.
* If no `deviceModelRepository` is provided, a default {@link sequelize.LocationRepository} instance is created and used.
*
* @param {CertificateAuthorityService} [certificateAuthorityService] - An optional parameter of
* type {@link CertificateAuthorityService} which handles certificate authority operations.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Certificates/src/module/module.ts#L127-L173 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | BootNotificationService.cacheChargerActionsPermissions | async cacheChargerActionsPermissions(
stationId: string,
cachedBootStatus: RegistrationStatusEnumType | null,
bootNotificationResponseStatus: RegistrationStatusEnumType,
): Promise<void> {
// New boot status is Accepted and cachedBootStatus exists (meaning there was a previous Rejected or Pending boot)
if (
bootNotificationResponseStatus === RegistrationStatusEnumType.Accepted
) {
if (cachedBootStatus) {
// Undo blacklisting of charger-originated actions
const promises = Array.from(CALL_SCHEMA_MAP).map(async ([action]) => {
if (action !== CallAction.BootNotification) {
return this._cache.remove(action, stationId);
}
});
await Promise.all(promises);
// Remove cached boot status
await this._cache.remove(BOOT_STATUS, stationId);
this._logger.debug('Cached boot status removed: ', cachedBootStatus);
}
} else if (!cachedBootStatus) {
// Status is not Accepted; i.e. Status is Rejected or Pending.
// Cached boot status for charger did not exist; i.e. this is the first BootNotificationResponse to be Rejected or Pending.
// Blacklist all charger-originated actions except BootNotification
// GetReport messages will need to un-blacklist NotifyReport
// TriggerMessage will need to un-blacklist the message it triggers
const promises = Array.from(CALL_SCHEMA_MAP).map(async ([action]) => {
if (action !== CallAction.BootNotification) {
return this._cache.set(action, 'blacklisted', stationId);
}
});
await Promise.all(promises);
}
} | /**
* Determines whether to blacklist or whitelist charger actions based on its boot status.
*
* If the new boot is accepted and the charger actions were previously blacklisted, then whitelist the charger actions.
* If the new boot is not accepted and charger actions were previously whitelisted, then blacklist the charger actions.
*
* @param stationId
* @param cachedBootStatus
* @param bootNotificationResponseStatus
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Configuration/src/module/BootNotificationService.ts#L128-L162 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | BootNotificationService.confirmGetBaseReportSuccess | async confirmGetBaseReportSuccess(
stationId: string,
requestId: string,
getBaseReportMessageConfirmation: IMessageConfirmation,
maxCachingSeconds: number,
): Promise<void> {
if (getBaseReportMessageConfirmation.success) {
this._logger.debug(
`GetBaseReport successfully sent to charger: ${getBaseReportMessageConfirmation}`,
);
// Wait for GetBaseReport to complete
let getBaseReportCacheValue = await this._cache.onChange(
requestId,
maxCachingSeconds,
stationId,
);
while (getBaseReportCacheValue === 'ongoing') {
getBaseReportCacheValue = await this._cache.onChange(
requestId,
maxCachingSeconds,
stationId,
);
}
if (getBaseReportCacheValue === 'complete') {
this._logger.debug('GetBaseReport process successful.'); // All NotifyReports have been processed
} else {
throw new Error(
'GetBaseReport process failed--message timed out without a response.',
);
}
} else {
throw new Error(
`GetBaseReport failed: ${JSON.stringify(getBaseReportMessageConfirmation)}`,
);
}
} | /**
* Based on the GetBaseReportMessageConfirmation, checks the cache to ensure GetBaseReport truly succeeded.
* If GetBaseReport did not succeed, this method will throw. Otherwise, it will finish without throwing.
*
* @param stationId
* @param requestId
* @param getBaseReportMessageConfirmation
* @param maxCachingSeconds
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Configuration/src/module/BootNotificationService.ts#L194-L232 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | DeviceModelService.getItemsPerMessageSetVariablesByStationId | async getItemsPerMessageSetVariablesByStationId(
stationId: string,
): Promise<number | null> {
const itemsPerMessageSetVariablesAttributes: VariableAttribute[] =
await this._deviceModelRepository.readAllByQuerystring({
stationId: stationId,
component_name: 'DeviceDataCtrlr',
variable_name: 'ItemsPerMessage',
variable_instance: 'SetVariables',
type: AttributeEnumType.Actual,
});
if (itemsPerMessageSetVariablesAttributes.length === 0) {
return null;
} else {
// It is possible for itemsPerMessageSetVariablesAttributes.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(itemsPerMessageSetVariablesAttributes[0].value);
}
} | /**
* Fetches the ItemsPerMessageSetVariables attribute from the device model.
* Returns null if no such attribute exists.
* It is possible for there to be multiple ItemsPerMessageSetVariables 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 ItemsPerMessageSetVariables as a number or null if no such attribute exists.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Configuration/src/module/DeviceModelService.ts#L25-L44 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | DeviceModelService.getItemsPerMessageGetVariablesByStationId | async getItemsPerMessageGetVariablesByStationId(
stationId: string,
): Promise<number | null> {
const itemsPerMessageGetVariablesAttributes: VariableAttribute[] =
await this._deviceModelRepository.readAllByQuerystring({
stationId: stationId,
component_name: 'DeviceDataCtrlr',
variable_name: 'ItemsPerMessage',
variable_instance: 'GetVariables',
type: AttributeEnumType.Actual,
});
if (itemsPerMessageGetVariablesAttributes.length === 0) {
return null;
} else {
// It is possible for itemsPerMessageGetVariablesAttributes.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(itemsPerMessageGetVariablesAttributes[0].value);
}
} | /**
* Fetches the ItemsPerMessageGetVariables attribute from the device model.
* Returns null if no such attribute exists.
* It is possible for there to be multiple ItemsPerMessageGetVariables 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 ItemsPerMessageGetVariables as a number or null if no such attribute exists.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Configuration/src/module/DeviceModelService.ts#L56-L75 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ConfigurationModuleApi.constructor | constructor(
ConfigurationComponent: ConfigurationModule,
server: FastifyInstance,
logger?: Logger<ILogObj>,
) {
super(ConfigurationComponent, server, logger);
} | /**
* Constructor for the class.
*
* @param {ConfigurationModule} ConfigurationComponent - The Configuration component.
* @param {FastifyInstance} server - The server instance.
* @param {Logger<ILogObj>} [logger] - Optional logger instance.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Configuration/src/module/api.ts#L95-L101 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ConfigurationModuleApi._toMessagePath | protected _toMessagePath(input: CallAction): string {
const endpointPrefix =
this._module.config.modules.configuration.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/Configuration/src/module/api.ts#L454-L458 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ConfigurationModuleApi._toDataPath | protected _toDataPath(input: Namespace): string {
const endpointPrefix =
this._module.config.modules.configuration.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/Configuration/src/module/api.ts#L466-L470 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
citrineos-core | github_2023 | citrineos | typescript | ConfigurationModule.constructor | constructor(
config: SystemConfig,
cache: ICache,
sender?: IMessageSender,
handler?: IMessageHandler,
logger?: Logger<ILogObj>,
bootRepository?: IBootRepository,
deviceModelRepository?: IDeviceModelRepository,
messageInfoRepository?: IMessageInfoRepository,
idGenerator?: IdGenerator,
) {
super(
config,
cache,
handler || new RabbitMqReceiver(config, logger),
sender || new RabbitMqSender(config, logger),
EventGroup.Configuration,
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._bootRepository =
bootRepository ||
new sequelize.SequelizeBootRepository(config, this._logger);
this._deviceModelRepository =
deviceModelRepository ||
new sequelize.SequelizeDeviceModelRepository(config, this._logger);
this._messageInfoRepository =
messageInfoRepository ||
new sequelize.SequelizeMessageInfoRepository(config, this._logger);
this._deviceModelService = new DeviceModelService(
this._deviceModelRepository,
);
this._bootService = new BootNotificationService(
this._bootRepository,
this._cache,
this._config.modules.configuration,
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 ConfigurationModule}.
*
* @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 {IBootRepository} [bootRepository] - An optional parameter of type {@link IBootRepository} which represents a repository for accessing and manipulating authorization data.
* If no `bootRepository` is provided, a default {@link SequelizeBootRepository} 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 {IMessageInfoRepository} [messageInfoRepository] - An optional parameter of type {@link messageInfoRepository} which
* represents a repository for accessing and manipulating variable data.
*
* @param {IdGenerator} [idGenerator] - An optional parameter of type {@link IdGenerator} which
* represents a generator for ids.
*
*If no `deviceModelRepository` is provided, a default {@link sequelize:messageInfoRepository} instance is created and used.
*/ | https://github.com/citrineos/citrineos-core/blob/462a009d9b7a2dabb8e9a55442654cdb39e672eb/03_Modules/Configuration/src/module/module.ts#L148-L205 | 462a009d9b7a2dabb8e9a55442654cdb39e672eb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.