@lokalise/healthcheck-utils 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,12 @@
1
- import { AbstractPeriodicJob, type PeriodicJobDependencies } from './AbstractPeriodicJob';
1
+ import { AbstractPeriodicJob, type JobExecutionContext, type PeriodicJobDependencies } from '@lokalise/background-jobs-common';
2
2
  import type { Healthcheck } from './healthchecks.js';
3
+ export type HealthcheckRefreshJobConfig = {
4
+ intervalInMs?: number;
5
+ shouldLogExecution?: boolean;
6
+ };
3
7
  export declare class HealthcheckRefreshJob extends AbstractPeriodicJob {
4
8
  static JOB_NAME: string;
5
9
  private readonly healthCheckers;
6
- constructor(dependencies: PeriodicJobDependencies, healthchecks: readonly Healthcheck[]);
7
- protected processInternal(_executionUuid: string): Promise<unknown>;
10
+ constructor(dependencies: PeriodicJobDependencies, healthchecks: readonly Healthcheck[], config?: HealthcheckRefreshJobConfig);
11
+ protected processInternal(_executionUuid: JobExecutionContext): Promise<unknown>;
8
12
  }
@@ -1,15 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HealthcheckRefreshJob = void 0;
4
+ const background_jobs_common_1 = require("@lokalise/background-jobs-common");
4
5
  const promise_pool_1 = require("@supercharge/promise-pool");
