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

Add healthcheck #88

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,9 @@ npm run test
```
npm run lint
```

### HealthCheck

```
/.well-known/apollo/server-health
```
9 changes: 9 additions & 0 deletions src/block-watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ class BlockWatcher {
private _lastBlockHeight!: number;
private _timer!: NodeJS.Timeout;

private _healthy: boolean;

constructor() {
this._callbacks = [];
this._lastBlockHeight = 0;
this._healthy = true;
}

public onNewBlock(callback: (height?: number) => void): BlockWatcher {
Expand Down Expand Up @@ -45,6 +48,7 @@ class BlockWatcher {
repository
.getMaxHeight()
.then((height) => {
this._healthy = true;
if (!height || this._lastBlockHeight >= height) {
return;
}
Expand All @@ -57,10 +61,15 @@ class BlockWatcher {
this._notify(height);
})
.catch((e) => {
this._healthy = true;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't it be false?

this._notify();
console.error(e);
});
}

public isHealthy(): boolean {
return this._healthy;
}
}

export const blockWatcher = new BlockWatcher();
6 changes: 6 additions & 0 deletions src/context/database-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { TokenRepository } from "./token-repository";
import { BlocksRepository } from "./blocks-repository";

export class DatabaseContext {
private dataSource: DataSource;
public readonly transactions!: TransactionRepository;
public readonly blockInfo!: BlocksRepository;
public readonly boxes!: BoxRepository;
Expand All @@ -28,6 +29,7 @@ export class DatabaseContext {
public readonly unconfirmedInputs!: UnconfirmedInputRepository;

constructor(dataSource: DataSource) {
this.dataSource = dataSource;
const context: RepositoryDataContext = {
dataSource,
graphQLDataLoader: new GraphQLDatabaseLoader(dataSource, { disableCache: true })
Expand All @@ -48,4 +50,8 @@ export class DatabaseContext {
this.dataInputs = new BaseRepository(DataInputEntity, "dti", { context, defaults });
this.inputs = new BaseRepository(InputEntity, "input", { context, defaults });
}

checkConnection = () => {
return this.dataSource.isInitialized;
};
}
31 changes: 31 additions & 0 deletions src/health-check.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { blockWatcher } from "./block-watcher";
import { redisClient } from "./caching";
import { DatabaseContext } from "./context/database-context";
import { nodeService } from "./services";

export const checkHealth = async (dataContext: DatabaseContext): Promise<void> => {
const checks = {
db: () => () => dataContext.checkConnection,
redis: async () => (await redisClient.mget("test")).length === 1,
node: async () => (await nodeService.getNodeInfo()).status === 200,
blockWatcher: () => blockWatcher.isHealthy()
};

const results = await Promise.all(
Object.entries(checks).map(async ([key, func]) => ({
[key]: await func()
}))
);

let isAnyFailed = false;
for (const result of results) {
for (const [key, value] of Object.entries(result)) {
if (!value) {
console.error(`🚫 ${key} is not healthy.`);
isAnyFailed = true;
}
}
}

if (isAnyFailed) throw new Error("Service is unhealthy.");
};
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { DatabaseContext } from "./context/database-context";
import { initializeDataSource } from "./data-source";
import { generateSchema } from "./graphql/schema";
import { nodeService } from "./services";
import { checkHealth } from "./health-check";

const { TS_NODE_DEV, MAX_QUERY_DEPTH } = process.env;

Expand Down Expand Up @@ -55,7 +56,8 @@ async function startServer(schema: GraphQLSchema, dataContext: DatabaseContext)
}
}
)
]
],
onHealthCheck: checkHealth.bind(null, dataContext)
});
const { url } = await server.listen({ port: 3000 });
console.log(`🚀 Server ready at ${url}`);
Expand Down
Loading