Skip to content
Merged
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ For information on the Service Registry product in Tanzu Platform for Cloud Foun
- Push the `greeter-messages` application:

```
cd greeter-messages && cf push
cd packages/greeter-messages && cf push
```

- Push the `greeter` application:

```
cd greeter && cf push
cd packages/greeter && cf push
```

## Trying It Out
Expand Down
108 changes: 1 addition & 107 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 9 additions & 3 deletions packages/greeter/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { env, eureka } from '@greeting/shared';
const app = express();
const eurekaClient = await eureka.getClient(env.port);

const serviceHost = () => {
// Counter for round-robin load balancing
let instanceCounter = 0;

const getServiceInstance = () => {
const instances =
eurekaClient
.getInstancesByAppId('GREETER-MESSAGES')
Expand All @@ -14,14 +17,17 @@ const serviceHost = () => {
throw new Error('No instances of GREETER-MESSAGES available');
}

return instances[0].hostName;
const selectedInstance = instances[instanceCounter % instances.length];
instanceCounter = (instanceCounter + 1) % instances.length;

return selectedInstance.hostName;
};

app.get('/hello', async (req, res) => {
const salutation = req.query.salutation || 'Hello';
const name = req.query.name || 'Bob';

const url = `https://${serviceHost()}/greeting?salutation=${salutation}&name=${name}`;
const url = `https://${getServiceInstance()}/greeting?salutation=${salutation}&name=${name}`;

const response = await fetch(`${url}`, {
headers: {
Expand Down
3 changes: 1 addition & 2 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
"license": "Apache-2.0",
"dependencies": {
"dotenv": "^17.2.0",
"eureka-js-client": "^4.5.0",
"simple-oauth2": "^5.1.0"
"eureka-js-client": "^4.5.0"
}
}
47 changes: 28 additions & 19 deletions packages/shared/src/oauth2.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,43 @@
import { ClientCredentials } from 'simple-oauth2';
import services from './vcap-services.js';

const credentials = services.getCredentials('p.service-registry');

const client = new ClientCredentials({
client: {
id: credentials.client_id,
secret: credentials.client_secret,
},
auth: {
tokenHost: credentials.access_token_uri.replace('/oauth/token', ''),
tokenPath: '/oauth/token',
},
});

let token = null;

// Checks if token is expired or will be expired in given window.
const expired = (token, expirationWindowSeconds = 0) => {
return (
!token ||
token.expires_at - (Date.now() + expirationWindowSeconds * 1000) <= 0
);
};

// Requests an access token from the UAA server using client credentials.
const getAccessToken = async () => {
// If token is not set or expired, request a new one.
if (!token || token.expired(3)) {
try {
token = await client.getToken();
} catch (error) {
console.error('Failed to get access token', error.message);
throw error;
if (!token || expired(token, 10)) {
const response = await fetch(credentials.access_token_uri, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(`${credentials.client_id}:${credentials.client_secret}`).toString('base64')}`,
},
body: new URLSearchParams({ grant_type: 'client_credentials' }),
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();

token = {
access_token: data.access_token,
expires_at: Date.now() + data.expires_in * 1000,
};
}

return token.token.access_token;
return token.access_token;
};

export default {
Expand Down