├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── buildspec.yaml ├── pom.xml └── src ├── main ├── java │ └── software │ │ └── amazon │ │ └── serverless │ │ └── ssmcachingclient │ │ └── SsmParameterCachingClient.java └── lombok.config └── test ├── java └── software │ └── amazon │ └── serverless │ └── ssmcachingclient │ └── SsmParameterCachingClientTest.java └── resources └── log4j2-test.xml /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /eclipse-bin/ 2 | *.iml 3 | .classpath 4 | .settings 5 | .project 6 | build 7 | .*.sw[op] 8 | .DS_Store 9 | .idea/ 10 | target/ 11 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/awslabs/aws-ssm-java-caching-client/issues), or [recently closed](https://github.com/awslabs/aws-ssm-java-caching-client/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/awslabs/aws-ssm-java-caching-client/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/awslabs/aws-ssm-java-caching-client/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | AWS Ssm Java Caching Client 2 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-ssm-java-caching-client ![Build Status](https://codebuild.us-east-1.amazonaws.com/badges?uuid=eyJlbmNyeXB0ZWREYXRhIjoiSzNueFVRdVdwSWhuOEZQL2FjTWZRaHh5S1luTzJ0aURsVHNqcVQ4a2RvenRJbHdpbVJ5UmdETXNpSk5uUlovM3BzZ3hFZWx3cEphWGxlYTlncU55OENFPSIsIml2UGFyYW1ldGVyU3BlYyI6IjBHM1RaZ2gzdlEzRWxJUWYiLCJtYXRlcmlhbFNldFNlcmlhbCI6MX0%3D&branch=master) 2 | 3 | aws-ssm-java-caching-client is a Java client-side caching library for AWS Systems Manager Parameter Store. Note, this client wraps the Java SDK V2 version of the AWS SSM client. 4 | 5 | ## Using the Client 6 | 7 | To use the client, first add a dependency on the library. 8 | 9 | Maven: 10 | 11 | ```xml 12 | 13 | software.amazon.serverless 14 | aws-ssm-java-caching-client 15 | 1.0.0 16 | 17 | ``` 18 | 19 | Gradle: 20 | 21 | ```gradle 22 | dependencies { 23 | compile 'software.amazon.serverless:aws-ssm-java-caching-client:1.0.0' 24 | } 25 | ``` 26 | 27 | ### Basic Usage 28 | 29 | The following example creates a basic caching client that will load and cache individual SSM Parameters on demand. In this example, the time-to-live of the cached Parameter values is set to 1 minute. 30 | 31 | ```java 32 | SsmClient ssm = SsmClient.create(); 33 | 34 | // cache parameter values for 1 minute before reloading them from SSM 35 | SsmParameterCachingClient client = new SsmParameterCachingClient(ssm, Duration.ofMinutes(1)); 36 | 37 | // simple string parameter 38 | String stringParameter = client.getAsString("string_param"); 39 | // SecureString parameters are decrypted on load 40 | String secureStringParameter = client.getAsString("secure_string_param"); 41 | // comma-delimited StringList parameters 42 | List stringListParameter = client.getAsStringList("string_list_param"); 43 | 44 | // can also get the full Parameter object returned by the SSM API 45 | Parameter parameter = client.get("string_param"); 46 | System.out.println("Full Parameter metadata: " + parameter); 47 | ``` 48 | 49 | ### Parameter Hierarchy Support 50 | 51 | The `SsmParameterCachingClient` constructor also accepts a parameter path prefix, which takes advantage of SSM Parameter Store's parameter hierarchy support to make more efficient bulk calls to load all parameters under the given path prefix at once. For example, you might use the following hierarchy for storing parameters for FooService: 52 | 53 | ```text 54 | /FooService/Dev/DbTableName 55 | /FooService/Dev/NotificationTopicArn 56 | /FooService/Prod/DbTableName 57 | /FooService/Prod/NotificationTopicArn 58 | ``` 59 | 60 | In this example, there are separate parameters for FooService depending on if the environment is Dev or Prod. If `SsmParameterCachingClient` is passed `/FooService/Dev/` as the `pathPrefix`, it will make a bulk call to the SSM Parameter Store API to load and cache all parameters that start with `/FooService/Dev/`. 61 | 62 | Also, the get methods on the client will automatically prepend the path prefix so you can initialize the client once with the path prefix and then reference the parameters without the prefix from there on out: 63 | 64 | ```java 65 | // initialization code, e.g., Spring/Guice config 66 | SsmClient ssm = SsmClient.create(); 67 | SsmParameterCachingClient client = new SsmParameterCachingClient(ssm, Duration.ofMinutes(1), "/FooService/Dev/"); 68 | 69 | ... 70 | 71 | // elsewhere in your business logic 72 | 73 | // client automatically prepends prefixPath so this resolves to /FooService/Dev/DbTableName 74 | // on cache miss, the client bulk loads/caches all parameters under /FooService/Dev/ 75 | client.getAsString("DbTableName"); 76 | ``` 77 | 78 | The advantage of using this pattern is that only your initialization code needs to know what environment it's running in, and the rest of your business logic can refer to the parameters without the prefix. 79 | 80 | For more information on organizing parameters into hierarchies, see the [AWS Systems Manager User Guide](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-organize.html) 81 | 82 | ### Production Considerations 83 | 84 | This section discusses the features included in this caching client for working in production, high availability environments. 85 | 86 | 1. The `SsmParameterCachingClient` class is thread safe. The recommendation is to instantiate a singleton instance of the class and reuse it across threads/requests to maximize caching. 87 | 88 | 1. By default, if the client has cached parameter values that have expired, but it encounters an error trying to reach SSM Parameter Store to reload them, it will return the stale cached value rather than throwing an error. This is recommended for maintaining high availability of your service, but this behavior can be disabled via the `allowStaleValues` constructor argument. 89 | 90 | 1. When the caching client is initialized with a `pathPrefix` set, by default, it bulk loads all parameters under the prefix when reloading the cache. In general, this is much more efficient than calling SSM for each individual parameter. However, you may want to consider disabling this behavior via the `bulkLoad` constructor argument in cases where there are many thousands of parameters under that path prefix, and the calling code only needs a few of them, since bulk loading all of the parameter values could result in unnecessary throttling and latency. 91 | 92 | Note: In the case where you request a parameter that does not exist from the caching client, it will always attempt to load the value from AWS SSM Parameter Store. This could cause an availability issue if a code update adds a call to the client with an invalid parameter name, e.g., a misspelling. If this change made it to production, you could have many clients making calls to SSM, causing throttling which can lead to latency/availability issues. The mitigation for this is to use deployment best practices such as deploying new code updates to a development environment first and running integration tests to catch bugs like misspelled or missing parameters before deploying the code updates to production environments. 93 | 94 | ### Security Considerations 95 | 96 | AWS SSM Parameter Store allows storing SecureString parameters, which are encrypted within AWS SSM. The caching client calls SSM with decryption enabled, meaning the decrypted values will be stored in-memory in plain text. The library does not log decrypted values. 97 | 98 | ## License Summary 99 | 100 | This sample code is made available under the Apache 2.0 license. See the LICENSE file. 101 | -------------------------------------------------------------------------------- /buildspec.yaml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | 3 | phases: 4 | install: 5 | runtime-versions: 6 | java: openjdk8 7 | build: 8 | commands: 9 | - mvn clean package 10 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | software.amazon.serverless 8 | aws-ssm-java-caching-client 9 | 1.0.0 10 | 11 | aws-ssm-java-caching-client 12 | A Java implementation of client-side caching library for AWS Systems Manager Parameter Store. 13 | https://github.com/awslabs/aws-ssm-java-caching-client 14 | 15 | 16 | scm:git:https://github.com/awslabs/aws-ssm-java-caching-client.git 17 | scm:git:git@github.com:awslabs/aws-ssm-java-caching-client.git 18 | https://github.com/awslabs/aws-ssm-java-caching-client 19 | 20 | 21 | 22 | 23 | amazonwebservices 24 | Amazon Web Services 25 | https://aws.amazon.com 26 | 27 | developer 28 | 29 | 30 | 31 | 32 | 33 | 34 | Apache License, Version 2.0 35 | https://aws.amazon.com/apache2.0 36 | repo 37 | 38 | 39 | 40 | 41 | 42 | sonatype-nexus-staging 43 | https://oss.sonatype.org/content/repositories/snapshots 44 | 45 | 46 | sonatype-nexus-staging 47 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 48 | 49 | 50 | 51 | 52 | UTF-8 53 | 54 | 55 | 56 | 57 | 58 | org.apache.maven.plugins 59 | maven-compiler-plugin 60 | 61 | 1.8 62 | 1.8 63 | 64 | 65 | 66 | org.jacoco 67 | jacoco-maven-plugin 68 | 0.8.0 69 | 70 | 71 | prepare-agent 72 | 73 | prepare-agent 74 | 75 | 76 | 77 | 78 | 79 | org.eluder.coveralls 80 | coveralls-maven-plugin 81 | 4.3.0 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | software.amazon.awssdk 90 | bom 91 | 2.8.0 92 | pom 93 | import 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | org.projectlombok 102 | lombok 103 | 1.16.6 104 | provided 105 | 106 | 107 | 108 | 109 | org.slf4j 110 | slf4j-api 111 | 1.7.25 112 | 113 | 114 | software.amazon.awssdk 115 | ssm 116 | 117 | 118 | 119 | 120 | junit 121 | junit 122 | 4.12 123 | test 124 | 125 | 126 | org.mockito 127 | mockito-core 128 | 2.0.100-beta 129 | test 130 | 131 | 132 | org.assertj 133 | assertj-core 134 | 3.13.2 135 | test 136 | 137 | 138 | org.apache.logging.log4j 139 | log4j-api 140 | 2.10.0 141 | test 142 | 143 | 144 | org.apache.logging.log4j 145 | log4j-core 146 | 2.10.0 147 | test 148 | 149 | 150 | org.apache.logging.log4j 151 | log4j-slf4j-impl 152 | 2.10.0 153 | test 154 | 155 | 156 | 157 | 158 | 159 | release 160 | 161 | 162 | 163 | 164 | org.apache.maven.plugins 165 | maven-source-plugin 166 | 3.0.1 167 | 168 | 169 | attach-sources 170 | 171 | jar-no-fork 172 | 173 | 174 | 175 | 176 | 177 | 178 | org.apache.maven.plugins 179 | maven-javadoc-plugin 180 | 2.10.3 181 | 182 | ${project.basedir}/src/software/amazon/serverless/overview.html 183 | Amazon SSM Java Caching Client ${project.version} API Reference 184 | Amazon SSM Java Caching Client ${project.version} 185 |
Amazon SSM Java Caching Client ${project.version} API Reference
186 | UTF-8 187 | Copyright © 2019 Amazon.com. All Rights Reserved.]]> 188 | Amazon SSM Java Caching Client Javadoc 189 | -Xdoclint:none 190 |
191 | 192 | 193 | attach-javadocs 194 | 195 | jar 196 | 197 | 198 | 199 |
200 | 201 | 202 | org.apache.maven.plugins 203 | maven-gpg-plugin 204 | 1.6 205 | 206 | 207 | sign-artifacts 208 | verify 209 | 210 | sign 211 | 212 | 213 | 214 | 215 | 216 | 217 | org.sonatype.plugins 218 | nexus-staging-maven-plugin 219 | 1.6.7 220 | true 221 | 222 | sonatype-nexus-staging 223 | https://aws.oss.sonatype.org/ 224 | false 225 | 226 | 227 |
228 |
229 |
230 |
231 |
232 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/serverless/ssmcachingclient/SsmParameterCachingClient.java: -------------------------------------------------------------------------------- 1 | package software.amazon.serverless.ssmcachingclient; 2 | 3 | import java.time.Clock; 4 | import java.time.Duration; 5 | import java.time.Instant; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import java.util.concurrent.ConcurrentHashMap; 9 | import java.util.concurrent.ConcurrentMap; 10 | 11 | import lombok.NonNull; 12 | import lombok.Value; 13 | import lombok.extern.slf4j.Slf4j; 14 | import software.amazon.awssdk.services.ssm.SsmClient; 15 | import software.amazon.awssdk.services.ssm.model.GetParameterRequest; 16 | import software.amazon.awssdk.services.ssm.model.GetParameterResponse; 17 | import software.amazon.awssdk.services.ssm.model.GetParametersByPathRequest; 18 | import software.amazon.awssdk.services.ssm.model.Parameter; 19 | import software.amazon.awssdk.services.ssm.model.ParameterNotFoundException; 20 | import software.amazon.awssdk.services.ssm.model.ParameterType; 21 | import software.amazon.awssdk.services.ssm.paginators.GetParametersByPathIterable; 22 | 23 | /** 24 | * The SsmParameterCachingClient is a thread-safe class that provides an in-memory caching layer over SSM Parameter Store. 25 | * This is useful when using the "standard" SSM Parameter Store (free service), which only supports a small number of 26 | * transactions per second (TPS). 27 | *

28 | * Security Note: All calls made to SSM Parameter Store decrypt SecureString parameter values and cache them in plain text in the 29 | * in-memory cache. However, this class does not write decrypted SecureString values to disk. 30 | *

31 | *

Using pathPrefix

32 | *

33 | * The client accepts a parameter path prefix, which allows it to make more efficient bulk calls to the SSM Parameter Store API 34 | * and bulk load all parameters under the given path prefix at once. For example, you might use the following hierarchy for storing 35 | * parameters for FooService: 36 | *

37 | *

 38 |  *     /FooService/Dev/DbTableName
 39 |  *     /FooService/Dev/NotificationTopicArn
 40 |  *     /FooService/Prod/DbTableName
 41 |  *     /FooService/Prod/NotificationTopicArn
 42 |  * 
43 | *

44 | * In this example, there are separate parameters for FooService depending on if the environment is Dev or Prod. If SsmParameterCachingClient 45 | * is passed "/FooService/Dev/" as the pathPrefix, it will make a bulk call to the SSM Parameter Store API to load and cache all 46 | * parameters that start with "/FooService/Dev/". 47 | *

48 | * Also, the get methods on the client will automatically prepend the pathPrefix so you can initialize the client once with the pathPrefix and 49 | * then reference the parameters without the prefix from there on out: 50 | *

51 | *

 52 |  * // initialization code
 53 |  * SsmClient ssm = SsmClient.create();
 54 |  * SsmParameterCachingClient client = new SsmParameterCachingClient(ssm, Duration.ofSeconds(60), "/FooService/Dev/");
 55 |  *
 56 |  * ...
 57 |  *
 58 |  * // elsewhere in your business logic
 59 |  * client.getAsString("DbTableName");
 60 |  * 
61 | *

62 | * Using this pattern, only your initialization code needs to know what environment you're running in, and the rest of your business logic can 63 | * refer to the parameters without the prefix. 64 | *

65 | * For more information on organizing parameters into hierarchies, see the 66 | * AWS Systems Manager User Guide. 67 | */ 68 | @Slf4j 69 | public class SsmParameterCachingClient { 70 | private final SsmClient ssm; 71 | private final Duration ttl; 72 | private final String pathPrefix; 73 | private final boolean allowStaleValues; 74 | private final boolean bulkLoad; 75 | private final Clock clock; 76 | 77 | private volatile ConcurrentMap cache; 78 | 79 | @Value 80 | private static final class CachedParameter { 81 | private final Parameter parameter; 82 | private final Instant loadedAt; 83 | } 84 | 85 | /** 86 | * Package-private constructor for unit testing only. 87 | * 88 | * @param ssm AWS SSM client. 89 | * @param ttl The cache time-to-live (TTL), which is the duration before a cached value will be considered stale. 90 | * @param pathPrefix Parameter path prefix to prepend to all parameter names passed to get methods. 91 | * @param allowStaleValues If set to true, the client will fall back to returning stale cached values if SSM cannot be reached to refresh the cache. 92 | * @param bulkLoad If set to true and pathPrefix is non-null, the client will bulk load and cache all parameters for the given pathPrefix once the cache is stale, rather than loading them one at a time. 93 | * @param clock Clock override for unit testing. 94 | */ 95 | SsmParameterCachingClient(@NonNull final SsmClient ssm, final Duration ttl, final String pathPrefix, final boolean allowStaleValues, final boolean bulkLoad, final Clock clock) { 96 | this.ssm = ssm; 97 | this.ttl = ttl; 98 | this.pathPrefix = pathPrefix; 99 | this.allowStaleValues = allowStaleValues; 100 | this.bulkLoad = bulkLoad; 101 | this.clock = clock; 102 | 103 | this.cache = new ConcurrentHashMap<>(); 104 | } 105 | 106 | /** 107 | * Create a new caching client. 108 | * 109 | * @param ssm AWS SSM client. 110 | * @param ttl The cache time-to-live (TTL), which is the duration before a cached value will be considered stale. 111 | * @param pathPrefix Parameter path prefix to prepend to all parameter names passed to get methods. 112 | * @param allowStaleValues If set to true, the client will fall back to returning stale cached values if SSM cannot be reached to refresh the cache. 113 | * @param bulkLoad If set to true and pathPrefix is non-null, the client will bulk load and cache all parameters for the given pathPrefix once the cache is stale, rather than loading them one at a time. 114 | */ 115 | public SsmParameterCachingClient(final SsmClient ssm, final Duration ttl, final String pathPrefix, final boolean allowStaleValues, final boolean bulkLoad) { 116 | this(ssm, ttl, pathPrefix, allowStaleValues, bulkLoad, Clock.systemUTC()); 117 | } 118 | 119 | /** 120 | * Convenience constructor for creating a new caching client. Defaults to setting allowStaleValues and bulkLoad to true. 121 | * 122 | * @param ssm AWS SSM client. 123 | * @param ttl The cache time-to-live (TTL), which is the duration before a cached value will be considered stale. 124 | * @param pathPrefix Parameter path prefix to prepend to all parameter names passed to #get(). 125 | */ 126 | public SsmParameterCachingClient(final SsmClient ssm, final Duration ttl, final String pathPrefix) { 127 | this(ssm, ttl, pathPrefix, true, true); 128 | } 129 | 130 | /** 131 | * Convenience constructor for creating a new caching client. Defaults to setting pathPrefix to null, and allowStaleValues and bulkLoad to true. 132 | * 133 | * @param ssm AWS SSM client. 134 | * @param ttl The cache time-to-live (TTL), which is the duration before a cached value will be considered stale. 135 | */ 136 | public SsmParameterCachingClient(final SsmClient ssm, final Duration ttl) { 137 | this(ssm, ttl, null); 138 | } 139 | 140 | /** 141 | * Get a parameter value. 142 | * 143 | * @param name Parameter name to get. If a pathPrefix has been supplied, it is prepended to name. 144 | * @return Full Parameter object returned by SSM client. 145 | */ 146 | public Parameter get(final String name) { 147 | CachedParameter cached = getCachedParameter(name); 148 | if (isStale(cached)) { 149 | log.debug("SSM Parameter cache miss for pathPrefix={}, name={}. Attempting to load value from SSM.", pathPrefix, name); 150 | try { 151 | cached = load(name); 152 | } catch (Exception e) { 153 | // only case where we don't allow stale values is if we found out the parameter they're requesting doesn't exist 154 | if (e instanceof ParameterNotFoundException) { 155 | throw e; 156 | } 157 | 158 | if (allowStaleValues && cached != null) { 159 | log.warn(String.format("Failed to update cache from SSM for pathPrefix=%s, name=%s. Returning stale value instead.", pathPrefix, name), e); 160 | return cached.getParameter(); 161 | } 162 | throw e; 163 | } 164 | } else { 165 | log.debug("SSM Parameter cache hit for pathPrefix={}, name={}. Returning cached value.", pathPrefix, name); 166 | } 167 | 168 | return cached.parameter; 169 | } 170 | 171 | private CachedParameter getCachedParameter(final String name) { 172 | String resolvedName = resolvedName(name); 173 | return cache.get(resolvedName); 174 | } 175 | 176 | private String resolvedName(final String name) { 177 | if (pathPrefix == null) { 178 | return name; 179 | } 180 | return pathPrefix + name; 181 | } 182 | 183 | private boolean isStale(CachedParameter cached) { 184 | return cached == null || Instant.now(clock).isAfter(cached.getLoadedAt().plus(ttl)); 185 | } 186 | 187 | private CachedParameter load(String name) { 188 | String resolvedName = resolvedName(name); 189 | if (bulkLoad && pathPrefix != null) { 190 | return bulkLoad(resolvedName); 191 | } 192 | return loadSingleValue(resolvedName); 193 | } 194 | 195 | private CachedParameter bulkLoad(final String resolvedName) { 196 | log.debug("Bulk loading and caching all parameters for pathPrefix={} from SSM", pathPrefix); 197 | // Call GetParametersByPath API, paginate through and replace cache with new values. 198 | GetParametersByPathRequest request = GetParametersByPathRequest.builder() 199 | .path(pathPrefix) 200 | .recursive(true) 201 | .withDecryption(true) 202 | .build(); 203 | GetParametersByPathIterable iterable = ssm.getParametersByPathPaginator(request); 204 | 205 | ConcurrentMap newCache = new ConcurrentHashMap<>(); 206 | iterable.stream() 207 | .flatMap(r -> r.parameters().stream()) 208 | .forEach(p -> newCache.put(p.name(), new CachedParameter(p, Instant.now(clock)))); 209 | 210 | if (!newCache.containsKey(resolvedName)) { 211 | // if parameter they requested isn't in the results, it doesn't exist in SSM. Call SSM for that specific 212 | // parameter so the SSM not found exception is thrown back to the caller. 213 | log.debug("Bulk load results did not contain parameter {}", resolvedName); 214 | loadSingleValue(resolvedName); 215 | 216 | // shouldn't get here 217 | throw new IllegalStateException( 218 | String.format("Could not find SSM parameter via GetParametersByPath(path=%s), but found it with GetParameter(name=%s). This is probably a bug in the caching client", 219 | pathPrefix, resolvedName)); 220 | } 221 | 222 | // replace cache in case previously cached values have since been removed from SSM parameter store 223 | cache = newCache; 224 | return cache.get(resolvedName); 225 | } 226 | 227 | private CachedParameter loadSingleValue(final String resolvedName) { 228 | log.debug("Loading and caching single value {} from SSM", resolvedName); 229 | GetParameterRequest request = GetParameterRequest.builder() 230 | .name(resolvedName) 231 | .withDecryption(true) 232 | .build(); 233 | 234 | GetParameterResponse response = ssm.getParameter(request); 235 | 236 | CachedParameter cached = new CachedParameter(response.parameter(), Instant.now(clock)); 237 | cache.put(response.parameter().name(), cached); 238 | 239 | return cached; 240 | } 241 | 242 | /** 243 | * Get a parameter value as a String. 244 | * 245 | * @param name Parameter name to get. If a pathPrefix has been supplied, it is prepended to name. 246 | * @return Parameter value as a string. 247 | */ 248 | public String getAsString(final String name) { 249 | return get(name).value(); 250 | } 251 | 252 | /** 253 | * Get a parameter value as a List of Strings. 254 | * 255 | * @param name Parameter name to get. If a pathPrefix has been supplied, it is prepended to name. 256 | * @return Parameter value as a list of strings. List is generated by splitting the parameter string using ',' as a delimiter. 257 | * @throws IllegalArgumentException if returned parameter is not of type StringList. 258 | */ 259 | public List getAsStringList(final String name) { 260 | Parameter parameter = get(name); 261 | if (parameter.type() != ParameterType.STRING_LIST) { 262 | throw new IllegalArgumentException(String.format("Parameter %s is of type %s, expected StringList", parameter.name(), parameter.type())); 263 | } 264 | 265 | return Arrays.asList(parameter.value().split(",")); 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /src/main/lombok.config: -------------------------------------------------------------------------------- 1 | # https://projectlombok.org/api/lombok/ConfigurationKeys.html 2 | 3 | # @NonNull parameters should throw IllegalArgumentException, not NullPointerException 4 | lombok.nonNull.exceptionType = IllegalArgumentException 5 | 6 | config.stopBubbling = true -------------------------------------------------------------------------------- /src/test/java/software/amazon/serverless/ssmcachingclient/SsmParameterCachingClientTest.java: -------------------------------------------------------------------------------- 1 | package software.amazon.serverless.ssmcachingclient; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 5 | import static org.mockito.ArgumentMatchers.any; 6 | import static org.mockito.Mockito.mock; 7 | import static org.mockito.Mockito.times; 8 | import static org.mockito.Mockito.verify; 9 | import static org.mockito.Mockito.verifyNoMoreInteractions; 10 | import static org.mockito.Mockito.when; 11 | 12 | import java.time.Clock; 13 | import java.time.Duration; 14 | import java.time.Instant; 15 | import java.util.Arrays; 16 | 17 | import org.junit.Before; 18 | import org.junit.Test; 19 | import org.mockito.Mock; 20 | import org.mockito.MockitoAnnotations; 21 | 22 | import software.amazon.awssdk.awscore.exception.AwsServiceException; 23 | import software.amazon.awssdk.services.ssm.SsmClient; 24 | import software.amazon.awssdk.services.ssm.model.GetParameterRequest; 25 | import software.amazon.awssdk.services.ssm.model.GetParameterResponse; 26 | import software.amazon.awssdk.services.ssm.model.GetParametersByPathRequest; 27 | import software.amazon.awssdk.services.ssm.model.GetParametersByPathResponse; 28 | import software.amazon.awssdk.services.ssm.model.Parameter; 29 | import software.amazon.awssdk.services.ssm.model.ParameterNotFoundException; 30 | import software.amazon.awssdk.services.ssm.model.ParameterType; 31 | import software.amazon.awssdk.services.ssm.paginators.GetParametersByPathIterable; 32 | 33 | public class SsmParameterCachingClientTest { 34 | private static final String PATH_PREFIX = "/foo/"; 35 | private static final Duration TTL = Duration.ofSeconds(1); 36 | 37 | private static final String STRING_PARAMETER_KEY_SUFFIX = "string"; 38 | private static final String STRING_PARAMETER_KEY = PATH_PREFIX + STRING_PARAMETER_KEY_SUFFIX; 39 | private static final String STRING_PARAMETER_VALUE = "stringvalue"; 40 | private static final Parameter STRING_PARAMETER = Parameter.builder() 41 | .name(STRING_PARAMETER_KEY) 42 | .type(ParameterType.STRING) 43 | .value(STRING_PARAMETER_VALUE) 44 | .build(); 45 | 46 | private static final String STRING_LIST_PARAMETER_KEY_SUFFIX = "stringlist"; 47 | private static final String STRING_LIST_PARAMETER_KEY = PATH_PREFIX + STRING_LIST_PARAMETER_KEY_SUFFIX; 48 | private static final String STRING_LIST_PARAMETER_VALUE = "a,b,c"; 49 | private static final Parameter STRING_LIST_PARAMETER = Parameter.builder() 50 | .name(STRING_LIST_PARAMETER_KEY) 51 | .type(ParameterType.STRING_LIST) 52 | .value(STRING_LIST_PARAMETER_VALUE) 53 | .build(); 54 | 55 | private static final String NOT_FOUND_PARAMETER_KEY_SUFFIX = "not here!"; 56 | private static final String NOT_FOUND_PARAMETER_KEY = PATH_PREFIX + NOT_FOUND_PARAMETER_KEY_SUFFIX; 57 | 58 | @Mock 59 | private SsmClient ssm; 60 | @Mock 61 | private GetParametersByPathIterable iterable; 62 | 63 | private SsmParameterCachingClient client; 64 | 65 | @Before 66 | public void setup() throws Exception { 67 | MockitoAnnotations.initMocks(this); 68 | mockParameters(); 69 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX); 70 | } 71 | 72 | private void mockParameters() { 73 | when(ssm.getParameter( 74 | GetParameterRequest.builder() 75 | .name(STRING_PARAMETER_KEY) 76 | .withDecryption(true) 77 | .build() 78 | )).thenReturn( 79 | GetParameterResponse.builder() 80 | .parameter(STRING_PARAMETER) 81 | .build() 82 | ); 83 | 84 | when(ssm.getParameter( 85 | GetParameterRequest.builder() 86 | .name(STRING_LIST_PARAMETER_KEY) 87 | .withDecryption(true) 88 | .build() 89 | )).thenReturn( 90 | GetParameterResponse.builder() 91 | .parameter(STRING_LIST_PARAMETER) 92 | .build() 93 | ); 94 | 95 | when(ssm.getParameter( 96 | GetParameterRequest.builder() 97 | .name(NOT_FOUND_PARAMETER_KEY) 98 | .withDecryption(true) 99 | .build() 100 | )).thenThrow(ParameterNotFoundException.class); 101 | 102 | when(ssm.getParametersByPathPaginator(any(GetParametersByPathRequest.class))).thenReturn(iterable); 103 | GetParametersByPathResponse response = GetParametersByPathResponse.builder() 104 | .parameters(STRING_PARAMETER, STRING_LIST_PARAMETER) 105 | .build(); 106 | when(iterable.stream()).thenReturn(Arrays.asList(response).stream()); 107 | } 108 | 109 | @Test 110 | public void new_nullSsmClient() throws Exception { 111 | assertThatThrownBy(() -> new SsmParameterCachingClient(null, TTL, PATH_PREFIX)).isInstanceOf(IllegalArgumentException.class); 112 | } 113 | 114 | @Test 115 | public void get_bulkLoad() throws Exception { 116 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 117 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 118 | assertThat(client.get(STRING_LIST_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_LIST_PARAMETER); 119 | assertThat(client.get(STRING_LIST_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_LIST_PARAMETER); 120 | 121 | GetParametersByPathRequest expected = GetParametersByPathRequest.builder() 122 | .path(PATH_PREFIX) 123 | .recursive(true) 124 | .withDecryption(true) 125 | .build(); 126 | 127 | // should only have been called the first time 128 | verify(ssm, times(1)).getParametersByPathPaginator(expected); 129 | 130 | verifyNoMoreInteractions(ssm); 131 | } 132 | 133 | @Test 134 | public void get_bulkLoad_parameterNotFound() throws Exception { 135 | assertThatThrownBy(() -> client.get(NOT_FOUND_PARAMETER_KEY_SUFFIX)).isInstanceOf(ParameterNotFoundException.class); 136 | 137 | GetParametersByPathRequest expectedBulkRequest = GetParametersByPathRequest.builder() 138 | .path(PATH_PREFIX) 139 | .recursive(true) 140 | .withDecryption(true) 141 | .build(); 142 | verify(ssm).getParametersByPathPaginator(expectedBulkRequest); 143 | 144 | GetParameterRequest expectedSingleRequest = GetParameterRequest.builder() 145 | .name(NOT_FOUND_PARAMETER_KEY) 146 | .withDecryption(true) 147 | .build(); 148 | verify(ssm).getParameter(expectedSingleRequest); 149 | 150 | verifyNoMoreInteractions(ssm); 151 | } 152 | 153 | @Test 154 | public void get_bulkLoad_noPathPrefix() throws Exception { 155 | client = new SsmParameterCachingClient(ssm, TTL); 156 | 157 | assertThat(client.get(STRING_PARAMETER_KEY)).isEqualTo(STRING_PARAMETER); 158 | assertThat(client.get(STRING_PARAMETER_KEY)).isEqualTo(STRING_PARAMETER); 159 | assertThat(client.get(STRING_LIST_PARAMETER_KEY)).isEqualTo(STRING_LIST_PARAMETER); 160 | assertThat(client.get(STRING_LIST_PARAMETER_KEY)).isEqualTo(STRING_LIST_PARAMETER); 161 | 162 | GetParameterRequest expectedStringParameterRequest = GetParameterRequest.builder() 163 | .name(STRING_PARAMETER_KEY) 164 | .withDecryption(true) 165 | .build(); 166 | verify(ssm, times(1)).getParameter(expectedStringParameterRequest); 167 | GetParameterRequest expectedStringListParameterRequest = GetParameterRequest.builder() 168 | .name(STRING_LIST_PARAMETER_KEY) 169 | .withDecryption(true) 170 | .build(); 171 | verify(ssm, times(1)).getParameter(expectedStringListParameterRequest); 172 | 173 | verifyNoMoreInteractions(ssm); 174 | } 175 | 176 | @Test 177 | public void get_noBulkLoad() throws Exception { 178 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX, true, false); 179 | 180 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 181 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 182 | assertThat(client.get(STRING_LIST_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_LIST_PARAMETER); 183 | assertThat(client.get(STRING_LIST_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_LIST_PARAMETER); 184 | 185 | GetParameterRequest expectedStringParameterRequest = GetParameterRequest.builder() 186 | .name(STRING_PARAMETER_KEY) 187 | .withDecryption(true) 188 | .build(); 189 | verify(ssm, times(1)).getParameter(expectedStringParameterRequest); 190 | GetParameterRequest expectedStringListParameterRequest = GetParameterRequest.builder() 191 | .name(STRING_LIST_PARAMETER_KEY) 192 | .withDecryption(true) 193 | .build(); 194 | verify(ssm, times(1)).getParameter(expectedStringListParameterRequest); 195 | 196 | verifyNoMoreInteractions(ssm); 197 | } 198 | 199 | @Test 200 | public void get_noBulkLoad_parameterNotFound() throws Exception { 201 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX, true, false); 202 | 203 | assertThatThrownBy(() -> client.get(NOT_FOUND_PARAMETER_KEY_SUFFIX)).isInstanceOf(ParameterNotFoundException.class); 204 | 205 | GetParameterRequest expected = GetParameterRequest.builder() 206 | .name(NOT_FOUND_PARAMETER_KEY) 207 | .withDecryption(true) 208 | .build(); 209 | verify(ssm).getParameter(expected); 210 | 211 | verifyNoMoreInteractions(ssm); 212 | } 213 | 214 | @Test 215 | public void get_staleCache_ssmSuccess() throws Exception { 216 | Clock clock = mock(Clock.class); 217 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX, true, true, clock); 218 | 219 | Instant now = Instant.now(); 220 | when(clock.instant()).thenReturn(now); 221 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 222 | 223 | when(clock.instant()).thenReturn(now.plus(Duration.ofSeconds(TTL.getSeconds() + 1))); 224 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 225 | 226 | GetParametersByPathRequest expected = GetParametersByPathRequest.builder() 227 | .path(PATH_PREFIX) 228 | .recursive(true) 229 | .withDecryption(true) 230 | .build(); 231 | 232 | verify(ssm, times(2)).getParametersByPathPaginator(expected); 233 | 234 | verifyNoMoreInteractions(ssm); 235 | } 236 | 237 | @Test 238 | public void get_staleCache_ssmParameterNotFound() throws Exception { 239 | Clock clock = mock(Clock.class); 240 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX, true, false, clock); 241 | 242 | Instant now = Instant.now(); 243 | when(clock.instant()).thenReturn(now); 244 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 245 | 246 | when(clock.instant()).thenReturn(now.plus(Duration.ofSeconds(TTL.getSeconds() + 1))); 247 | when(ssm.getParameter( 248 | GetParameterRequest.builder() 249 | .name(STRING_PARAMETER_KEY) 250 | .withDecryption(true) 251 | .build() 252 | )).thenThrow(ParameterNotFoundException.class); 253 | assertThatThrownBy(() -> client.get(STRING_PARAMETER_KEY_SUFFIX)).isInstanceOf(ParameterNotFoundException.class); 254 | } 255 | 256 | @Test 257 | public void get_staleCache_ssmOtherException_allowStaleValues() throws Exception { 258 | Clock clock = mock(Clock.class); 259 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX, true, false, clock); 260 | 261 | Instant now = Instant.now(); 262 | when(clock.instant()).thenReturn(now); 263 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 264 | 265 | when(clock.instant()).thenReturn(now.plus(Duration.ofSeconds(TTL.getSeconds() + 1))); 266 | when(ssm.getParameter( 267 | GetParameterRequest.builder() 268 | .name(STRING_PARAMETER_KEY) 269 | .withDecryption(true) 270 | .build() 271 | )).thenThrow(AwsServiceException.class); 272 | 273 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 274 | } 275 | 276 | @Test 277 | public void get_staleCache_ssmOtherException_noAllowStaleValues() throws Exception { 278 | Clock clock = mock(Clock.class); 279 | client = new SsmParameterCachingClient(ssm, TTL, PATH_PREFIX, false, false, clock); 280 | 281 | Instant now = Instant.now(); 282 | when(clock.instant()).thenReturn(now); 283 | assertThat(client.get(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER); 284 | 285 | when(clock.instant()).thenReturn(now.plus(Duration.ofSeconds(TTL.getSeconds() + 1))); 286 | when(ssm.getParameter( 287 | GetParameterRequest.builder() 288 | .name(STRING_PARAMETER_KEY) 289 | .withDecryption(true) 290 | .build() 291 | )).thenThrow(new RuntimeException("boom!")); 292 | 293 | assertThatThrownBy(() -> client.get(STRING_PARAMETER_KEY_SUFFIX)) 294 | .isInstanceOf(RuntimeException.class) 295 | .hasMessage("boom!"); 296 | } 297 | 298 | @Test 299 | public void getAsString() throws Exception { 300 | assertThat(client.getAsString(STRING_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_PARAMETER_VALUE); 301 | assertThat(client.getAsString(STRING_LIST_PARAMETER_KEY_SUFFIX)).isEqualTo(STRING_LIST_PARAMETER_VALUE); 302 | } 303 | 304 | @Test 305 | public void getAsStringList() throws Exception { 306 | assertThat(client.getAsStringList(STRING_LIST_PARAMETER_KEY_SUFFIX)).isEqualTo(Arrays.asList("a", "b", "c")); 307 | } 308 | 309 | @Test 310 | public void getAsStringList_wrongType() throws Exception { 311 | assertThatThrownBy(() -> client.getAsStringList(STRING_PARAMETER_KEY_SUFFIX)).isInstanceOf(IllegalArgumentException.class); 312 | } 313 | } -------------------------------------------------------------------------------- /src/test/resources/log4j2-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | --------------------------------------------------------------------------------