Skip to content

Commit

Permalink
Merge pull request #20 from Cardinal-Cryptography/cmn-607_improve-log…
Browse files Browse the repository at this point in the history
…ging

CMN-607: Replace console.log with logging lib
  • Loading branch information
deuszx authored May 23, 2024
2 parents 66756a6 + 4e1b43a commit cb74e17
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 38 deletions.
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"graphql-request": "^6.1.0",
"graphql-ws": "^5.15.0",
"rxjs": "^7.8.1",
"tslog": "^4.9.2",
"ws": "^8.16.0"
}
}
4 changes: 3 additions & 1 deletion src/grapqhl/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Observable } from "rxjs";
import { Connection, ConnectionQuery } from "./connection";
import { SubscriptionQuery } from "./subscription";

import { log } from "../index";

/**
* Executes GraphQL connection query that iterates over the paginated results.
*
Expand Down Expand Up @@ -41,7 +43,7 @@ export async function readWholeConnection<T>(
}
}
} catch (err) {
console.error(err);
log.error(err);
break;
}
}
Expand Down
31 changes: 18 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,23 @@ import { graphqlSubscribe$, RawElement } from "./grapqhl";
import { poolsV2SubscriptionQuery as v2PoolSubscriptionQuery } from "./grapqhl/v2/queries";
import { poolsV2SubscriptionQuery as v1PoolSubscriptionQuery } from "./grapqhl/v1/queries";
import { setupPoolsV2OverWs } from "./servers/ws/amm";
import { UsdPriceCache } from "./services/usdPriceCache";
import { UsdPriceCache } from "./services/coingeckoPriceCache";
import { loadInitPoolReserves, poolsV2$ } from "./grapqhl/pools";
import { poolDataSample$ } from "./mocks/pools";
import { Pools } from "./models/pool";
import { merge, Observable, share } from "rxjs";
import { isV2GraphQLReservesError, isV1GraphQLReservesError } from "./utils";

import { Logger, ILogObj } from "tslog";

export const log: Logger<ILogObj> = new Logger({
prettyLogTemplate:
"{{logLevelName}}\t{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t[{{filePathWithLine}}{{name}}]\t",
});

async function main(): Promise<void> {
log.info("Starting Common API server");

const app = express();
app.use(
cors({
Expand All @@ -33,20 +42,16 @@ async function main(): Promise<void> {
const server = http.createServer(app);
const config = new Config();

console.log("Starting Common API server");

server.listen(config.http.port, () => {
console.log(
`HTTP server listening at http://localhost:${config.http.port}`,
);
log.info(`HTTP server listening at http://localhost:${config.http.port}`);
});

let pools = new Pools();
rest.poolsV2Endpoints(app, pools);
rest.healthcheckEnpoint(app, config);

if (config.enablePriceCache) {
console.log("USD price cache enabled");
log.info("USD price cache enabled");

const azeroUsdPriceCache = new UsdPriceCache(
"aleph-zero",
Expand Down Expand Up @@ -81,21 +86,21 @@ async function main(): Promise<void> {

if (config.enableDemoMode || config.enableGraphql) {
const wsServer = new WebSocketServer(config.ws, () => {
console.log(
log.info(
`WS server listening at ws://${config.ws.host}:${config.ws.port}`,
);
});

if (config.enableDemoMode) {
console.log("Running in demo mode");
log.info("Running in demo mode");
const source = poolDataSample$.pipe(share());
source.forEach((pool) => pools.update(pool));
setupPoolsV2OverWs(wsServer, source, pools);
} else if (config.enableGraphql) {
const graphqlClientUrl = `${config.graphql.proto}://${config.graphql.host}:${config.graphql.port}/graphql`;

console.log("Enabling updates over GraphQL/WS");
console.log(`Connecting Graphql client to ${graphqlClientUrl}`);
log.info("Enabling updates over GraphQL/WS");
log.info(`Connecting Graphql client to ${graphqlClientUrl}`);

const graphqlClient = createClient({
webSocketImpl: WebSocket,
Expand Down Expand Up @@ -139,7 +144,7 @@ async function main(): Promise<void> {
!isV2GraphQLReservesError(err) &&
!isV1GraphQLReservesError(err)
) {
console.error("Error updating pools", err);
log.error("Error updating pools", err);
Promise.reject(err);
}
});
Expand Down Expand Up @@ -171,7 +176,7 @@ async function main(): Promise<void> {
// );
}
} else {
console.log("Updates over GraphQL/WS are disabled.");
log.info("Updates over GraphQL/WS are disabled.");
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/servers/http/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TokenBalances } from "../../models/psp22";
import { UsdPriceCache } from "../../services/usdPriceCache";
import { UsdPriceCache } from "../../services/coingeckoPriceCache";
import { Pools } from "../../models/pool";
import express from "express";
import { Config } from "../../config";
Expand Down
23 changes: 12 additions & 11 deletions src/servers/ws/amm.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Observable } from "rxjs";
import { WebSocketServer } from "ws";
import { Pools, PoolV2 } from "../../models/pool";
import { log } from "../../index";

export function setupPoolsV2OverWs(
wssServer: WebSocketServer,
Expand All @@ -9,29 +10,29 @@ export function setupPoolsV2OverWs(
) {
wssServer.on("connection", (ws, request) => {
ws.send(JSON.stringify(Object.fromEntries(knownState.pools)), (error) => {
if (error) {
console.log("error sending known state", error);
}
log.error("error sending known state", error);
});

const subscription = pools.subscribe((pool) => {
ws.send(JSON.stringify(pool), function (err) {
console.error(`Error when sending data to the client over WS: ${err}`);
ws.send(JSON.stringify(pool), (error) => {
log.error("error when sending data to the client over WS", error);
});
});

console.log("started feeding new client the pools events");
log.trace("started feeding new client the pools events");

ws.on("error", console.error);
ws.on("error", (error) => {
log.error("error on the websocket connection", error);
});

ws.on("message", function (message) {
console.log(
`Received message ${message} from user ${JSON.stringify(request)}`,
ws.on("message", (message) => {
log.trace(
`received message ${message} from user ${JSON.stringify(request)}`,
);
});

ws.on("close", function () {
console.log("stopping client subscription");
log.info("stopping client subscription");
subscription.unsubscribe();
});
});
Expand Down
19 changes: 10 additions & 9 deletions src/servers/ws/nativeTransfers.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
import { Observable } from "rxjs";
import { WebSocketServer } from "ws";
import { NativeTransfer } from "../../models/nativeTransfer";
import { log } from "../../index";

export function setupNativeTransfersOverWss(
wssServer: WebSocketServer,
nativeTransfers: Observable<NativeTransfer>,
) {
wssServer.on("connection", (ws, request) => {
const subscription = nativeTransfers.subscribe((transfer) => {
ws.send(JSON.stringify(transfer), function () {
//
// Ignore errors.
//
ws.send(JSON.stringify(transfer), (error) => {
log.error("error sending known state", error);
});
});
console.log("started feeding new client the nativeTransfers events");
log.trace("started feeding new client the nativeTransfers events");

ws.on("error", console.error);
ws.on("error", (error) => {
log.error("error on the websocket connection", error);
});

ws.on("message", function (message) {
console.log(
ws.on("message", (message) => {
log.trace(
`Received message ${message} from user ${JSON.stringify(request)}`,
);
});

ws.on("close", function () {
console.log("stopping client subscription");
log.info("stopping client subscription");
subscription.unsubscribe();
});
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import axios from "axios";

import { UsdTokenPrice } from "../models/usdTokenPrice";
import { log } from "../index";

export class UsdPriceCache {
ticker: string;
Expand Down Expand Up @@ -34,13 +35,13 @@ export class UsdPriceCache {
lastUpdateTimestampSeconds: this.lastUpdateTimestampSeconds,
};
} else if (response.status == 429) {
console.log("Rate limited, returning cached price");
log.warn("Rate limited, returning cached price");
return {
price: this.price,
lastUpdateTimestampSeconds: this.lastUpdateTimestampSeconds,
};
} else {
console.error(
log.error(
`Unhandled status when fetching ${this.ticker} price`,
response,
);
Expand All @@ -50,7 +51,7 @@ export class UsdPriceCache {
};
}
} catch (e) {
console.error(`Error fetching ${this.ticker} price`, e);
log.warn(`Error fetching ticker's price`, {ticker: this.ticker, error: e});
return {
price: this.price,
lastUpdateTimestampSeconds: this.lastUpdateTimestampSeconds,
Expand Down

0 comments on commit cb74e17

Please sign in to comment.