Skip to content

Commit

Permalink
fix(start.cjs): use start.cjs for runnable service
Browse files Browse the repository at this point in the history
  • Loading branch information
Gerald Baulig committed Feb 23, 2024
1 parent 67555c5 commit 73f5358
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 34 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"typescript": "^5.3.3"
},
"scripts": {
"start": "node lib/start.js",
"start": "node ./lib/start.cjs",
"dev": "cross-env NODE_ENV=development nodemon --watch './src/**/*.ts' --exec node --loader ts-node/esm ./src/start.ts",
"tsctests": "tsc -d -p tsconfig.test.json",
"test": "npm run lint && c8 --reporter=text npm run mocha",
Expand All @@ -66,9 +66,9 @@
"mochadebug": "cross-env NODE_ENV=test; mocha -R spec ./test/*.js --full-trace --inspect-brk",
"lcov-report": "c8 report --reporter=lcov",
"coveralls": "c8 report --reporter=text-lcov | coveralls",
"build:tsc": "esbuild ./src/start.ts --bundle --platform=node --outfile=lib/start.js --minify --tree-shaking=true --sourcemap=inline",
"build:es": "esbuild ./src/start.ts --bundle --platform=node --outfile=lib/start.cjs --minify --tree-shaking=true --sourcemap=inline",
"build:clean": "rimraf lib",
"build": "npm-run-all lint build:clean build:tsc"
"build": "npm-run-all lint build:clean build:es"
},
"engines": {
"node": ">= 20.8.0"
Expand Down
24 changes: 12 additions & 12 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export const getSubTreeOrgs = async (

for (let i = 0; i < traversalResponse.length; i++) {
let targetID = traversalResponse[i].id;
const subOrgs = traversalResponse.filter(e => e.parent_id === targetID);
const subOrgs = traversalResponse.filter((e: any) => e.parent_id === targetID);
// find hrScopes id and then get the childer object
const filteredSubOrgFields = [];
for (let org of subOrgs) {
Expand All @@ -243,27 +243,27 @@ export const createHRScope = async (
user: UserResponse,
token: string,
graphClient: GraphClient,
cache,
cfg,
logger
): Promise<ResolvedSubject> => {
cache: any,
cfg: any,
logger: any,
): Promise<ResolvedSubject | undefined> => {
const subject = user?.payload as ResolvedSubject;
const roleScopingEntityURN = cfg.get('authorization:urns:roleScopingEntity');
const roleScopingInstanceURN = cfg.get('authorization:urns:roleScopingInstance');
if (subject?.role_associations && !subject?.hierarchical_scopes?.length) {
// create HR scopes iterating through the user's assigned role scoping instances
let userRoleAssocs = subject.role_associations;
let assignedUserScopes = new Set<{ userScope: string; role: string }>();
let assignedUserScopes = new Set<{ userScope: string | undefined; role: string | undefined }>();
let tokenData;
// verify the validity of subject tokens
if (token && user?.payload?.tokens?.length > 0) {
for (let tokenInfo of user.payload.tokens) {
if (token && user?.payload?.tokens?.length! > 0) {
for (let tokenInfo of user?.payload?.tokens ?? []) {
if (tokenInfo.token === token) {
tokenData = tokenInfo;
const expiresIn = tokenInfo.expires_in;
if (expiresIn && expiresIn != new Date(0) && expiresIn < new Date()) {
logger.info(`Token name ${tokenInfo.name} has expired`);
return;
return undefined;
}
}
}
Expand All @@ -276,10 +276,10 @@ export const createHRScope = async (
) ?? userRoleAssocs;

for (let roleObj of reducedUserRoleAssocs) {
if (roleObj?.attributes?.length > 0) {
for (let roleAttribute of roleObj?.attributes) {
if (roleObj?.attributes?.length! > 0) {
for (let roleAttribute of roleObj?.attributes!) {
if (roleAttribute.id === roleScopingEntityURN) {
for (let roleScopInstObj of roleAttribute.attributes) {
for (let roleScopInstObj of roleAttribute.attributes!) {
if (roleScopInstObj.id === roleScopingInstanceURN) {
let obj = { userScope: roleScopInstObj.value, role: roleObj.role };
assignedUserScopes.add(obj);
Expand Down
41 changes: 22 additions & 19 deletions src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
Server,
Health
} from '@restorecommerce/chassis-srv';
import { ResourceService } from './service.js';
import { Logger } from 'winston';
import { createLogger } from '@restorecommerce/logger';
import { createServiceConfig } from '@restorecommerce/service-config';
Expand Down Expand Up @@ -102,6 +101,7 @@ import {
import { BindConfig } from '@restorecommerce/chassis-srv/lib/microservice/transport/provider/grpc/index.js';
import { protoMetadata as hierarchicalScopesMeta } from '@restorecommerce/rc-grpc-clients/dist/generated-server/io/restorecommerce/auth.js';
import { UserServiceClient } from '@restorecommerce/rc-grpc-clients/dist/generated-server/io/restorecommerce/user.js';
import { ResourceService } from './service.js';
import { getUserServiceClient, getGraphServiceClient, createHRScope } from './utils.js';

const COMMANDEVENTS = [
Expand Down Expand Up @@ -160,15 +160,15 @@ const ServiceDefinitions: any = [
];

export class Worker {
server: Server;
events: Events;
logger: Logger;
server: Server | undefined = undefined;
events: Events | undefined = undefined;
logger: Logger | undefined = undefined;
redisClient: any;
offsetStore: OffsetStore;
cis: CommandInterface;
service: any[];
idsClient: UserServiceClient;
graphClient: GraphServiceClient;
offsetStore: OffsetStore | undefined = undefined;
cis: CommandInterface | undefined = undefined;
service: any[] | undefined = undefined;
idsClient: UserServiceClient | undefined = undefined;
graphClient: GraphServiceClient | undefined = undefined;

async start(cfg?: any, resourcesServiceEventListener?: Function) {
// Load config
Expand Down Expand Up @@ -219,7 +219,7 @@ export class Worker {
cfg.set('events:kafka', kafkaCfg);

const loggerCfg = cfg.get('logger');
loggerCfg.esTransformer = (msg) => {
loggerCfg.esTransformer = (msg: any) => {
msg.fields = JSON.stringify(msg.fields);
return msg;
};
Expand All @@ -232,14 +232,17 @@ export class Worker {

await events.start();
this.offsetStore = new OffsetStore(events, cfg, logger);
let redisClient: RedisClientType<any, any>;
let redisClient: RedisClientType<any, any> | undefined;
if (cfg.get('redis')) {
const redisConfig = cfg.get('redis');
redisConfig.database = cfg.get('redis:db-indexes:db-resourcesCounter');
redisClient = createClient(redisConfig);
redisClient.on('error', (err) => logger.error('Redis Client Error', err));
await redisClient.connect();
}
else {
redisClient = undefined;
}
const fieldGeneratorConfig: any = cfg.get('fieldHandlers:fieldGenerators');
const bufferHandlerConfig: any = cfg.get('fieldHandlers:bufferFields');
const requiredFieldsConfig: any = cfg.get('fieldHandlers:requiredFields');
Expand Down Expand Up @@ -303,7 +306,7 @@ export class Worker {
// TODO provide typing on ResourceService<T, M>
this.service[resourceName] = new ResourceService(resourceName,
resourceEvents, cfg, logger, resourceAPI, isEventsEnabled, authZ, redisClientSubject);
const resourceServiceDefinition = ServiceDefinitions.filter((obj) => obj.fullName.split('.')[2] === resourceName);
const resourceServiceDefinition = ServiceDefinitions.filter((obj: any) => obj.fullName.split('.')[2] === resourceName);
// todo add bindConfig typing
await server.bind(`${resourcesServiceConfigPrefix}${resourceName}-srv`, {
service: resourceServiceDefinition[0],
Expand Down Expand Up @@ -343,12 +346,12 @@ export class Worker {
const token = msg.token?.split(':')?.[0] as string;
const user = token ? await this.idsClient?.findByToken({ token }) : undefined;
if (!user?.payload?.id) {
this.logger.debug('Subject could not be resolved for token');
this.logger?.debug('Subject could not be resolved for token');
}
const subject: ResolvedSubject = user?.payload?.id ? await createHRScope(user, token, this.graphClient, null, cfg, this.logger) : undefined;
const subject: ResolvedSubject = user?.payload?.id ? await createHRScope(user, token, this.graphClient!, null, cfg, this.logger) : undefined;
if (hrTopic) {
// emit response with same messag id on same topic
this.logger.info(`Hierarchical scopes are created for subject ${user?.payload?.id}`);
this.logger?.info(`Hierarchical scopes are created for subject ${user?.payload?.id}`);
await hrTopic.emit('hierarchicalScopesResponse', {
subject_id: user?.payload?.id,
token: msg.token,
Expand Down Expand Up @@ -426,9 +429,9 @@ export class Worker {
}

async stop() {
this.logger.info('Shutting down');
await this.server.stop();
await this.events.stop();
await this.offsetStore.stop();
this.logger?.info('Shutting down');
await this.server?.stop();
await this.events?.stop();
await this.offsetStore?.stop();
}
}

0 comments on commit 73f5358

Please sign in to comment.