Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Porting first batch of commands and queries to new framework #6790

Merged
merged 22 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
464 changes: 464 additions & 0 deletions .dependency-cruiser.js

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ node_modules/
*.postgres
*.rabbitmq
redis-data
**/.nyc_output
**/.nyc_output
**/dependency-graph.svg
17 changes: 11 additions & 6 deletions libs/adapters/src/express/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
AnalyticsOptions,
INVALID_ACTOR_ERROR,
INVALID_INPUT_ERROR,
User,
analytics,
stats,
} from '@hicommonwealth/core';
Expand Down Expand Up @@ -70,17 +71,21 @@ export const errorMiddleware = (
* Captures analytics
*/
export function analyticsMiddleware<T>(
event: any,
transformer: (payload: T) => AnalyticsOptions,
event: string,
transformer?: (results?: T) => AnalyticsOptions,
) {
return (req: Request, res: Response, next: NextFunction) => {
return (req: Request<{ id: string }>, res: Response, next: NextFunction) => {
try {
// override res.json
const originalResJson = res.json;

res.json = function (data: T) {
analytics().track(event, transformer(data));
return originalResJson.call(res, data);
res.json = function (results: T) {
analytics().track(event, {
userId: (req.user as User).id,
aggregateId: req.params.id,
...(transformer ? transformer(results) : {}),
});
return originalResJson.call(res, results);
};
} catch (err: unknown) {
console.error(err); // don't use logger port here
Expand Down
2 changes: 1 addition & 1 deletion libs/adapters/src/mixpanel/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const MixpanelAnalytics = (): Analytics => {
}

return {
name: 'mixpanel-analytics',
name: 'MixpanelAnalytics',
dispose: async () => {},
track: (event: string, payload: AnalyticsOptions) => {
try {
Expand Down
12 changes: 6 additions & 6 deletions libs/core/src/framework/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ export type QueryHandler<T, P extends ZodSchema> = (
* - `body`: function implementing core domain logic, and returning side effects (mutations)
*/
export type CommandMetadata<T, P extends ZodSchema> = {
schema: P;
auth: CommandHandler<T, P>[];
body: CommandHandler<T, P>;
readonly schema: P;
readonly auth: CommandHandler<T, P>[];
readonly body: CommandHandler<T, P>;
Rotorsoft marked this conversation as resolved.
Show resolved Hide resolved
};

/**
Expand All @@ -135,7 +135,7 @@ export type CommandMetadata<T, P extends ZodSchema> = {
* - `body`: function implementing the query logic
*/
export type QueryMetadata<T, P extends ZodSchema> = {
schema: P;
auth: QueryHandler<T, P>[];
body: QueryHandler<T, P>;
readonly schema: P;
readonly auth: QueryHandler<T, P>[];
readonly body: QueryHandler<T, P>;
};
46 changes: 46 additions & 0 deletions libs/core/src/ports/in-memory-logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Logger } from './interfaces';

const devLogger: Logger = {
name: 'in-memory-logger',
dispose: () => Promise.resolve(),
getLogger: () => ({
trace(msg: string) {
console.log(msg);
},
debug(msg: string) {
console.log(msg);
},
info(msg: string) {
console.log(msg);
},
warn(msg: string) {
console.log(msg);
},
error(msg: string, error?: Error) {
console.error(msg, error?.message);
},
fatal(msg: string, error?: Error) {
console.error(msg, error?.message);
},
}),
};

const testLogger: Logger = {
name: 'in-memory-logger',
dispose: () => Promise.resolve(),
getLogger: () => ({
trace() {},
debug() {},
info() {},
warn() {},
error(msg: string, error?: Error) {
console.error(msg, error?.message);
},
fatal(msg: string, error?: Error) {
console.error(msg, error?.message);
},
}),
};

export const getInMemoryLogger = () =>
process.env.NODE_ENV === 'test' ? testLogger : devLogger;
94 changes: 0 additions & 94 deletions libs/core/src/ports/index.ts
Original file line number Diff line number Diff line change
@@ -1,97 +1,3 @@
import { Analytics, Cache, Logger, Stats } from './interfaces';
import { port } from './port';

export * from './enums';
export * from './interfaces';
export * from './port';

/**
* Logger port factory
*/
export const logger = port(function logger(logger?: Logger) {
return (
logger || {
name: 'in-memory-logger',
dispose: () => Promise.resolve(),
getLogger: () => ({
trace(msg: string) {
console.log(msg);
},
debug(msg: string) {
console.log(msg);
},
info(msg: string) {
console.log(msg);
},
warn(msg: string) {
console.log(msg);
},
error(msg: string, error?: Error) {
console.error(msg, error?.message);
},
fatal(msg: string, error?: Error) {
console.error(msg, error?.message);
},
}),
}
);
});

/**
* Stats port factory
*/
export const stats = port(function stats(stats?: Stats) {
return (
stats || {
name: 'in-memory-stats',
dispose: () => Promise.resolve(),
histogram: () => {},
set: () => {},
increment: () => {},
incrementBy: () => {},
decrement: () => {},
decrementBy: () => {},
on: () => {},
off: () => {},
timing: () => {},
}
);
});

/**
* Cache port factory
*/
export const cache = port(function cache(cache?: Cache) {
return (
cache || {
name: 'in-memory-cache',
dispose: () => Promise.resolve(),
getKey: () => Promise.resolve(''),
setKey: () => Promise.resolve(false),
getKeys: () => Promise.resolve(false),
setKeys: () => Promise.resolve(false),
getNamespaceKeys: () => Promise.resolve(false),
deleteKey: () => Promise.resolve(0),
deleteNamespaceKeys: () => Promise.resolve(0),
flushAll: () => Promise.resolve(),
incrementKey: () => Promise.resolve(0),
decrementKey: () => Promise.resolve(0),
getKeyTTL: () => Promise.resolve(0),
setKeyTTL: () => Promise.resolve(false),
}
);
});

/**
* Analytics port factory
*/

export const analytics = port(function analytics(analytics?: Analytics) {
return (
analytics || {
name: 'in-memory-analytics',
dispose: () => Promise.resolve(),
track: () => {},
}
);
});
97 changes: 90 additions & 7 deletions libs/core/src/ports/port.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { ExitCode } from './enums';
import { AdapterFactory, Disposable, Disposer } from './interfaces';
import { getInMemoryLogger } from './in-memory-logger';
import {
AdapterFactory,
Analytics,
Cache,
Disposable,
Disposer,
Logger,
Stats,
} from './interfaces';

/**
* Map of disposable adapter instances
Expand All @@ -16,7 +25,9 @@ export function port<T extends Disposable>(factory: AdapterFactory<T>) {
if (!adapters.has(factory.name)) {
const instance = factory(adapter);
adapters.set(factory.name, instance);
console.log('[binding adapter]', instance.name || factory.name);
logger()
.getLogger('ports')
.info(`[binding adapter] ${instance.name || factory.name}`);
return instance;
}
return adapters.get(factory.name) as T;
Expand All @@ -40,7 +51,9 @@ const disposeAndExit = async (code: ExitCode = 'UNIT_TEST'): Promise<void> => {
await Promise.all(disposers.map((disposer) => disposer()));
await Promise.all(
[...adapters].reverse().map(async ([key, adapter]) => {
console.log('[disposing adapter]', adapter.name || key);
logger()
.getLogger('ports')
.info(`[disposing adapter] ${adapter.name || key}`);
await adapter.dispose();
}),
);
Expand All @@ -66,18 +79,88 @@ export const dispose = (
* Handlers to dispose registered resources on exit or unhandled exceptions
*/
process.once('SIGINT', async (arg?: any) => {
console.log('SIGINT', arg !== 'SIGINT' ? arg : '');
logger()
.getLogger('ports')
.info(`SIGINT ${arg !== 'SIGINT' ? arg : ''}`);
await disposeAndExit('EXIT');
});
process.once('SIGTERM', async (arg?: any) => {
console.log('SIGTERM', arg !== 'SIGTERM' ? arg : '');
logger()
.getLogger('ports')
.info(`SIGTERM ${arg !== 'SIGTERM' ? arg : ''}`);
await disposeAndExit('EXIT');
});
process.once('uncaughtException', async (arg?: any) => {
console.error('Uncaught Exception', arg);
logger().getLogger('ports').error('Uncaught Exception', arg);
await disposeAndExit('ERROR');
});
process.once('unhandledRejection', async (arg?: any) => {
console.error('Unhandled Rejection', arg);
logger().getLogger('ports').error('Unhandled Rejection', arg);
await disposeAndExit('ERROR');
});

/**
* Logger port factory
*/
export const logger = port(function logger(logger?: Logger) {
return logger || getInMemoryLogger();
});

/**
* Stats port factory
*/
export const stats = port(function stats(stats?: Stats) {
return (
stats || {
name: 'in-memory-stats',
dispose: () => Promise.resolve(),
histogram: () => {},
set: () => {},
increment: () => {},
incrementBy: () => {},
decrement: () => {},
decrementBy: () => {},
on: () => {},
off: () => {},
timing: () => {},
}
);
});

/**
* Cache port factory
*/
export const cache = port(function cache(cache?: Cache) {
return (
cache || {
name: 'in-memory-cache',
dispose: () => Promise.resolve(),
getKey: () => Promise.resolve(''),
setKey: () => Promise.resolve(false),
getKeys: () => Promise.resolve(false),
setKeys: () => Promise.resolve(false),
getNamespaceKeys: () => Promise.resolve(false),
deleteKey: () => Promise.resolve(0),
deleteNamespaceKeys: () => Promise.resolve(0),
flushAll: () => Promise.resolve(),
incrementKey: () => Promise.resolve(0),
decrementKey: () => Promise.resolve(0),
getKeyTTL: () => Promise.resolve(0),
setKeyTTL: () => Promise.resolve(false),
}
);
});

/**
* Analytics port factory
*/

export const analytics = port(function analytics(analytics?: Analytics) {
return (
analytics || {
name: 'in-memory-analytics',
dispose: () => Promise.resolve(),
track: () => {},
}
);
});
Loading
Loading