# AWS SSM Parameter Store based discovery client

Library that provides an easier access to AWS SSM Parameter store to use it
as a resilient distributed key/value storage for service discovery.

Read about AWS SSM Parameter Store [here](http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html).

## Install

```
npm i --save aws-sdk @assetchain/parameter-store-discovery-client
```

## Example

Here is the example how to use parameter discovery service in your lambda

```js
import { ParameterDiscoveryService } from '@assetchain/parameter-store-discovery-client';

// Init parameter
const store = new ParameterDiscoveryService({}, {stage: 'dev'});
// You can prefetch some parameters outside of your lambda handler
// Be aware that this is an async call and it may not be complete before handler executed
store.get([
    '/services/accounts/baseUrl',
    '/services/transactions/baseUrl',
    '/services/transactions/timeout'
]);

export async function handler(event, context, callback) {
    // if you already have parameter fetched in line #26 then this will load it from a cache
    const response = await fetch(store.get('/services/accounts/baseUrl'));
    // if you don't have parameter fetched already - it will make a call and cache it for a some time
    const response = await fetch(store.get('/services/accounts/random'));
}
```

## Docs

### new ParameterDiscoveryService([awsConfig: Object], [options: Object])

Where `awsConfig` is AWS SDK Configuration object that will be passed directly. It has many configuration options 
and uses this one as a default:
- `region (defaults to process.env.REGION)`

Optional arguments within options object are these: 
- `stage (defaults to process.env.STAGE)` - stage that will be used as a prefix for all your keys like `/${stage}/my/key/name`
- `ttl (30000)` - time to live for your cache, new call will be made to AWS API if cache expired
- `isFallbackEnabled (true)` - enable or disable `Fallback Mode` (read below)
- `fallbackStage ('master')` - stage that will be used to search for parameter if main stage parameter not found
- `isAutoRefreshEnabled (false)` - set a timeout to automatically refresh cache when it expires even if no get calls have been made. 
Be careful as internal SetInterval may prevent a shutdown of your lambda as you have to manually cancel `this.timeout`

Example

```js
const parameterDiscoveryService = new ParameterDiscoveryService({region: 'ap-southeast-2'}, {stage: 'dev', ttl: 120000});
```

### ParameterDiscoveryService.get(path: String, [options: Object]): Promise<Parameter>
### ParameterDiscoveryService.get(paths: Array<String>, [options: Object]): Promise<Map<Parameter>>

Retrieves a parameter or multiple parameters from the storage. It will automatically decrypt them if needed as `WithDecryption: true`
option is set by default. Retrieved value will be stored in internal cache and retrived from there if it's not expired.

`Parameter` has structure like
```
{
    "Name": "string",
    "Type": "string",
    "Value": "string",
    "Version": number
}
```

Promise from `ParameterDiscoveryService.get(['something'], options)` will return a HashMap with parameters objects where promise from 
`ParameterDiscoveryService.get('something', options)` will return parameter object

```js
const parameterDiscoveryService = new ParameterDiscoveryService({region: 'ap-southeast-2'}, {stage: 'dev'});

async printBaseUrl() {
  const baseUrl = await parameterDiscoveryService.get('/service/accounts/baseUrl'); 
  
  console.log(baseUrl.Value) // prints parameter from /dev/service/accounts/baseUrl
}

async printManyParams() {
  const parameters = await parameterDiscoveryService.get(['/service/accounts/baseUrl', '/service/transactions/limit']);
  
  console.log(parameters) // this is a hashMap so...
  console.log(parameters.get('/service/accounts/baseUrl').Value) // prints parameter from /dev/service/accounts/baseUrl
  console.log(parameters.get('/service/transactions/limit').Value) // prints parameter from /dev/service/transactions/limit
}
```

### ParameterDiscoveryService.set(path: String, value: String|Array<String>, [options]): Promise<ParameterCreationResponse>

Set parameter in AWS SSM Parameter Store. You can pass either string or array of strings here. Non strings values will be converted
to strings.

AWS Option for `Overwrite` set to `true` by default but you can overwrite it. 
You can check [AWS API reference](http://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PutParameter.html) for PutParameter
to get a better idea what options you can pass through

```js
const parameterDiscoveryService = new ParameterDiscoveryService({region: 'ap-southeast-2'}, {stage: 'dev'});

async updateBaseUrl(url) {
  const result = await parameterDiscoveryService.set('/service/accounts/baseUrl', url);
  console.log(result); // Something like {Version: 12}
}
```

### ParameterDiscoveryService.setEncrypted(path: String, value: String, [options]): Promise<ParameterCreationResponse>

The same as `.set()` described above but option for parameter type set to `SecureString`. 
If you don't specify a KMS key ID (`KeyId`), the system uses the default key associated with your AWS account.

## Fallback Mode

By default this library operates with enabled Fallback Mode. That means if parameter wasn't found by `/${stage}/path/to/param` path
then library will try to retrieve it from `/${fallbackStage/path/to/param`. This is extremely useful if you deploy your branches 
next to master when they can reach each other. If your branch don't have any configuration - it will fallback to use master parameters.

You can disable that behaviour or change fallback stage by defining and passing `isFallbackEnabled` and `fallbackStage` arguments
to the constructor

# Development

Build this library using `npm build` - that will run eslint + prettier checks and unit tests

# License

The MIT License (MIT)
=====================

Copyright © 2017 AssetChain

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
