Skip to content

Commit 7bf1bb8

Browse files
authored
feat: Added distributed lock API support to javascript sdk (#306)
* Added distributed lock api support to javascript sdk Signed-off-by: Amulya Varote <[email protected]> * Changes based on the initial review comments Signed-off-by: Amulya Varote <[email protected]> * Fixed build failures on initial feedback Signed-off-by: Amulya Varote <[email protected]> * Changes based on the review comments Signed-off-by: Amulya Varote <[email protected]> * Changes based on the second review comments Signed-off-by: Amulya Varote <[email protected]> * Fixing build and other test cases Signed-off-by: Amulya Varote <[email protected]> * Chnaged file name for testing Signed-off-by: Amulya Varote <[email protected]> * Changed file name to the right one Signed-off-by: Amulya Varote <[email protected]> * Resolved merge conflicts Signed-off-by: Amulya Varote <[email protected]> * Fixing the builds Signed-off-by: Amulya Varote <[email protected]> * Modified documentation based on the review comments Signed-off-by: Amulya Varote <[email protected]> * Getting changes from master Signed-off-by: Amulya Varote <[email protected]> * Reverting unnecessary changes Signed-off-by: Amulya Varote <[email protected]> * Reverting unnecessary changes Signed-off-by: Amulya Varote <[email protected]> * Reverting unnecessary changes Signed-off-by: Amulya Varote <[email protected]> * Reverting unnecessary changes Signed-off-by: Amulya Varote <[email protected]> * Changes based on the review comments on consistency Signed-off-by: Amulya Varote <[email protected]> * Changes based on the review comments in the test file Signed-off-by: Amulya Varote <[email protected]> * Added uuids for resource ids Signed-off-by: Amulya Varote <[email protected]>
1 parent 9dd64a1 commit 7bf1bb8

File tree

20 files changed

+2564
-6931
lines changed

20 files changed

+2564
-6931
lines changed

examples/distributedLock/README.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Example - Distributed Lock APIs
2+
3+
This example demonstrates 2 features (Try Lock & Unlock) from the [Distributed lock API from Dapr](https://github.com/dapr/dapr/issues/3549) that helps developers to keep their data safe from race conditions. For more information, check out the documentation at
4+
5+
It demonstrates the **Distributed Lock** API's following methods:
6+
- `TryLock`
7+
- `Unlock`
8+
9+
> **Note:** Make sure to use the latest proto bindings by running scripts/fetch-proto.sh file.
10+
## Prerequisites
11+
12+
- [Dapr CLI](https://docs.dapr.io/getting-started/install-dapr-cli/)
13+
- [Dapr JS SDK](https://docs.dapr.io/developing-applications/sdks/js/)
14+
- Initialize Dapr environment by pulling the code from master branch of [Dapr](https://github.com/dapr/dapr)
15+
16+
## Overview
17+
18+
The TryLock and Unlock calls are implemented under the client.lock attribute.
19+
20+
#### TryLock Example
21+
22+
```javascript
23+
const tryLockResponse = await client.lock.tryLock(storeName, resourceId, lockOwner, expiryInSeconds);
24+
```
25+
26+
#### Unlock Example
27+
28+
```javascript
29+
const unlockResponse = await client.lock.unlock(storeName, resourceId, lockOwner);
30+
```
31+
32+
### Start the Lock application.
33+
34+
Execute the example under the folder `examples/distributedLock/TryLockApplication`
35+
36+
```bash
37+
cd examples/distributedLock/TryLockApplication
38+
npm install
39+
```
40+
41+
To run the `TryLock`, execute the following command:
42+
43+
```bash
44+
dapr run --app-id lock --app-protocol grpc --components-path ./components npm run start
45+
```
46+
47+
You should see the following output from the application:
48+
49+
```
50+
== APP == Acquiring lock on redislock, resourceId as owner: owner1
51+
== APP == { success: true }
52+
== APP == Unlocking on redislock, resourceId as owner: owner1
53+
== APP == Unlock API response: Success
54+
== APP == Unlocking on redislock, resourceId as owner: owner1
55+
== APP == Unlock API response when lock is not acquired: LockDoesNotExist
56+
== APP == Acquiring lock on redislock, resourceId as owner: owner1
57+
== APP == Acquired Lock? true
58+
```
59+
60+
### Start the Unlock Example.
61+
62+
Run `UnlockApplication` after `TryLockApplication` is ran.
63+
64+
Navigate to examples/distributedLock/UnlockApplication.
65+
66+
```bash
67+
cd examples/distributedLock/UnlockApplication
68+
npm install
69+
```
70+
71+
To run the `UnlockApplication`, execute the following command:
72+
73+
```bash
74+
dapr run --app-id lock --app-protocol grpc --components-path ./components npm run start
75+
```
76+
77+
You should see the following output from the application:
78+
79+
```
80+
== APP == Acquiring lock on redislock, resourceId as owner: owner2
81+
== APP == Acquired Lock? false
82+
== APP == Lock cannot be acquired as it belongs to the other process
83+
== APP == Unlocking on redislock, resourceId as owner: owner2
84+
== APP == Unlock API response when lock is acquired by a different process: LockBelongToOthers
85+
== APP == Acquiring lock on redislock, resourceId as owner: owner2
86+
== APP == Acquired lock after the lock from the other process expired? true
87+
== APP == Unlocking on redislock, resourceId as owner: owner2
88+
== APP == Unlock API response when lock is released after the expiry time: Success
89+
== APP == Unlocking on redislock, resourceId as owner: owner2
90+
== APP == Unlock API response when lock is released after the expiry time and lock does not exist: LockDoesNotExist
91+
```
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
apiVersion: dapr.io/v1alpha1
2+
kind: Component
3+
metadata:
4+
name: redislock
5+
spec:
6+
type: lock.redis
7+
version: v1
8+
metadata:
9+
- name: redisHost
10+
value: localhost:6379
11+
- name: redisPassword
12+
value: ""

examples/distributedLock/TryLockApplication/package-lock.json

Lines changed: 918 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
{
2-
"name": "dapr-example-config",
2+
"name": "dapr-example-lock",
33
"version": "1.0.0",
4-
"description": "An example utilizing the Dapr JS SDK to invoke a service",
4+
"description": "An example utilizing the Dapr JS SDK to lock a resource",
55
"main": "dist/index.js",
66
"private": true,
77
"scripts": {
88
"build": "rimraf ./dist && tsc",
99
"start": "npm run build && node dist/index.js",
10-
"start:dapr-grpc": "dapr run --app-id example-config --app-port 50051 --app-protocol grpc npm run start",
11-
"start:dapr-http": "dapr run --app-id example-config --app-port 50051 --app-protocol http npm run start"
10+
"start:dapr-grpc": "dapr run --app-id lock --app-protocol grpc --components-path ./components npm run start",
11+
"start:dapr-http": "dapr run --app-id lock --app-protocol grpc --components-path ./components npm run start"
1212
},
1313
"keywords": [],
1414
"license": "ISC",
@@ -18,7 +18,7 @@
1818
"typescript": "^4.2.4"
1919
},
2020
"dependencies": {
21-
"@dapr/dapr": "file:../../build",
21+
"@dapr/dapr": "file:../../../build",
2222
"@types/node": "^15.3.0"
2323
}
24-
}
24+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Copyright 2022 The Dapr Authors
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
14+
import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";
15+
import { LockStatus } from "@dapr/dapr/types/lock/UnlockResponse";
16+
17+
const daprHost = "127.0.0.1";
18+
const daprPortDefault = "3500";
19+
20+
async function start() {
21+
const client = new DaprClient(
22+
daprHost,
23+
process.env.DAPR_GRPC_PORT ?? daprPortDefault,
24+
CommunicationProtocolEnum.GRPC
25+
);
26+
27+
const storeName = "redislock";
28+
const resourceId = "resourceId";
29+
const lockOwner = "owner1";
30+
let expiryInSeconds = 1000;
31+
32+
console.log(`Acquiring lock on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
33+
const tryLockResponse = await client.lock.tryLock(storeName, resourceId, lockOwner, expiryInSeconds);
34+
console.log(tryLockResponse);
35+
36+
console.log(`Unlocking on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
37+
const unlockResponse = await client.lock.unlock(storeName, resourceId, lockOwner);
38+
console.log("Unlock API response: " + getResponseStatus(unlockResponse.status));
39+
40+
// Checking if the lock exists.
41+
console.log(`Unlocking on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
42+
const lockUnexistResponse = await client.lock.unlock(storeName, resourceId, lockOwner);
43+
console.log("Unlock API response when lock is not acquired: " + getResponseStatus(lockUnexistResponse.status));
44+
45+
expiryInSeconds = 25;
46+
console.log(`Acquiring lock on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
47+
const tryLockResponse1 = await client.lock.tryLock(storeName, resourceId, lockOwner, expiryInSeconds);
48+
console.log("Acquired Lock? " + tryLockResponse1.success);
49+
50+
await new Promise(resolve => setTimeout(resolve, 20000));
51+
}
52+
53+
function getResponseStatus(status: LockStatus) {
54+
switch(status) {
55+
case LockStatus.Success:
56+
return "Success";
57+
case LockStatus.LockDoesNotExist:
58+
return "LockDoesNotExist";
59+
case LockStatus.LockBelongToOthers:
60+
return "LockBelongToOthers";
61+
default:
62+
return "InternalError";
63+
}
64+
}
65+
66+
start().catch((e) => {
67+
console.error(e);
68+
process.exit(1);
69+
});
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
{
2+
"compilerOptions": {
3+
/* Visit https://aka.ms/tsconfig.json to read more about this file */
4+
5+
/* Basic Options */
6+
// "incremental": true, /* Enable incremental compilation */
7+
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
8+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9+
// "lib": [], /* Specify library files to be included in the compilation. */
10+
// "allowJs": true, /* Allow javascript files to be compiled. */
11+
// "checkJs": true, /* Report errors in .js files. */
12+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
13+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
14+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15+
// "sourceMap": true, /* Generates corresponding '.map' file. */
16+
// "outFile": "./", /* Concatenate and emit output to single file. */
17+
"outDir": "./dist", /* Redirect output structure to the directory. */
18+
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
19+
// "composite": true, /* Enable project compilation */
20+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
21+
// "removeComments": true, /* Do not emit comments to output. */
22+
// "noEmit": true, /* Do not emit outputs. */
23+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
24+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
25+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
26+
27+
/* Strict Type-Checking Options */
28+
"strict": true, /* Enable all strict type-checking options. */
29+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
30+
// "strictNullChecks": true, /* Enable strict null checks. */
31+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
32+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
33+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
34+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
35+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
36+
37+
/* Additional Checks */
38+
// "noUnusedLocals": true, /* Report errors on unused locals. */
39+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
40+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
41+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
42+
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
43+
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
44+
45+
/* Module Resolution Options */
46+
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
47+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
48+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
49+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
50+
// "typeRoots": [], /* List of folders to include type definitions from. */
51+
// "types": [], /* Type declaration files to be included in compilation. */
52+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
53+
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
54+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
55+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
56+
57+
/* Source Map Options */
58+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
59+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
61+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
62+
63+
/* Experimental Options */
64+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
65+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
66+
67+
/* Advanced Options */
68+
"skipLibCheck": true, /* Skip type checking of declaration files. */
69+
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
70+
}
71+
}
72+
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
apiVersion: dapr.io/v1alpha1
2+
kind: Component
3+
metadata:
4+
name: redislock
5+
spec:
6+
type: lock.redis
7+
version: v1
8+
metadata:
9+
- name: redisHost
10+
value: localhost:6379
11+
- name: redisPassword
12+
value: ""

0 commit comments

Comments
 (0)