|
| 1 | +import {GristServer} from 'app/server/lib/GristServer'; |
| 2 | +import log from 'app/server/lib/log'; |
| 3 | +import {createPubSubManager, IPubSubManager} from 'app/server/lib/PubSubManager'; |
| 4 | +import * as shutdown from 'app/server/lib/shutdown'; |
| 5 | + |
| 6 | +import {v4 as uuidv4} from 'uuid'; |
| 7 | + |
| 8 | +// Not to be confused with health checks from the frontend, these |
| 9 | +// request/response pairs are internal checks between Grist instances |
| 10 | +// in multi-server environments |
| 11 | +interface ServerHealthcheckRequest { |
| 12 | + id: string; |
| 13 | + checkReady: boolean; |
| 14 | +} |
| 15 | +interface ServerHealthcheckResponse { |
| 16 | + instanceId: string; |
| 17 | + requestId: string; |
| 18 | + healthy: boolean; |
| 19 | +} |
| 20 | + |
| 21 | +// For keeping track of pending health checks for all other servers |
| 22 | +// for each request that was broadcast to all of them. |
| 23 | +interface PendingServerHealthCheck { |
| 24 | + expectedCount: number; |
| 25 | + responses: Record<string, boolean>; |
| 26 | + resolve: (res: boolean) => void; |
| 27 | + reject: (err: Error) => void; |
| 28 | + timeout: NodeJS.Timeout; |
| 29 | +} |
| 30 | + |
| 31 | +export class HealthChecker { |
| 32 | + private _pendingServerHealthChecks: Map<string, PendingServerHealthCheck>; |
| 33 | + private _serverInstanceID: string; |
| 34 | + private _pubSubManager: IPubSubManager; |
| 35 | + |
| 36 | + constructor( |
| 37 | + private _server: GristServer |
| 38 | + ) { |
| 39 | + this._pubSubManager = createPubSubManager(process.env.REDIS_URL); |
| 40 | + this._pendingServerHealthChecks = new Map<string, PendingServerHealthCheck>(); |
| 41 | + this._serverInstanceID = process.env.GRIST_INSTANCE_ID || `testInsanceId_${this._server.getHost()}`; |
| 42 | + this._pubSubManager.getClient()?.sadd('grist-instances', this._serverInstanceID).catch((err) => { |
| 43 | + log.error('Failed to contact redis', err); |
| 44 | + }); |
| 45 | + this._subscribeToChannels(); |
| 46 | + |
| 47 | + // Make sure we clean up our Redis mess, if any, even if we exit |
| 48 | + // by signal. |
| 49 | + shutdown.addCleanupHandler(null, () => this.close()); |
| 50 | + } |
| 51 | + |
| 52 | + public async allServersOkay(timeout: number) { |
| 53 | + const requestId = uuidv4(); |
| 54 | + const client = this._pubSubManager.getClient(); |
| 55 | + |
| 56 | + // If there is no Redis, then our current instance is the only instance |
| 57 | + const allInstances = await client?.smembers('grist-instances') || [this._serverInstanceID]; |
| 58 | + |
| 59 | + const allInstancesPromise: Promise<boolean> = new Promise((resolve, reject) => { |
| 60 | + const allInstancesTimeout = setTimeout(() => { |
| 61 | + log.warn('allServersOkay: timeout waiting for responses'); |
| 62 | + reject(new Error('Timeout waiting for health responses')); |
| 63 | + this._pendingServerHealthChecks.delete(requestId); |
| 64 | + }, timeout); |
| 65 | + |
| 66 | + this._pendingServerHealthChecks.set(requestId, { |
| 67 | + responses: {}, |
| 68 | + expectedCount: allInstances.length, |
| 69 | + resolve, |
| 70 | + reject, |
| 71 | + timeout: allInstancesTimeout, |
| 72 | + }); |
| 73 | + }); |
| 74 | + const request: ServerHealthcheckRequest = { |
| 75 | + id: requestId, |
| 76 | + checkReady: true |
| 77 | + }; |
| 78 | + await this._pubSubManager.publish('healthcheck:requests', JSON.stringify(request)); |
| 79 | + return allInstancesPromise; |
| 80 | + } |
| 81 | + |
| 82 | + public async close() { |
| 83 | + await this._pubSubManager.getClient()?.srem('grist-instances', [this._serverInstanceID]); |
| 84 | + await this._pubSubManager.close(); |
| 85 | + } |
| 86 | + |
| 87 | + private _subscribeToChannels() { |
| 88 | + this._pubSubManager.subscribe('healthcheck:requests', async (message) => { |
| 89 | + const request: ServerHealthcheckRequest = JSON.parse(message); |
| 90 | + const response: ServerHealthcheckResponse = { |
| 91 | + instanceId: this._serverInstanceID|| '', |
| 92 | + requestId: request.id, |
| 93 | + healthy: !request.checkReady || this._server.ready, |
| 94 | + }; |
| 95 | + log.debug('allServersOkay request', response); |
| 96 | + await this._pubSubManager.publish('healthcheck:responses', JSON.stringify(response)); |
| 97 | + }); |
| 98 | + |
| 99 | + this._pubSubManager.subscribe('healthcheck:responses', (message) => { |
| 100 | + const response: ServerHealthcheckResponse = JSON.parse(message); |
| 101 | + const pending = this._pendingServerHealthChecks.get(response.requestId); |
| 102 | + if (!pending) { |
| 103 | + // This instance didn't broadcast a health check request with |
| 104 | + // this requestId, so nothing to do. |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + pending.responses[response.instanceId] = response.healthy; |
| 109 | + log.debug( |
| 110 | + `allServersOkay cleared pending response on ${this._serverInstanceID} for ${response.instanceId}` |
| 111 | + ); |
| 112 | + |
| 113 | + if (Object.keys(pending.responses).length === pending.expectedCount) { |
| 114 | + // All servers have replied. Make it known and clean up. |
| 115 | + clearTimeout(pending.timeout); |
| 116 | + pending.resolve(Object.values(pending.responses).every(e => e)); |
| 117 | + this._pendingServerHealthChecks.delete(response.requestId); |
| 118 | + } |
| 119 | + }); |
| 120 | + } |
| 121 | +} |
0 commit comments