@mojaloop/central-services-shared 18.28.2 → 18.29.0-snapshot.0

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [18.28.3](https://github.com/mojaloop/central-services-shared/compare/v18.28.2...v18.28.3) (2025-06-24)
6
+
7
+
8
+ ### Chore
9
+
10
+ * add parties to header resources ([#459](https://github.com/mojaloop/central-services-shared/issues/459)) ([5092d84](https://github.com/mojaloop/central-services-shared/commit/5092d84125e72257ecb9bdcff1441274c253ca04))
11
+
5
12
  ### [18.28.2](https://github.com/mojaloop/central-services-shared/compare/v18.28.1...v18.28.2) (2025-06-12)
6
13
 
7
14
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mojaloop/central-services-shared",
3
- "version": "18.28.2",
3
+ "version": "18.29.0-snapshot.0",
4
4
  "description": "Shared code for mojaloop central services",
5
5
  "license": "Apache-2.0",
6
6
  "author": "ModusBox",
@@ -41,6 +41,7 @@
41
41
  "lint": "npm run standard",
42
42
  "lint:fix": "npm run standard:fix",
43
43
  "test": "npm run test:unit",
44
+ "test:distLock": "npx tape 'test/unit/util/distLock/**/*.test.js'",
44
45
  "test:header": "npx tape 'test/unit/util/headerValidation/**/*.test.js'",
45
46
  "test:logging": "npx tape 'test/unit/util/hapi/plugins/loggingPlugin.test.js'",
46
47
  "test:endpoints": "npx tape 'test/unit/util/endpoints.test.js'",
@@ -70,10 +71,10 @@
70
71
  "@opentelemetry/api": "1.9.0",
71
72
  "async-exit-hook": "2.0.1",
72
73
  "async-retry": "1.3.3",
73
- "axios": "1.9.0",
74
+ "axios": "1.10.0",
74
75
  "clone": "2.1.2",
75
76
  "convict": "^6.2.4",
76
- "dotenv": "16.5.0",
77
+ "dotenv": "17.0.0",
77
78
  "env-var": "7.5.0",
78
79
  "event-stream": "4.0.1",
79
80
  "fast-safe-stringify": "2.1.1",
@@ -82,9 +83,10 @@
82
83
  "joi": "17.13.3",
83
84
  "lodash": "4.17.21",
84
85
  "mustache": "4.2.0",
85
- "openapi-backend": "5.12.0",
86
+ "openapi-backend": "5.13.0",
86
87
  "raw-body": "3.0.0",
87
88
  "rc": "1.2.8",
89
+ "redlock": "5.0.0-beta.2",
88
90
  "shins": "2.6.0",
89
91
  "ulidx": "2.4.1",
90
92
  "uuid4": "2.0.3",
@@ -96,8 +98,8 @@
96
98
  "@mojaloop/central-services-logger": "11.9.0",
97
99
  "@mojaloop/central-services-metrics": "12.6.0",
98
100
  "@mojaloop/event-sdk": "14.6.1",
99
- "@mojaloop/sdk-standard-components": "19.15.2",
100
- "@opentelemetry/auto-instrumentations-node": "^0.60.0",
101
+ "@mojaloop/sdk-standard-components": "19.16.0",
102
+ "@opentelemetry/auto-instrumentations-node": "^0.60.1",
101
103
  "@types/hapi__joi": "17.1.15",
102
104
  "ajv": "^8.17.1",
103
105
  "ajv-formats": "^3.0.1",
@@ -112,7 +114,7 @@
112
114
  "proxyquire": "2.1.3",
113
115
  "replace": "1.2.2",
114
116
  "rewire": "8.0.0",
115
- "sinon": "20.0.0",
117
+ "sinon": "21.0.0",
116
118
  "standard": "17.1.2",
117
119
  "standard-version": "9.5.0",
118
120
  "tap-spec": "5.0.0",
package/src/enums/http.js CHANGED
@@ -127,7 +127,8 @@ const HeaderResources = {
127
127
  TRANSFERS: 'transfers',
128
128
  FX_TRANSFERS: 'fxTransfers',
129
129
  QUOTES: 'quotes',
130
- FX_QUOTES: 'fxQuotes'
130
+ FX_QUOTES: 'fxQuotes',
131
+ PARTIES: 'parties'
131
132
  }
132
133
 
133
134
  const ServiceType = {
package/src/index.d.ts CHANGED
@@ -19,6 +19,15 @@ declare namespace CentralServicesShared {
19
19
  URI: string;
20
20
  };
21
21
  };
22
+ HeaderResources: {
23
+ PARTICIPANTS: string;
24
+ ORACLE: string;
25
+ TRANSFERS: string;
26
+ FX_TRANSFERS: string;
27
+ QUOTES: string;
28
+ FX_QUOTES: string;
29
+ PARTIES: string;
30
+ };
22
31
  ReturnCodes: {
23
32
  OK: ReturnCode;
24
33
  ACCEPTED: ReturnCode;
@@ -769,6 +778,42 @@ declare namespace CentralServicesShared {
769
778
  RedisCache: RedisCache;
770
779
  }
771
780
 
781
+ type RedisInstanceConfig =
782
+ | {
783
+ type: 'redis';
784
+ host: string;
785
+ port: number;
786
+ }
787
+ | {
788
+ type: 'redis-cluster';
789
+ cluster: Array<{ host: string; port: number }>;
790
+ };
791
+
792
+ interface DistributedLockConfig {
793
+ redisConfigs: RedisInstanceConfig[];
794
+ driftFactor?: number;
795
+ retryCount?: number;
796
+ retryDelay?: number;
797
+ retryJitter?: number;
798
+ lockTimeout?: number;
799
+ }
800
+
801
+ interface LockInterface {
802
+ acquire(key: string, ttl: number, acquireTimeout?: number): Promise<string>;
803
+ release(): Promise<boolean>;
804
+ extend(ttl: number): Promise<string>;
805
+ }
806
+
807
+ interface DistributedLock extends LockInterface {
808
+ config: DistributedLockConfig;
809
+ logger: ILogger;
810
+ redisInstances: IORedis[];
811
+ }
812
+
813
+ interface DistLock {
814
+ createLock(config: DistributedLockConfig, logger?: ILogger): DistributedLock;
815
+ }
816
+
772
817
  interface Util {
773
818
  Endpoints: Endpoints;
774
819
  Participants: Participants;
@@ -780,6 +825,7 @@ declare namespace CentralServicesShared {
780
825
  StreamingProtocol: StreamingProtocol;
781
826
  HeaderValidation: HeaderValidation;
782
827
  Redis: Redis;
828
+ distLock: DistLock;
783
829
  }
784
830
 
785
831
  const Enum: Enum
@@ -0,0 +1,18 @@
1
+ const ERROR_MESSAGES = {
2
+ ACQUIRE_ERROR: 'Failed to acquire lock',
3
+ NO_LOCK_TO_RELEASE: 'No lock to release',
4
+ NO_LOCK_TO_EXTEND: 'No lock to extend',
5
+ REDLOCK_ERROR: 'Redlock error occurred',
6
+ INVALID_CONFIG: 'Invalid configuration for distributed lock',
7
+ TIMEOUT_ERROR: 'Timeout while trying to acquire lock'
8
+ }
9
+
10
+ const REDIS_TYPE = {
11
+ REDIS: 'redis',
12
+ REDIS_CLUSTER: 'redis-cluster'
13
+ }
14
+
15
+ module.exports = {
16
+ ERROR_MESSAGES,
17
+ REDIS_TYPE
18
+ }
@@ -0,0 +1,157 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2020-2025 Mojaloop Foundation
5
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ Contributors
12
+ --------------
13
+ This is the official list of the Mojaloop project contributors for this file.
14
+ Names of the original copyright holders (individuals or organizations)
15
+ should be listed with a '*' in the first column. People who have
16
+ contributed from an organization can be listed under the organization
17
+ that actually holds the copyright for their contributions (see the
18
+ Mojaloop Foundation for an example). Those individuals should have
19
+ their names indented and be marked with a '-'. Email address can be added
20
+ optionally within square brackets <email>.
21
+
22
+ * Mojaloop Foundation
23
+ - Name Surname <name.surname@mojaloop.io>
24
+
25
+ * Infitx
26
+ - Steven Oderayi <steven.oderayi@infitx.com>
27
+
28
+ --------------
29
+
30
+ ******/
31
+
32
+ 'use strict'
33
+
34
+ const Redis = require('ioredis')
35
+ const { default: Redlock } = require('redlock')
36
+ const { logger: defaultLogger } = require('../../../logger')
37
+ const LockInterface = require('../lock')
38
+ const { ERROR_MESSAGES, REDIS_TYPE } = require('../constants')
39
+
40
+ /**
41
+ * @typedef {Object} DistributedLockConfig
42
+ * @property {Array<Object>} redisConfigs - Array of Redis instance configurations.
43
+ * @property {string} redisConfigs[].type - Type of Redis instance ('redis' or 'redis-cluster').
44
+ * @property {string} redisConfigs[].host - Hostname of a standalone Redis instance when type is "redis".
45
+ * @property {number} redisConfigs[].port - Port of a standalone Redis instance when type is "redis".
46
+ * @property {number} redisConfigs[].cluster - Array of Redis leader nodes for cluster configuration when type is "redis-cluster".
47
+ * @property {string} redisConfigs[].cluster[].host - Hostname of the Redis leader node in a cluster.
48
+ * @property {number} redisConfigs[].cluster[].port - Port of a the Redis leader node in a cluster.
49
+ * @property {number} [driftFactor=0.01] - Drift factor for Redlock.
50
+ * @property {number} [retryCount=3] - Number of retry attempts for acquiring a lock.
51
+ * @property {number} [retryDelay=200] - Delay in milliseconds between retry attempts.
52
+ * @property {number} [retryJitter=100] - Jitter in milliseconds for retry delay.
53
+ * @property {number} [lockTimeout=10000] - Time-to-live for the lock in milliseconds.
54
+ *
55
+ */
56
+
57
+ /**
58
+ * DistributedLock class provides a distributed locking mechanism using Redlock.
59
+ * It supports both Redis standalone and Redis Cluster configurations simultaneously.
60
+ * It allows acquiring, releasing, and extending locks across multiple Redis instances.
61
+ *
62
+ * @class DistributedLock
63
+ * @param {DistributedLockConfig} config - Configuration for the distributed lock.
64
+ * @param {Object} [logger=console] - Logger instance for logging messages.
65
+ */
66
+ class DistributedLock extends LockInterface {
67
+ #redlock = null
68
+ #lock = null
69
+ #timeout = null
70
+
71
+ constructor (config, logger) {
72
+ super()
73
+ this.config = config
74
+ this.logger = (logger || defaultLogger).child({ component: this.constructor.name })
75
+ this.redisInstances = config.redisConfigs.map(instance => this.#createRedisClient(instance))
76
+ this.#redlock = new Redlock(this.redisInstances, {
77
+ driftFactor: config.driftFactor || 0.01,
78
+ retryCount: config.retryCount || 3,
79
+ retryDelay: config.retryDelay || 200,
80
+ retryJitter: config.retryJitter || 100
81
+ })
82
+ this.#redlock.on('error', this.#handleError.bind(this))
83
+ }
84
+
85
+ async acquire (key, ttl, acquireTimeout = 2000) {
86
+ let timeoutError
87
+ const timeoutPromise = new Promise((_resolve, reject) => {
88
+ const timeout = setTimeout(() => {
89
+ timeoutError = new Error(ERROR_MESSAGES.TIMEOUT_ERROR)
90
+ reject(timeoutError)
91
+ }, acquireTimeout)
92
+ this.#timeout = timeout // Store timeout reference to clear it later
93
+ })
94
+
95
+ try {
96
+ this.#lock = await Promise.race([
97
+ this.#redlock.acquire([key], ttl),
98
+ timeoutPromise
99
+ ])
100
+ clearTimeout(this.#timeout) // Clear timeout if lock is acquired
101
+ if (!this.#lock) {
102
+ throw new Error(ERROR_MESSAGES.ACQUIRE_ERROR)
103
+ }
104
+ this.logger.debug(`Lock acquired: ${this.#lock.value} with TTL: ${ttl}ms`)
105
+ return this.#lock.value
106
+ } catch (error) {
107
+ if (error === timeoutError) {
108
+ this.logger.error(error.stack) // Possible redis connection issue, cluster not correctly setup etc.
109
+ }
110
+ throw error // Re-throw the error for the caller to handle
111
+ }
112
+ }
113
+
114
+ async release () {
115
+ if (!this.#lock) {
116
+ throw new Error(ERROR_MESSAGES.NO_LOCK_TO_RELEASE)
117
+ }
118
+ await this.#redlock.release(this.#lock)
119
+ this.logger.debug(`Lock released: ${this.#lock.value}`)
120
+ this.#lock = null
121
+ return true
122
+ }
123
+
124
+ async extend (ttl) {
125
+ if (!this.#lock) {
126
+ throw new Error(ERROR_MESSAGES.NO_LOCK_TO_EXTEND)
127
+ }
128
+ this.#lock = await this.#redlock.extend(this.#lock, ttl)
129
+ this.logger.debug(`Lock extended: ${this.#lock.value} with new TTL: ${ttl}ms`)
130
+ return this.#lock.value
131
+ }
132
+
133
+ #createRedisClient (instance) {
134
+ return instance.type === REDIS_TYPE.REDIS_CLUSTER
135
+ ? new Redis.Cluster(instance.cluster)
136
+ : new Redis(instance)
137
+ }
138
+
139
+ #handleError (error) {
140
+ // Logging with debug level as all redlock methods throw on all failures anyway.
141
+ // The error here is only more specific for fixing technical issues.
142
+ this.logger.debug(ERROR_MESSAGES.REDLOCK_ERROR, error)
143
+ }
144
+ }
145
+
146
+ const createLock = (config, logger) => {
147
+ logger.verbose('createLock config: ', { config })
148
+ if (!Array.isArray(config?.redisConfigs)) {
149
+ throw new Error(ERROR_MESSAGES.INVALID_CONFIG)
150
+ }
151
+ const distLock = new DistributedLock(config, logger)
152
+ return distLock
153
+ }
154
+
155
+ module.exports = {
156
+ createLock
157
+ }
@@ -0,0 +1 @@
1
+ module.exports = require('./impl/redlock.js')
@@ -0,0 +1,109 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2020-2025 Mojaloop Foundation
5
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ Contributors
12
+ --------------
13
+ This is the official list of the Mojaloop project contributors for this file.
14
+ Names of the original copyright holders (individuals or organizations)
15
+ should be listed with a '*' in the first column. People who have
16
+ contributed from an organization can be listed under the organization
17
+ that actually holds the copyright for their contributions (see the
18
+ Mojaloop Foundation for an example). Those individuals should have
19
+ their names indented and be marked with a '-'. Email address can be added
20
+ optionally within square brackets <email>.
21
+
22
+ * Mojaloop Foundation
23
+ - Name Surname <name.surname@mojaloop.io>
24
+
25
+ * Infitx
26
+ - Steven Oderayi <steven.oderayi@infitx.com>
27
+
28
+ --------------
29
+
30
+ ******/
31
+
32
+ 'use strict'
33
+
34
+ /**
35
+ * @interface LockInterface
36
+ * @property {Function} acquire - Method to acquire a lock.
37
+ * @property {Function} release - Method to release a lock.
38
+ * @property {Function} extend - Method to extend a lock.
39
+ */
40
+
41
+ class LockInterface {
42
+ /**
43
+ * @constructor
44
+ * @param {Object} config - Configuration for the lock implementation.
45
+ * @param {Object} logger - Logger instance for logging.
46
+ */
47
+ constructor (config, logger) {
48
+ if (new.target === LockInterface) {
49
+ throw new TypeError('Cannot construct LockInterface instances directly')
50
+ }
51
+ validateInterface(this)
52
+ }
53
+
54
+ /**
55
+ * @method acquire
56
+ * @param {string} key - The key to acquire the lock for.
57
+ * @param {number} ttl - Time to live for the lock.
58
+ * @param {number} acquireTimeout - Timeout for acquiring the lock.
59
+ */
60
+ /* istanbul ignore next */
61
+ acquire (key, ttl, acquireTimeout) {
62
+ throw new Error('Method "acquire" must be implemented')
63
+ }
64
+
65
+ /**
66
+ * @method release
67
+ */
68
+ /* istanbul ignore next */
69
+ release () {
70
+ throw new Error('Method "release" must be implemented')
71
+ }
72
+
73
+ /**
74
+ * @method extend
75
+ * @param {number} ttl - New time to live for the lock.
76
+ */
77
+ /* istanbul ignore next */
78
+ extend (ttl) {
79
+ throw new Error('Method "extend" must be implemented')
80
+ }
81
+ }
82
+
83
+ function getClassMethodsFromClass (Class) {
84
+ const prototype = Class.prototype
85
+ return Object.getOwnPropertyNames(prototype).filter(
86
+ (prop) =>
87
+ typeof prototype[prop] === 'function' &&
88
+ prop !== 'constructor'
89
+ )
90
+ }
91
+
92
+ function hasOwnMethod (instance, methodName) {
93
+ const prototype = Object.getPrototypeOf(instance)
94
+ return (
95
+ Object.getOwnPropertyNames(prototype).includes(methodName) &&
96
+ typeof prototype[methodName] === 'function'
97
+ )
98
+ }
99
+
100
+ function validateInterface (instance) {
101
+ const methods = getClassMethodsFromClass(LockInterface)
102
+ methods.forEach((method) => {
103
+ if (!hasOwnMethod(instance, method)) {
104
+ throw new Error(`Class must implement method: "${method}"`)
105
+ }
106
+ })
107
+ }
108
+
109
+ module.exports = LockInterface
package/src/util/index.js CHANGED
@@ -55,6 +55,7 @@ const id = require('./id')
55
55
  const rethrow = require('./rethrow')
56
56
  const Redis = require('./redis')
57
57
  const createLogger = require('./createLogger')
58
+ const distLock = require('./distLock')
58
59
 
59
60
  const omitNil = (object) => {
60
61
  return _.omitBy(object, _.isNil)
@@ -267,5 +268,6 @@ module.exports = {
267
268
  id,
268
269
  resourceVersions: Helpers.resourceVersions,
269
270
  rethrow,
270
- Redis
271
+ Redis,
272
+ distLock
271
273
  }
@@ -0,0 +1,194 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2020-2025 Mojaloop Foundation
5
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ Contributors
12
+ --------------
13
+ This is the official list of the Mojaloop project contributors for this file.
14
+ Names of the original copyright holders (individuals or organizations)
15
+ should be listed with a '*' in the first column. People who have
16
+ contributed from an organization can be listed under the organization
17
+ that actually holds the copyright for their contributions (see the
18
+ Mojaloop Foundation for an example). Those individuals should have
19
+ their names indented and be marked with a '-'. Email address can be added
20
+ optionally within square brackets <email>.
21
+
22
+ * Mojaloop Foundation
23
+ - Name Surname <name.surname@mojaloop.io>
24
+
25
+ * Infitx
26
+ - Steven Oderayi <steven.oderayi@infitx.com>
27
+
28
+ --------------
29
+
30
+ ******/
31
+
32
+ 'use strict'
33
+
34
+ const Test = require('tapes')(require('tape'))
35
+ const sinon = require('sinon')
36
+ const Proxyquire = require('proxyquire')
37
+ const { ERROR_MESSAGES } = require('#src/util/distLock/constants')
38
+ const { mockRedis, mockRedlock, mockConfig, mockLogger } = require('../mocks')
39
+
40
+ const proxyqireRedlockImpl = (redlock = mockRedlock) => Proxyquire('#src/util/distLock/impl/redlock', {
41
+ ioredis: mockRedis,
42
+ redlock: { default: redlock }
43
+ })
44
+
45
+ Test('DistributedLock', async (distLockTest) => {
46
+ let DistributedLock
47
+
48
+ distLockTest.beforeEach((t) => {
49
+ DistributedLock = proxyqireRedlockImpl()
50
+ t.end()
51
+ })
52
+
53
+ distLockTest.test('createLock', async (t) => {
54
+ t.test('should create a new DistributedLock instance', async (t) => {
55
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
56
+ t.ok(lock, 'Lock instance should be created')
57
+ t.end()
58
+ })
59
+ t.test('should create a new DistributedLock with redis-cluster config', async (t) => {
60
+ const minConfig = {
61
+ redisConfigs: [{ type: 'redis-cluster', cluster: [{ host: 'localhost', port: 6379 }] }]
62
+ }
63
+ const lock = DistributedLock.createLock(minConfig, mockLogger)
64
+ t.ok(lock, 'Lock instance with redis-cluster config should be created')
65
+ t.end()
66
+ })
67
+ t.test('should create a new DistributedLock with defaults', async (t) => {
68
+ const minConfig = {
69
+ redisConfigs: [{ type: 'redis', host: 'localhost', port: 6379 }]
70
+ }
71
+ const lock = DistributedLock.createLock(minConfig, mockLogger)
72
+ t.ok(lock, 'Lock instance with default config should be created')
73
+ t.end()
74
+ })
75
+ t.test('should throw error for invalid config', async (t) => {
76
+ const invalidConfig = { redisConfigs: 'invalid' }
77
+ t.throws(() => DistributedLock.createLock(invalidConfig, mockLogger), /Invalid configuration/, 'Should throw error for invalid config')
78
+ t.end()
79
+ })
80
+ t.end()
81
+ })
82
+
83
+ distLockTest.test('acquire', async (t) => {
84
+ t.test('should acquire lock successfully', async (t) => {
85
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
86
+ const result = await lock.acquire('test-key', 1000)
87
+ t.equal(result, 'test-lock-value', 'Should return lock value')
88
+ t.end()
89
+ })
90
+ t.test('should throw error on acquire timeout', async (t) => {
91
+ const mockRedlockMod = sinon.stub().returns({
92
+ acquire: async () => {
93
+ await new Promise(resolve => setTimeout(resolve, 6000))
94
+ return { value: 'test-lock-value' }
95
+ },
96
+ on: () => {}
97
+ })
98
+ DistributedLock = proxyqireRedlockImpl(mockRedlockMod)
99
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
100
+ try {
101
+ await lock.acquire('test-key', 1000)
102
+ t.fail('Should throw timeout error')
103
+ } catch (error) {
104
+ t.equal(error.message, ERROR_MESSAGES.TIMEOUT_ERROR, 'Should throw timeout error')
105
+ }
106
+ t.end()
107
+ })
108
+
109
+ t.test('should throw error when lock cannot be acquired', async (t) => {
110
+ const mockRedlockMod = sinon.stub().returns({
111
+ acquire: async () => null,
112
+ on: () => {}
113
+ })
114
+ DistributedLock = proxyqireRedlockImpl(mockRedlockMod)
115
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
116
+ try {
117
+ await lock.acquire('test-key', 1000)
118
+ t.fail('Should throw error when lock cannot be acquired')
119
+ } catch (error) {
120
+ t.equal(error.message, ERROR_MESSAGES.ACQUIRE_ERROR, 'Should throw error when lock cannot be acquired')
121
+ }
122
+ t.end()
123
+ })
124
+ t.end()
125
+ })
126
+
127
+ distLockTest.test('release', async (t) => {
128
+ t.test('should release lock successfully', async (t) => {
129
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
130
+ await lock.acquire('test-key', 1000)
131
+ const result = await lock.release()
132
+ t.true(result, 'Should return true on successful release')
133
+ t.end()
134
+ })
135
+ t.test('should throw error when no lock to release', async (t) => {
136
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
137
+ try {
138
+ await lock.release()
139
+ t.fail('Should throw error when no lock exists')
140
+ } catch (error) {
141
+ t.equal(error.message, ERROR_MESSAGES.NO_LOCK_TO_RELEASE, 'Should throw error when no lock exists')
142
+ }
143
+ t.end()
144
+ })
145
+ t.end()
146
+ })
147
+
148
+ distLockTest.test('extend', async (t) => {
149
+ t.test('should extend lock successfully', async (t) => {
150
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
151
+ await lock.acquire('test-key', 1000)
152
+ const result = await lock.extend(2000)
153
+ t.equal(result, 'test-lock-extend-value', 'Should return lock value after extension')
154
+ t.end()
155
+ })
156
+ t.test('should throw error when no lock to extend', async (t) => {
157
+ const lock = DistributedLock.createLock(mockConfig, mockLogger)
158
+ try {
159
+ await lock.extend(2000)
160
+ t.fail('Should throw error when no lock exists')
161
+ } catch (error) {
162
+ t.equal(error.message, ERROR_MESSAGES.NO_LOCK_TO_EXTEND, 'Should throw error when no lock exists')
163
+ }
164
+ t.end()
165
+ })
166
+ t.end()
167
+ })
168
+
169
+ distLockTest.test('error handling', async (t) => {
170
+ t.test('should handle redlock errors', async (t) => {
171
+ let errorLogged = false
172
+ const errorLogger = {
173
+ debug: () => { errorLogged = true },
174
+ verbose: () => {},
175
+ error: () => {},
176
+ child: () => errorLogger
177
+ }
178
+ const mockRedlockMod = sinon.stub().returns({
179
+ on: (event, handler) => {
180
+ if (event === 'error') {
181
+ handler(new Error('Test error'))
182
+ }
183
+ }
184
+ })
185
+ DistributedLock = proxyqireRedlockImpl(mockRedlockMod)
186
+ DistributedLock.createLock(mockConfig, errorLogger)
187
+ t.true(errorLogged, 'Should log error')
188
+ t.end()
189
+ })
190
+ t.end()
191
+ })
192
+
193
+ distLockTest.end()
194
+ })
@@ -0,0 +1,77 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2020-2025 Mojaloop Foundation
5
+ The Mojaloop files are made available by the Mojaloop Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
10
+
11
+ Contributors
12
+ --------------
13
+ This is the official list of the Mojaloop project contributors for this file.
14
+ Names of the original copyright holders (individuals or organizations)
15
+ should be listed with a '*' in the first column. People who have
16
+ contributed from an organization can be listed under the organization
17
+ that actually holds the copyright for their contributions (see the
18
+ Mojaloop Foundation for an example). Those individuals should have
19
+ their names indented and be marked with a '-'. Email address can be added
20
+ optionally within square brackets <email>.
21
+
22
+ * Mojaloop Foundation
23
+ - Name Surname <name.surname@mojaloop.io>
24
+
25
+ * Infitx
26
+ - Steven Oderayi <steven.oderayi@infitx.com>
27
+
28
+ --------------
29
+
30
+ ******/
31
+
32
+ 'use strict'
33
+
34
+ const Test = require('tapes')(require('tape'))
35
+ const LockInterface = require('#src/util/distLock/lock')
36
+
37
+ Test('LockInterface test', async (lockTest) => {
38
+ lockTest.test('should throw error when instantiated directly', (test) => {
39
+ try {
40
+ const obj = new LockInterface()
41
+ console.log(obj)
42
+ test.fail('Expected error not thrown')
43
+ } catch (error) {
44
+ test.equal(error.message, 'Cannot construct LockInterface instances directly')
45
+ test.end()
46
+ }
47
+ })
48
+
49
+ lockTest.test('should implement acquire method', (test) => {
50
+ class TestLockImpl extends LockInterface {
51
+ release () {}
52
+ extend () {}
53
+ }
54
+ test.throws(() => new TestLockImpl(), /Class must implement method: "acquire"/)
55
+ test.end()
56
+ })
57
+
58
+ lockTest.test('should implement release method', (test) => {
59
+ class TestLockImpl extends LockInterface {
60
+ acquire () {}
61
+ extend () {}
62
+ }
63
+ test.throws(() => new TestLockImpl(), /Class must implement method: "release"/)
64
+ test.end()
65
+ })
66
+
67
+ lockTest.test('should implement extend method', (test) => {
68
+ class TestLockImpl extends LockInterface {
69
+ acquire () {}
70
+ release () {}
71
+ }
72
+ test.throws(() => new TestLockImpl(), /Class must implement method: "extend"/)
73
+ test.end()
74
+ })
75
+
76
+ lockTest.end()
77
+ })
@@ -0,0 +1,31 @@
1
+ const sinon = require('sinon')
2
+ const { logger } = require('#src/logger')
3
+
4
+ const mockRedis = sinon.stub()
5
+ const mockCluster = sinon.stub()
6
+ mockRedis.Cluster = mockCluster
7
+
8
+ const mockRedlock = sinon.stub().returns({
9
+ acquire: async () => ({ value: 'test-lock-value' }),
10
+ release: async () => {},
11
+ extend: async () => ({ value: 'test-lock-extend-value' }),
12
+ on: () => {}
13
+ })
14
+
15
+ const mockLogger = logger.child({ context: 'tests' })
16
+
17
+ const mockConfig = {
18
+ redisConfigs: [
19
+ {
20
+ type: 'redis',
21
+ host: 'localhost',
22
+ port: 6379
23
+ }
24
+ ],
25
+ driftFactor: 0.01,
26
+ retryCount: 3,
27
+ retryDelay: 200,
28
+ retryJitter: 100
29
+ }
30
+
31
+ module.exports = { mockRedis, mockCluster, mockConfig, mockLogger, mockRedlock }