5
- const AbstractPeriodicJob_1 = require("./AbstractPeriodicJob");
6
- class HealthcheckRefreshJob extends AbstractPeriodicJob_1.AbstractPeriodicJob {
6
+ class HealthcheckRefreshJob extends background_jobs_common_1.AbstractPeriodicJob {
7
7
  static JOB_NAME = 'HealthcheckRefreshJob';
8
8
  healthCheckers;
9
- constructor(dependencies, healthchecks) {
9
+ constructor(dependencies, healthchecks, config) {
10
10
  super({
11
11
  jobId: HealthcheckRefreshJob.JOB_NAME,
12
- intervalInMs: 15000,
12
+ schedule: {
13
+ intervalInMs: config?.intervalInMs ?? 15000,
14
+ },
15
+ shouldLogExecution: config?.shouldLogExecution ?? false,
13
16
  singleConsumerMode: {
14
17
  enabled: false,
15
18
  },
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
- export * from './healthchecks';
2
- export * from './HealthcheckResultsStore';
3
- export * from './HealthcheckRefreshJob';
1
+ export type { Healthcheck, HealthcheckDependencies } from './healthchecks';
2
+ export { HealthcheckResultsStore } from './HealthcheckResultsStore';
3
+ export type { HealthcheckResultsStoreParams, HealthcheckEntry } from './HealthcheckResultsStore';
4
+ export { AbstractHealthcheck } from './healthchecks';
5
+ export { HealthcheckRefreshJob, type HealthcheckRefreshJobConfig } from './HealthcheckRefreshJob';
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./healthchecks"), exports);
5
- tslib_1.__exportStar(require("./HealthcheckResultsStore"), exports);
6
- tslib_1.__exportStar(require("./HealthcheckRefreshJob"), exports);
3
+ exports.HealthcheckRefreshJob = exports.AbstractHealthcheck = exports.HealthcheckResultsStore = void 0;
4
+ var HealthcheckResultsStore_1 = require("./HealthcheckResultsStore");
5
+ Object.defineProperty(exports, "HealthcheckResultsStore", { enumerable: true, get: function () { return HealthcheckResultsStore_1.HealthcheckResultsStore; } });
6
+ var healthchecks_1 = require("./healthchecks");
7
+ Object.defineProperty(exports, "AbstractHealthcheck", { enumerable: true, get: function () { return healthchecks_1.AbstractHealthcheck; } });
8
+ var HealthcheckRefreshJob_1 = require("./HealthcheckRefreshJob");
9
+ Object.defineProperty(exports, "HealthcheckRefreshJob", { enumerable: true, get: function () { return HealthcheckRefreshJob_1.HealthcheckRefreshJob; } });
package/package.json CHANGED
@@ -1,12 +1,8 @@
1
1
  {
2
2
  "name": "@lokalise/healthcheck-utils",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "license": "Apache-2.0",
5
- "files": [
6
- "dist/**",
7
- "LICENSE.md",
8
- "README.md"
9
- ],
5
+ "files": ["dist/**", "LICENSE.md", "README.md"],
10
6
  "type": "commonjs",
11
7
  "main": "./dist/index.js",
12
8
  "types": "./dist/index.d.ts",
@@ -26,7 +22,8 @@
26
22
  "test:ci": "npm run test",
27
23
  "test:ci:teardown": "docker compose down",
28
24
  "prepublishOnly": "npm run build",
29
- "package-version": "echo $npm_package_version"
25
+ "package-version": "echo $npm_package_version",
26
+ "postversion": "biome check --write package.json"
30
27
  },
31
28
  "dependencies": {
32
29
  "@lokalise/node-core": "^11.2.0",
@@ -35,22 +32,24 @@
35
32
  "toad-cache": "^3.7.0"
36
33
  },
37
34
  "peerDependencies": {
35
+ "@lokalise/background-jobs-common": ">=6.0.0",
38
36
  "ioredis": "^5.4.1",
39
37
  "prom-client": "^15.1.3",
40
38
  "toad-scheduler": "^3.0.1"
41
39
  },
42
40
  "devDependencies": {
43
41
  "@biomejs/biome": "^1.8.3",
44
- "@lokalise/biome-config": "^1.2.2",
42
+ "@lokalise/background-jobs-common": "^6.0.0",
43
+ "@lokalise/biome-config": "^1.3.0",
45
44
  "@lokalise/node-core": "^11.2.0",
46
45
  "@lokalise/package-vite-config": "latest",
47
- "@vitest/coverage-v8": "^2.0.4",
46
+ "@vitest/coverage-v8": "^2.0.5",
48
47
  "ioredis": "^5.4.1",
49
48
  "prom-client": "^15.1.3",
50
49
  "rimraf": "^6.0.1",
51
50
  "toad-scheduler": "^3.0.1",
52
51
  "typescript": "5.5.4",
53
- "vite": "5.3.5",
54
- "vitest": "^2.0.4"
52
+ "vite": "5.4.0",
53
+ "vitest": "^2.0.5"
55
54
  }
56
55
  }
@@ -1,69 +0,0 @@
1
- import type { CommonLogger, ErrorReporter, TransactionObservabilityManager } from '@lokalise/node-core';
2
- import type Redis from 'ioredis';
3
- import type { LockOptions } from 'redis-semaphore';
4
- import { Mutex } from 'redis-semaphore';
5
- import type { ToadScheduler } from 'toad-scheduler';
6
- import { AsyncTask } from 'toad-scheduler';
7
- export type BackgroundJobConfiguration = {
8
- /**
9
- * Job unique name
10
- */
11
- jobId: string;
12
- /**
13
- * The interval in milliseconds at which the job should run.
14
- */
15
- intervalInMs?: number;
16
- /**
17
- * Allows to run the job exclusively in a single instance of the application.
18
- * The first consumer that acquires the lock will be the only one to run the job until it stops refreshing the lock.
19
- */
20
- singleConsumerMode?: {
21
- enabled: boolean;
22
- /**
23
- * By default, the lock TTL is 2 * intervalInMs, to prevent the lock from expiring before the next execution.
24
- */
25
- lockTimeout?: number;
26
- /**
27
- * Lock will be reset to this value after success, so that other node could potentially acquire the lock after it expires, but in order to prevent immediate acquire
28
- */
29
- lockTimeoutAfterSuccess?: number;
30
- };
31
- /**
32
- * If true, the job will log when it starts and finishes.
33
- */
34
- shouldLogExecution?: boolean;
35
- };
36
- export type LockConfiguration = {
37
- lockName?: string;
38
- identifier?: string;
39
- refreshInterval?: number;
40
- lockTimeout?: number;
41
- acquiredExternally?: true;
42
- };
43
- export declare function createTask(logger: CommonLogger, job: AbstractPeriodicJob): AsyncTask;
44
- export type PeriodicJobDependencies = {
45
- redis: Redis;
46
- logger: CommonLogger;
47
- transactionObservabilityManager: TransactionObservabilityManager;
48
- errorReporter: ErrorReporter;
49
- scheduler: ToadScheduler;
50
- };
51
- export declare abstract class AbstractPeriodicJob {
52
- readonly options: Required<BackgroundJobConfiguration>;
53
- protected readonly redis: Redis;
54
- protected readonly transactionObservabilityManager: TransactionObservabilityManager;
55
- protected readonly logger: CommonLogger;
56
- protected readonly errorReporter: ErrorReporter;
57
- protected readonly scheduler: ToadScheduler;
58
- private singleConsumerLock?;
59
- protected constructor(options: BackgroundJobConfiguration, { redis, logger, transactionObservabilityManager, errorReporter, scheduler, }: PeriodicJobDependencies);
60
- register(): void;
61
- dispose(): Promise<void>;
62
- protected abstract processInternal(executionUuid: string): Promise<unknown>;
63
- process(executionUuid: string): Promise<void>;
64
- protected getJobMutex(key: string, options: LockOptions): Mutex;
65
- protected tryAcquireExclusiveLock(lockConfiguration?: LockConfiguration): Promise<Mutex | undefined>;
66
- protected updateMutex(mutex: Mutex, newLockTimeout: number, key?: string): Promise<Mutex | undefined>;
67
- protected getJobLockName(key: string): string;
68
- protected resolveExecutionLogger(uuid: string): CommonLogger;
69
- }
@@ -1,161 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AbstractPeriodicJob = void 0;
4
- exports.createTask = createTask;
5
- const node_crypto_1 = require("node:crypto");
6
- const node_core_1 = require("@lokalise/node-core");
7
- const pino_1 = require("pino");
8
- const redis_semaphore_1 = require("redis-semaphore");
9
- const toad_scheduler_1 = require("toad-scheduler");
10
- const DEFAULT_LOCK_NAME = 'exclusive';
11
- const DEFAULT_JOB_INTERVAL = 60000;
12
- function createTask(logger, job) {
13
- const executorId = (0, node_crypto_1.randomUUID)();
14
- logger.info({
15
- msg: 'Periodic job registered',
16
- jobId: job.options.jobId,
17
- executorId,
18
- });
19
- return new toad_scheduler_1.AsyncTask(job.options.jobId, () => {
20
- return job.process(executorId);
21
- }, (error) => {
22
- logger.error(pino_1.stdSerializers.err({
23
- name: error.name,
24
- message: error.message,
25
- stack: error.stack,
26
- }));
27
- });
28
- }
29
- class AbstractPeriodicJob {
30
- options;
31
- redis;
32
- transactionObservabilityManager;
33
- logger;
34
- errorReporter;
35
- scheduler;
36
- singleConsumerLock;
37
- constructor(options, { redis, logger, transactionObservabilityManager, errorReporter, scheduler, }) {
38
- this.options = {
39
- intervalInMs: DEFAULT_JOB_INTERVAL,
40
- shouldLogExecution: false,
41
- ...options,
42
- singleConsumerMode: {
43
- enabled: true,
44
- lockTimeout: (options.intervalInMs ?? DEFAULT_JOB_INTERVAL) * 2,
45
- ...options.singleConsumerMode,
46
- },
47
- };
48
- this.logger = logger;
49
- this.redis = redis;
50
- this.transactionObservabilityManager = transactionObservabilityManager;
51
- this.errorReporter = errorReporter;
52
- this.scheduler = scheduler;
53
- }
54
- register() {
55
- const task = createTask(this.logger, this);
56
- this.scheduler.addSimpleIntervalJob(new toad_scheduler_1.SimpleIntervalJob({
57
- milliseconds: this.options.intervalInMs,
58
- runImmediately: true,
59
- }, task, {
60
- id: this.options.jobId,
61
- preventOverrun: true,
62
- }));
63
- }
64
- async dispose() {
65
- this.scheduler.stop();
66
- await this.singleConsumerLock?.release();
67
- }
68
- async process(executionUuid) {
69
- const logger = this.resolveExecutionLogger(executionUuid);
70
- if (this.options.singleConsumerMode.enabled) {
71
- // acquire or update lock
72
- this.singleConsumerLock = await this.tryAcquireExclusiveLock({
73
- lockTimeout: this.options.singleConsumerMode.lockTimeout,
74
- identifier: executionUuid,
75
- });
76
- if (!this.singleConsumerLock) {
77
- logger.debug('Periodic job skipped: unable to acquire single consumer lock');
78
- return;
79
- }
80
- }
81
- try {
82
- this.transactionObservabilityManager.start(this.options.jobId, executionUuid);
83
- if (this.options.shouldLogExecution)
84
- logger.info('Periodic job started');
85
- await this.processInternal(executionUuid);
86
- }
87
- catch (err) {
88
- logger.error({
89
- ...(0, node_core_1.resolveGlobalErrorLogObject)(err, executionUuid),
90
- msg: 'Error during periodic job execution',
91
- });
92
- if (err instanceof Error) {
93
- this.errorReporter.report({
94
- error: err,
95
- context: {
96
- executorId: executionUuid,
97
- },
98
- });
99
- }
100
- }
101
- finally {
102
- // stop auto-refreshing the lock to let it expire
103
- if (this.singleConsumerLock) {
104
- await this.updateMutex(this.singleConsumerLock, this.options.singleConsumerMode.lockTimeoutAfterSuccess ?? this.options.intervalInMs);
105
- this.singleConsumerLock.stopRefresh();
106
- }
107
- if (this.options.shouldLogExecution)
108
- logger.info('Periodic job finished');
109
- this.transactionObservabilityManager.stop(executionUuid);
110
- }
111
- }
112
- getJobMutex(key, options) {
113
- return new redis_semaphore_1.Mutex(this.redis, this.getJobLockName(key), options);
114
- }
115
- async tryAcquireExclusiveLock(lockConfiguration) {
116
- const mutexOptions = {
117
- acquireAttemptsLimit: 1,
118
- refreshInterval: lockConfiguration?.refreshInterval,
119
- acquiredExternally: lockConfiguration?.acquiredExternally,
120
- identifier: lockConfiguration?.identifier,
121
- lockTimeout: lockConfiguration?.lockTimeout ?? this.options.singleConsumerMode.lockTimeout,
122
- };
123
- let lock = this.getJobMutex(lockConfiguration?.lockName ?? DEFAULT_LOCK_NAME, mutexOptions);
124
- let acquired = await lock.tryAcquire();
125
- // If lock has been acquired previously by this instance, try to refresh
126
- if (!acquired && lockConfiguration?.identifier) {
127
- lock = this.getJobMutex(lockConfiguration?.lockName ?? DEFAULT_LOCK_NAME, {
128
- ...mutexOptions,
129
- acquiredExternally: true,
130
- });
131
- acquired = await lock.tryAcquire();
132
- }
133
- // If someone else already has this lock, skip
134
- if (!acquired) {
135
- return;
136
- }
137
- return lock;
138
- }
139
- async updateMutex(mutex, newLockTimeout, key = DEFAULT_LOCK_NAME) {
140
- const newMutex = new redis_semaphore_1.Mutex(this.redis, this.getJobLockName(key), {
141
- acquiredExternally: true,
142
- identifier: mutex.identifier,
143
- lockTimeout: newLockTimeout,
144
- });
145
- const lock = await newMutex.tryAcquire();
146
- if (!lock) {
147
- return;
148
- }
149
- return newMutex;
150
- }
151
- getJobLockName(key) {
152
- return `${this.options.jobId}:locks:${key}`;
153
- }
154
- resolveExecutionLogger(uuid) {
155
- return this.logger.child({
156
- executorId: uuid,
157
- jobId: this.options.jobId,
158
- });
159
- }
160
- }
161
- exports.AbstractPeriodicJob = AbstractPeriodicJob;