aurora-dsql-ruby-pg 1.0.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.
- checksums.yaml +7 -0
- data/LICENSE +175 -0
- data/NOTICE +1 -0
- data/README.md +227 -0
- data/lib/aurora_dsql/pg/config.rb +175 -0
- data/lib/aurora_dsql/pg/connection.rb +72 -0
- data/lib/aurora_dsql/pg/occ_retry.rb +97 -0
- data/lib/aurora_dsql/pg/pool.rb +100 -0
- data/lib/aurora_dsql/pg/token.rb +39 -0
- data/lib/aurora_dsql/pg/util.rb +41 -0
- data/lib/aurora_dsql/pg/version.rb +17 -0
- data/lib/aurora_dsql_pg.rb +26 -0
- metadata +133 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 0af7ba782ac3c43e13044ec8ef592bf162fae89aabba8228747542d80e1eb79b
|
|
4
|
+
data.tar.gz: 8fcb277ac218333d5835dcca93628f3897c59770409f09970cd4ec4d6d193c86
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 8a5478e20f6359ec8b5641a2f075711b0a8c642614c8d891f7d258b0a19f3bcb5fdb5e466e8032685a59eb0228f03733d6e2f250291191de1766b83fe4426fbd
|
|
7
|
+
data.tar.gz: f73b1322c292ae87a9583636246a3e1b7d9e1a78caf7b301efe7afd070e9cd7852cc5eb3f45da255af2a2c20ab5d9d0ba542303b64e5ab8357003b93ddb5c8b7
|
data/LICENSE
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
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.
|
data/NOTICE
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
data/README.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
# Aurora DSQL Ruby pg Connector
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
A Ruby connector for Amazon Aurora DSQL that wraps the [pg](https://github.com/ged/ruby-pg) gem with automatic IAM authentication. The connector handles token generation, SSL configuration, and connection pooling so you can focus on your application logic.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Automatic IAM token generation
|
|
10
|
+
- Connection pooling via `connection_pool` gem with max_lifetime enforcement
|
|
11
|
+
- Single connection support for simpler use cases
|
|
12
|
+
- Flexible host configuration (full endpoint or cluster ID)
|
|
13
|
+
- Region auto-detection from endpoint hostname
|
|
14
|
+
- Support for AWS profiles and custom credentials providers
|
|
15
|
+
- SSL always enabled with `verify-full` mode and direct TLS negotiation (libpq 17+)
|
|
16
|
+
- Opt-in OCC retry with exponential backoff on `pool.with`
|
|
17
|
+
|
|
18
|
+
## Prerequisites
|
|
19
|
+
|
|
20
|
+
- Ruby 3.1 or later
|
|
21
|
+
- AWS credentials configured (see [Credentials Resolution](#credentials-resolution) below)
|
|
22
|
+
- An Aurora DSQL cluster
|
|
23
|
+
|
|
24
|
+
For information about creating an Aurora DSQL cluster, see the [Getting started with Aurora DSQL](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/getting-started.html) guide.
|
|
25
|
+
|
|
26
|
+
### Credentials Resolution
|
|
27
|
+
|
|
28
|
+
The connector uses the [AWS SDK for Ruby default credential chain](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html), which resolves credentials in the following order:
|
|
29
|
+
|
|
30
|
+
1. **Environment variables** (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and optionally `AWS_SESSION_TOKEN`)
|
|
31
|
+
2. **Shared credentials file** (`~/.aws/credentials`) with optional profile via `AWS_PROFILE` or `profile` config
|
|
32
|
+
3. **Shared config file** (`~/.aws/config`)
|
|
33
|
+
4. **IAM role for Amazon EC2/ECS/Lambda** (instance metadata or task role)
|
|
34
|
+
|
|
35
|
+
The first source that provides valid credentials is used. You can override this by specifying `profile` for a specific AWS profile or `credentials_provider` for complete control over credential resolution.
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Add to your Gemfile:
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
gem "aurora-dsql-ruby-pg"
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Or install directly:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
gem install aurora-dsql-ruby-pg
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quick Start
|
|
52
|
+
|
|
53
|
+
```ruby
|
|
54
|
+
require "aurora_dsql_pg"
|
|
55
|
+
|
|
56
|
+
# Create a connection pool with OCC retry enabled
|
|
57
|
+
pool = AuroraDsql::Pg.create_pool(
|
|
58
|
+
host: "your-cluster.dsql.us-east-1.on.aws",
|
|
59
|
+
occ_max_retries: 3
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Read
|
|
63
|
+
pool.with do |conn|
|
|
64
|
+
result = conn.exec("SELECT 'Hello, DSQL!'")
|
|
65
|
+
puts result[0]["?column?"]
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Write — you must wrap writes in a transaction
|
|
69
|
+
pool.with do |conn|
|
|
70
|
+
conn.transaction do
|
|
71
|
+
conn.exec_params("INSERT INTO users (id, name) VALUES (gen_random_uuid(), $1)", ["Alice"])
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
pool.shutdown
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Configuration Options
|
|
79
|
+
|
|
80
|
+
| Field | Type | Default | Description |
|
|
81
|
+
|-------|------|---------|-------------|
|
|
82
|
+
| `host` | `String` | (required) | Cluster endpoint or cluster ID |
|
|
83
|
+
| `region` | `String` | (auto-detected) | AWS region |
|
|
84
|
+
| `user` | `String` | `"admin"` | Database user |
|
|
85
|
+
| `database` | `String` | `"postgres"` | Database name |
|
|
86
|
+
| `port` | `Integer` | `5432` | Database port |
|
|
87
|
+
| `profile` | `String` | `nil` | AWS profile name |
|
|
88
|
+
| `token_duration` | `Integer` | `900` (15 min) | Token validity in seconds |
|
|
89
|
+
| `credentials_provider` | `Aws::Credentials` | `nil` | Custom credentials |
|
|
90
|
+
| `pool_size` | `Integer` | `5` | Connection pool size |
|
|
91
|
+
| `checkout_timeout` | `Integer` | `5` | Seconds to wait for a pool connection |
|
|
92
|
+
| `max_lifetime` | `Integer` | `3300` (55 min) | Max connection lifetime in seconds |
|
|
93
|
+
| `application_name` | `String` | `nil` | ORM prefix for application_name |
|
|
94
|
+
| `logger` | `Logger` | `nil` | Logger for OCC retry warnings |
|
|
95
|
+
| `occ_max_retries` | `Integer` | `nil` (disabled) | Max OCC retries on `pool.with`; enables retry when set |
|
|
96
|
+
|
|
97
|
+
## Connection String Format
|
|
98
|
+
|
|
99
|
+
```ruby
|
|
100
|
+
pool = AuroraDsql::Pg.create_pool(
|
|
101
|
+
"postgres://admin@cluster.dsql.us-east-1.on.aws/postgres?profile=dev"
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Single Connection Usage
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
conn = AuroraDsql::Pg.connect(host: "cluster.dsql.us-east-1.on.aws")
|
|
109
|
+
conn.exec("SELECT 1")
|
|
110
|
+
conn.close
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The `Connection` wrapper delegates common methods (`exec_params`, `query`, `transaction`, `close`, `finished?`) directly. All other `PG::Connection` methods (e.g., `exec`, `prepare`, `exec_prepared`, `copy_data`) are also available via delegation. The underlying `PG::Connection` can be accessed directly via `conn.pg_conn` if needed.
|
|
114
|
+
|
|
115
|
+
## OCC Retry
|
|
116
|
+
|
|
117
|
+
Aurora DSQL uses optimistic concurrency control (OCC). When two transactions modify the same data, the first to commit wins and the second receives an OCC error.
|
|
118
|
+
|
|
119
|
+
OCC retry is **opt-in**. Set `occ_max_retries` when creating the pool to enable automatic retry with exponential backoff and jitter on `pool.with`:
|
|
120
|
+
|
|
121
|
+
```ruby
|
|
122
|
+
pool = AuroraDsql::Pg.create_pool(
|
|
123
|
+
host: "your-cluster.dsql.us-east-1.on.aws",
|
|
124
|
+
occ_max_retries: 3 # retries up to 3 times on OCC conflict
|
|
125
|
+
)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
> **Important:** `pool.with` does NOT automatically wrap your block in a transaction. You must call `conn.transaction` yourself for write operations. On OCC conflict the entire block is re-executed, so it should contain only database operations and be safe to retry.
|
|
129
|
+
|
|
130
|
+
```ruby
|
|
131
|
+
pool.with do |conn|
|
|
132
|
+
conn.transaction do
|
|
133
|
+
conn.exec_params("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [100, from_id])
|
|
134
|
+
conn.exec_params("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [100, to_id])
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
To skip retry on individual calls, pass `retry_occ: false`:
|
|
140
|
+
|
|
141
|
+
```ruby
|
|
142
|
+
pool.with(retry_occ: false) do |conn|
|
|
143
|
+
conn.exec("SELECT 1")
|
|
144
|
+
end
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
For custom retry configuration (different backoff, etc.), use the `OCCRetry` module directly. Unlike `pool.with`, `OCCRetry.with_retry` automatically wraps the block in a transaction:
|
|
148
|
+
|
|
149
|
+
```ruby
|
|
150
|
+
AuroraDsql::Pg::OCCRetry.with_retry(pool, max_retries: 10) do |conn|
|
|
151
|
+
conn.exec_params("UPDATE ...", [...])
|
|
152
|
+
end
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
For single SQL statements (DDL or DML), `exec_with_retry` provides a simple convenience without transaction wrapping:
|
|
156
|
+
|
|
157
|
+
```ruby
|
|
158
|
+
AuroraDsql::Pg::OCCRetry.exec_with_retry(pool, "CREATE TABLE users (id UUID PRIMARY KEY)")
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
To see OCC retries in your logs, pass a `logger` when creating the pool:
|
|
162
|
+
|
|
163
|
+
```ruby
|
|
164
|
+
pool = AuroraDsql::Pg.create_pool(
|
|
165
|
+
host: "your-cluster.dsql.us-east-1.on.aws",
|
|
166
|
+
occ_max_retries: 3,
|
|
167
|
+
logger: Logger.new(STDOUT)
|
|
168
|
+
)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Examples
|
|
172
|
+
|
|
173
|
+
The `example/` directory contains runnable examples demonstrating various patterns:
|
|
174
|
+
|
|
175
|
+
| Example | Description |
|
|
176
|
+
|---------|-------------|
|
|
177
|
+
| [example_preferred](example/src/example_preferred.rb) | Recommended: Connection pool with concurrent queries |
|
|
178
|
+
| [manual_token](example/src/alternatives/manual_token/) | Manual IAM token generation without the connector |
|
|
179
|
+
|
|
180
|
+
### Running examples
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
export CLUSTER_ENDPOINT=your-cluster.dsql.us-east-1.on.aws
|
|
184
|
+
export CLUSTER_USER=admin
|
|
185
|
+
export REGION=us-east-1
|
|
186
|
+
cd example
|
|
187
|
+
|
|
188
|
+
# Run the preferred example
|
|
189
|
+
ruby src/example_preferred.rb
|
|
190
|
+
|
|
191
|
+
# Run the manual token example
|
|
192
|
+
ruby src/alternatives/manual_token/example.rb
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
cd ruby/pg
|
|
199
|
+
bundle install
|
|
200
|
+
bundle exec rake unit # Run unit tests
|
|
201
|
+
bundle exec rake integration # Run integration tests (requires CLUSTER_ENDPOINT)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## DSQL Best Practices
|
|
205
|
+
|
|
206
|
+
When using this connector with Aurora DSQL, follow these practices:
|
|
207
|
+
|
|
208
|
+
1. **UUID Primary Keys**: Always use `UUID DEFAULT gen_random_uuid()` - DSQL doesn't support sequences or SERIAL
|
|
209
|
+
2. **OCC Handling**: DSQL uses optimistic concurrency control. Enable retry via `occ_max_retries` on the pool; for single connections, use `OCCRetry` explicitly
|
|
210
|
+
3. **No Foreign Keys**: DSQL doesn't support foreign key constraints - enforce relationships in your application
|
|
211
|
+
4. **Async Indexes**: Use `CREATE INDEX ASYNC` for index creation
|
|
212
|
+
5. **Transaction Limits**: Transactions are limited to 3,000 rows, 10 MiB, and 5 minutes
|
|
213
|
+
6. **Connection Limits**: Connections timeout after 60 minutes; configure pool `max_lifetime` accordingly
|
|
214
|
+
7. **No SAVEPOINT**: Partial rollbacks via SAVEPOINT are not supported
|
|
215
|
+
|
|
216
|
+
## Additional Resources
|
|
217
|
+
|
|
218
|
+
- [Amazon Aurora DSQL Documentation](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/what-is-aurora-dsql.html)
|
|
219
|
+
- [pg gem Documentation](https://deveiate.org/code/pg/)
|
|
220
|
+
- [connection_pool Documentation](https://github.com/mperham/connection_pool)
|
|
221
|
+
- [AWS SDK for Ruby](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/)
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
226
|
+
|
|
227
|
+
SPDX-License-Identifier: Apache-2.0
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
require "uri"
|
|
5
|
+
|
|
6
|
+
module AuroraDsql
|
|
7
|
+
module Pg
|
|
8
|
+
# Configuration for Aurora DSQL connections.
|
|
9
|
+
class Config
|
|
10
|
+
DEFAULTS = {
|
|
11
|
+
user: "admin",
|
|
12
|
+
database: "postgres",
|
|
13
|
+
port: 5432,
|
|
14
|
+
max_lifetime: 55 * 60, # 55 minutes in seconds
|
|
15
|
+
token_duration: 15 * 60, # 15 minutes in seconds
|
|
16
|
+
pool_size: 5,
|
|
17
|
+
checkout_timeout: 5 # seconds to wait for a pool connection
|
|
18
|
+
}.freeze
|
|
19
|
+
|
|
20
|
+
attr_accessor :host, :region, :user, :database, :port,
|
|
21
|
+
:profile, :token_duration, :credentials_provider,
|
|
22
|
+
:max_lifetime, :pool_size, :checkout_timeout,
|
|
23
|
+
:application_name, :logger, :occ_max_retries
|
|
24
|
+
|
|
25
|
+
def initialize(**options)
|
|
26
|
+
@host = options[:host]
|
|
27
|
+
@region = options[:region]
|
|
28
|
+
@user = options[:user]
|
|
29
|
+
@database = options[:database]
|
|
30
|
+
@port = options[:port]
|
|
31
|
+
@profile = options[:profile]
|
|
32
|
+
@token_duration = options[:token_duration]
|
|
33
|
+
@credentials_provider = options[:credentials_provider]
|
|
34
|
+
@max_lifetime = options[:max_lifetime]
|
|
35
|
+
@pool_size = options[:pool_size]
|
|
36
|
+
@checkout_timeout = options[:checkout_timeout]
|
|
37
|
+
@application_name = options[:application_name]
|
|
38
|
+
@logger = options[:logger]
|
|
39
|
+
@occ_max_retries = options[:occ_max_retries]
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Parse a connection string into a Config.
|
|
43
|
+
VALID_SCHEMES = %w[postgres postgresql].freeze
|
|
44
|
+
|
|
45
|
+
def self.parse(conn_string)
|
|
46
|
+
uri = URI.parse(conn_string)
|
|
47
|
+
|
|
48
|
+
unless VALID_SCHEMES.include?(uri.scheme)
|
|
49
|
+
raise Error, "unsupported URI scheme '#{uri.scheme}', expected 'postgres' or 'postgresql'"
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
config = new(
|
|
53
|
+
host: uri.host,
|
|
54
|
+
user: uri.user,
|
|
55
|
+
database: uri.path&.delete_prefix("/"),
|
|
56
|
+
port: uri.port
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# Parse query params for DSQL-specific options
|
|
60
|
+
if uri.query
|
|
61
|
+
params = URI.decode_www_form(uri.query).to_h
|
|
62
|
+
config.region = params["region"] if params["region"]
|
|
63
|
+
config.profile = params["profile"] if params["profile"]
|
|
64
|
+
config.token_duration = params["tokenDurationSecs"].to_i if params["tokenDurationSecs"]
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
config
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Build a Config from various input types.
|
|
71
|
+
# Accepts a connection String, a Config instance, nil (keyword args only),
|
|
72
|
+
# or any object that responds to #to_h (e.g. a Hash).
|
|
73
|
+
def self.from(config = nil, **options)
|
|
74
|
+
case config
|
|
75
|
+
when String then parse(config)
|
|
76
|
+
when Config then config
|
|
77
|
+
when nil then new(**options)
|
|
78
|
+
else
|
|
79
|
+
unless config.respond_to?(:to_h)
|
|
80
|
+
raise ArgumentError,
|
|
81
|
+
"config must be a String, Config, Hash, or respond to #to_h, got #{config.class}"
|
|
82
|
+
end
|
|
83
|
+
new(**options.merge(config.to_h))
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Resolve and validate config, returning an immutable ResolvedConfig.
|
|
88
|
+
def resolve
|
|
89
|
+
validate!
|
|
90
|
+
|
|
91
|
+
resolved_host, resolved_region = resolve_host_and_region(@host, @region)
|
|
92
|
+
|
|
93
|
+
ResolvedConfig.new(
|
|
94
|
+
host: resolved_host,
|
|
95
|
+
region: resolved_region,
|
|
96
|
+
user: @user || DEFAULTS[:user],
|
|
97
|
+
database: @database || DEFAULTS[:database],
|
|
98
|
+
port: @port || DEFAULTS[:port],
|
|
99
|
+
profile: @profile,
|
|
100
|
+
token_duration: @token_duration || DEFAULTS[:token_duration],
|
|
101
|
+
credentials_provider: @credentials_provider,
|
|
102
|
+
max_lifetime: @max_lifetime || DEFAULTS[:max_lifetime],
|
|
103
|
+
pool_size: @pool_size || DEFAULTS[:pool_size],
|
|
104
|
+
checkout_timeout: @checkout_timeout || DEFAULTS[:checkout_timeout],
|
|
105
|
+
application_name: @application_name,
|
|
106
|
+
logger: @logger,
|
|
107
|
+
occ_max_retries: @occ_max_retries
|
|
108
|
+
).freeze
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
private
|
|
112
|
+
|
|
113
|
+
def resolve_host_and_region(host, region)
|
|
114
|
+
if Util.cluster_id?(host)
|
|
115
|
+
region ||= Util.region_from_env
|
|
116
|
+
raise Error, "region is required when host is a cluster ID" unless region
|
|
117
|
+
|
|
118
|
+
[Util.build_hostname(host, region), region]
|
|
119
|
+
else
|
|
120
|
+
region ||= begin
|
|
121
|
+
Util.parse_region(host)
|
|
122
|
+
rescue ArgumentError
|
|
123
|
+
nil
|
|
124
|
+
end
|
|
125
|
+
region ||= Util.region_from_env
|
|
126
|
+
raise Error, "region is required: could not parse from hostname and not set" unless region
|
|
127
|
+
|
|
128
|
+
[host, region]
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def validate!
|
|
133
|
+
raise Error, "host is required" if @host.nil? || @host.empty?
|
|
134
|
+
|
|
135
|
+
if @port
|
|
136
|
+
raise Error, "port must be an integer, got #{@port.class}" unless @port.is_a?(Integer)
|
|
137
|
+
raise Error, "port must be between 1 and 65535, got #{@port}" if @port < 1 || @port > 65_535
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
if @occ_max_retries
|
|
141
|
+
unless @occ_max_retries.is_a?(Integer) && @occ_max_retries > 0
|
|
142
|
+
raise Error, "occ_max_retries must be a positive integer, got #{@occ_max_retries.inspect}"
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# Immutable resolved configuration ready for connection.
|
|
149
|
+
ResolvedConfig = Struct.new(
|
|
150
|
+
:host, :region, :user, :database, :port,
|
|
151
|
+
:profile, :token_duration, :credentials_provider,
|
|
152
|
+
:max_lifetime, :pool_size, :checkout_timeout,
|
|
153
|
+
:application_name, :logger, :occ_max_retries,
|
|
154
|
+
keyword_init: true
|
|
155
|
+
) do
|
|
156
|
+
# Convert to pg connection parameters hash.
|
|
157
|
+
def to_pg_params(password:)
|
|
158
|
+
params = {
|
|
159
|
+
host: host,
|
|
160
|
+
port: port,
|
|
161
|
+
user: user,
|
|
162
|
+
dbname: database,
|
|
163
|
+
password: password,
|
|
164
|
+
sslmode: "verify-full",
|
|
165
|
+
application_name: AuroraDsql::Pg.build_application_name(application_name)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
# Direct SSL negotiation (libpq 17+)
|
|
169
|
+
params[:sslnegotiation] = "direct" if PG.library_version >= 170_000
|
|
170
|
+
|
|
171
|
+
params
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
end
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
require "pg"
|
|
5
|
+
|
|
6
|
+
module AuroraDsql
|
|
7
|
+
module Pg
|
|
8
|
+
# Single connection wrapper for Aurora DSQL.
|
|
9
|
+
class Connection
|
|
10
|
+
attr_reader :pg_conn, :config
|
|
11
|
+
|
|
12
|
+
# Create a new connection to Aurora DSQL.
|
|
13
|
+
def self.connect(config = nil, **options)
|
|
14
|
+
resolved = Config.from(config, **options).resolve
|
|
15
|
+
|
|
16
|
+
token = Token.generate(
|
|
17
|
+
host: resolved.host,
|
|
18
|
+
region: resolved.region,
|
|
19
|
+
user: resolved.user,
|
|
20
|
+
credentials: resolved.credentials_provider,
|
|
21
|
+
profile: resolved.profile,
|
|
22
|
+
expires_in: resolved.token_duration
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
pg_conn = ::PG.connect(resolved.to_pg_params(password: token))
|
|
26
|
+
new(pg_conn, resolved)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def initialize(pg_conn, config)
|
|
30
|
+
@pg_conn = pg_conn
|
|
31
|
+
@config = config
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Delegate common pg methods
|
|
35
|
+
|
|
36
|
+
def exec_params(...)
|
|
37
|
+
@pg_conn.exec_params(...)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def query(...)
|
|
41
|
+
@pg_conn.query(...)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def transaction(...)
|
|
45
|
+
@pg_conn.transaction(...)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def close
|
|
49
|
+
@pg_conn.close
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def finished?
|
|
53
|
+
@pg_conn.finished?
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
private
|
|
57
|
+
|
|
58
|
+
# Delegate remaining methods to PG::Connection.
|
|
59
|
+
def method_missing(method, ...)
|
|
60
|
+
if @pg_conn.respond_to?(method)
|
|
61
|
+
@pg_conn.send(method, ...)
|
|
62
|
+
else
|
|
63
|
+
super
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def respond_to_missing?(method, include_private = false)
|
|
68
|
+
@pg_conn.respond_to?(method, include_private) || super
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
require "pg"
|
|
5
|
+
|
|
6
|
+
module AuroraDsql
|
|
7
|
+
module Pg
|
|
8
|
+
# OCC (Optimistic Concurrency Control) retry utilities for Aurora DSQL.
|
|
9
|
+
module OCCRetry
|
|
10
|
+
# OCC error code for mutation conflicts.
|
|
11
|
+
ERROR_CODE_MUTATION = "OC000"
|
|
12
|
+
|
|
13
|
+
# OCC error code for schema conflicts.
|
|
14
|
+
ERROR_CODE_SCHEMA = "OC001"
|
|
15
|
+
|
|
16
|
+
# SQLSTATE for serialization failure.
|
|
17
|
+
SQLSTATE_SERIALIZATION_FAILURE = "40001"
|
|
18
|
+
|
|
19
|
+
# Default retry configuration.
|
|
20
|
+
DEFAULT_CONFIG = {
|
|
21
|
+
max_retries: 3,
|
|
22
|
+
initial_wait: 0.1, # 100ms
|
|
23
|
+
max_wait: 5.0, # 5 seconds
|
|
24
|
+
multiplier: 2.0
|
|
25
|
+
}.freeze
|
|
26
|
+
|
|
27
|
+
# Check if an error is an OCC conflict.
|
|
28
|
+
# Checks SQLSTATE first, then falls back to message matching.
|
|
29
|
+
def self.occ_error?(error)
|
|
30
|
+
return false if error.nil?
|
|
31
|
+
|
|
32
|
+
# Prefer structured SQLSTATE check when available
|
|
33
|
+
if error.respond_to?(:result) && error.result&.respond_to?(:error_field)
|
|
34
|
+
sqlstate = error.result.error_field(PG::Result::PG_DIAG_SQLSTATE)
|
|
35
|
+
return true if sqlstate == SQLSTATE_SERIALIZATION_FAILURE
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Fall back to message matching for OCC-specific codes
|
|
39
|
+
msg = error.message.to_s
|
|
40
|
+
msg.include?(ERROR_CODE_MUTATION) || msg.include?(ERROR_CODE_SCHEMA)
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Retry a block on OCC conflicts with exponential backoff and jitter.
|
|
44
|
+
# Used by both Pool#with and OCCRetry.with_retry.
|
|
45
|
+
def self.retry_on_occ(config = DEFAULT_CONFIG, logger: nil)
|
|
46
|
+
wait = config[:initial_wait]
|
|
47
|
+
last_error = nil
|
|
48
|
+
|
|
49
|
+
(0..config[:max_retries]).each do |attempt|
|
|
50
|
+
begin
|
|
51
|
+
return yield
|
|
52
|
+
rescue StandardError => e
|
|
53
|
+
raise unless occ_error?(e)
|
|
54
|
+
|
|
55
|
+
last_error = e
|
|
56
|
+
|
|
57
|
+
if attempt < config[:max_retries]
|
|
58
|
+
jittered_wait = wait + rand * wait / 4
|
|
59
|
+
logger&.warn(
|
|
60
|
+
"[AuroraDsql::Pg] OCC conflict detected, retrying " \
|
|
61
|
+
"(attempt #{attempt + 1}/#{config[:max_retries]}, wait #{jittered_wait.round(2)}s)"
|
|
62
|
+
)
|
|
63
|
+
sleep(jittered_wait)
|
|
64
|
+
wait = [wait * config[:multiplier], config[:max_wait]].min
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Re-raise inside rescue so Ruby sets .cause to the original OCC error.
|
|
70
|
+
begin
|
|
71
|
+
raise last_error
|
|
72
|
+
rescue StandardError
|
|
73
|
+
raise AuroraDsql::Pg::Error,
|
|
74
|
+
"Max retries (#{config[:max_retries]}) exceeded, last error: #{last_error&.message}"
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Execute a transactional block with automatic retry on OCC conflicts.
|
|
79
|
+
def self.with_retry(pool, config = {}, &block)
|
|
80
|
+
retry_on_occ(DEFAULT_CONFIG.merge(config)) do
|
|
81
|
+
pool.with(retry_occ: false) do |conn|
|
|
82
|
+
conn.transaction { block.call(conn) }
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Execute a single SQL statement with automatic retry on OCC conflicts.
|
|
88
|
+
# Unlike with_retry, this does NOT wrap in an explicit transaction,
|
|
89
|
+
# making it suitable for both DDL (CREATE TABLE, etc.) and single DML statements.
|
|
90
|
+
def self.exec_with_retry(pool, sql, max_retries: 3)
|
|
91
|
+
retry_on_occ(DEFAULT_CONFIG.merge(max_retries: max_retries)) do
|
|
92
|
+
pool.with(retry_occ: false) { |conn| conn.exec(sql) }
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
require "pg"
|
|
5
|
+
require "connection_pool"
|
|
6
|
+
|
|
7
|
+
module AuroraDsql
|
|
8
|
+
module Pg
|
|
9
|
+
# Connection pool for Aurora DSQL with max_lifetime enforcement.
|
|
10
|
+
class Pool
|
|
11
|
+
# Wrapper to track connection creation time for max_lifetime enforcement.
|
|
12
|
+
PooledConnection = Struct.new(:conn, :created_at, keyword_init: true)
|
|
13
|
+
|
|
14
|
+
# Create a new connection pool.
|
|
15
|
+
def self.create(config = nil, **options)
|
|
16
|
+
new(Config.from(config, **options).resolve)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def initialize(resolved_config)
|
|
20
|
+
@config = resolved_config
|
|
21
|
+
|
|
22
|
+
@pool = ConnectionPool.new(
|
|
23
|
+
size: resolved_config.pool_size,
|
|
24
|
+
timeout: resolved_config.checkout_timeout
|
|
25
|
+
) { create_connection }
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Maximum stale connection discards before giving up.
|
|
29
|
+
MAX_STALE_RETRIES = 10
|
|
30
|
+
|
|
31
|
+
# Check out a connection and yield it to the block.
|
|
32
|
+
# Enforces max_lifetime. Retries on OCC errors only when occ_max_retries
|
|
33
|
+
# is set in the pool config. Pass retry_occ: false to skip retry on
|
|
34
|
+
# individual calls.
|
|
35
|
+
def with(retry_occ: @config.occ_max_retries, &block)
|
|
36
|
+
return checkout_and_execute(&block) unless retry_occ
|
|
37
|
+
|
|
38
|
+
unless retry_occ.is_a?(Integer) && retry_occ > 0
|
|
39
|
+
raise ArgumentError,
|
|
40
|
+
"retry_occ must be false/nil or a positive integer, got #{retry_occ.inspect}. " \
|
|
41
|
+
"Configure occ_max_retries on the pool instead of passing retry_occ: true"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
occ_config = OCCRetry::DEFAULT_CONFIG.merge(max_retries: retry_occ)
|
|
45
|
+
OCCRetry.retry_on_occ(occ_config, logger: @config.logger) { checkout_and_execute(&block) }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Shutdown the pool, closing all connections.
|
|
49
|
+
def shutdown
|
|
50
|
+
@pool.shutdown { |wrapped| wrapped.conn.close rescue nil }
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
private
|
|
54
|
+
|
|
55
|
+
# Check out a connection, handling stale connection replacement.
|
|
56
|
+
# Loops because each @pool.with checkout may return a stale connection
|
|
57
|
+
# that must be discarded before retrying with a fresh one.
|
|
58
|
+
def checkout_and_execute(&block)
|
|
59
|
+
stale_retries = 0
|
|
60
|
+
|
|
61
|
+
loop do
|
|
62
|
+
@pool.with do |wrapped|
|
|
63
|
+
if stale?(wrapped)
|
|
64
|
+
stale_retries += 1
|
|
65
|
+
if stale_retries > MAX_STALE_RETRIES
|
|
66
|
+
raise AuroraDsql::Pg::Error,
|
|
67
|
+
"unable to acquire a non-stale connection after #{MAX_STALE_RETRIES} attempts"
|
|
68
|
+
end
|
|
69
|
+
@config.logger&.warn(
|
|
70
|
+
"[AuroraDsql::Pg] Discarding stale connection " \
|
|
71
|
+
"(age #{(Time.now - wrapped.created_at).round}s, max_lifetime #{@config.max_lifetime}s)"
|
|
72
|
+
)
|
|
73
|
+
@pool.discard_current_connection
|
|
74
|
+
wrapped.conn.close rescue nil
|
|
75
|
+
else
|
|
76
|
+
return block.call(wrapped.conn)
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def stale?(wrapped)
|
|
83
|
+
Time.now - wrapped.created_at > @config.max_lifetime
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def create_connection
|
|
87
|
+
token = Token.generate(
|
|
88
|
+
host: @config.host,
|
|
89
|
+
region: @config.region,
|
|
90
|
+
user: @config.user,
|
|
91
|
+
credentials: @config.credentials_provider,
|
|
92
|
+
profile: @config.profile,
|
|
93
|
+
expires_in: @config.token_duration
|
|
94
|
+
)
|
|
95
|
+
conn = ::PG.connect(@config.to_pg_params(password: token))
|
|
96
|
+
PooledConnection.new(conn: conn, created_at: Time.now)
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
require "aws-sdk-dsql"
|
|
5
|
+
|
|
6
|
+
module AuroraDsql
|
|
7
|
+
module Pg
|
|
8
|
+
# IAM token generation for Aurora DSQL.
|
|
9
|
+
class Token
|
|
10
|
+
ADMIN_USER = "admin"
|
|
11
|
+
# Generate an IAM authentication token.
|
|
12
|
+
def self.generate(host:, region:, user:, credentials: nil, profile: nil, expires_in: 15 * 60)
|
|
13
|
+
credentials ||= resolve_credentials(profile)
|
|
14
|
+
|
|
15
|
+
token_generator = Aws::DSQL::AuthTokenGenerator.new(credentials: credentials)
|
|
16
|
+
params = { endpoint: host, region: region, expires_in: expires_in }
|
|
17
|
+
|
|
18
|
+
begin
|
|
19
|
+
if user == ADMIN_USER
|
|
20
|
+
token_generator.generate_db_connect_admin_auth_token(**params)
|
|
21
|
+
else
|
|
22
|
+
token_generator.generate_db_connect_auth_token(**params)
|
|
23
|
+
end
|
|
24
|
+
rescue Aws::Errors::ServiceError => e
|
|
25
|
+
raise AuroraDsql::Pg::Error, "Failed to generate authentication token: #{e.message}"
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Resolve AWS credentials from profile or default chain.
|
|
30
|
+
def self.resolve_credentials(profile = nil)
|
|
31
|
+
if profile && !profile.empty?
|
|
32
|
+
Aws::SharedCredentials.new(profile_name: profile)
|
|
33
|
+
else
|
|
34
|
+
Aws::CredentialProviderChain.new.resolve
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
module AuroraDsql
|
|
5
|
+
module Pg
|
|
6
|
+
# Utility functions for host/region parsing.
|
|
7
|
+
module Util
|
|
8
|
+
# Pattern to extract region from DSQL hostname.
|
|
9
|
+
# Matches: cluster.dsql.us-east-1.on.aws or cluster.dsql-suffix.us-east-1.on.aws
|
|
10
|
+
REGION_PATTERN = /\.dsql[^.]*\.([^.]+)\.on\.aws\z/
|
|
11
|
+
|
|
12
|
+
# Pattern for valid DSQL cluster IDs: 26 lowercase alphanumeric characters.
|
|
13
|
+
CLUSTER_ID_PATTERN = /\A[a-z0-9]{26}\z/
|
|
14
|
+
|
|
15
|
+
# Extract AWS region from a DSQL hostname.
|
|
16
|
+
def self.parse_region(host)
|
|
17
|
+
match = host&.match(REGION_PATTERN)
|
|
18
|
+
raise ArgumentError, "Cannot parse region from hostname: #{host.inspect}" unless match
|
|
19
|
+
|
|
20
|
+
match[1]
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Check if the given string is a cluster ID (not a full hostname).
|
|
24
|
+
def self.cluster_id?(host)
|
|
25
|
+
return false if host.nil? || host.empty? || host.include?(".")
|
|
26
|
+
|
|
27
|
+
CLUSTER_ID_PATTERN.match?(host)
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Build a full DSQL hostname from cluster ID and region.
|
|
31
|
+
def self.build_hostname(cluster_id, region)
|
|
32
|
+
"#{cluster_id}.dsql.#{region}.on.aws"
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Get AWS region from environment variables.
|
|
36
|
+
def self.region_from_env
|
|
37
|
+
ENV["AWS_REGION"] || ENV["AWS_DEFAULT_REGION"]
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
module AuroraDsql
|
|
5
|
+
module Pg
|
|
6
|
+
VERSION = "1.0.0"
|
|
7
|
+
APPLICATION_NAME = "aurora-dsql-ruby-pg/#{VERSION}"
|
|
8
|
+
|
|
9
|
+
# Build application_name with optional ORM prefix.
|
|
10
|
+
def self.build_application_name(orm_prefix = nil)
|
|
11
|
+
prefix = orm_prefix.to_s.strip
|
|
12
|
+
return APPLICATION_NAME if prefix.empty?
|
|
13
|
+
|
|
14
|
+
"#{prefix}:#{APPLICATION_NAME}"
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
end
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
require_relative "aurora_dsql/pg/version"
|
|
5
|
+
require_relative "aurora_dsql/pg/util"
|
|
6
|
+
require_relative "aurora_dsql/pg/config"
|
|
7
|
+
require_relative "aurora_dsql/pg/token"
|
|
8
|
+
require_relative "aurora_dsql/pg/connection"
|
|
9
|
+
require_relative "aurora_dsql/pg/pool"
|
|
10
|
+
require_relative "aurora_dsql/pg/occ_retry"
|
|
11
|
+
|
|
12
|
+
module AuroraDsql
|
|
13
|
+
module Pg
|
|
14
|
+
class Error < StandardError; end
|
|
15
|
+
|
|
16
|
+
# Create a single connection to Aurora DSQL.
|
|
17
|
+
def self.connect(config = nil, **options)
|
|
18
|
+
Connection.connect(config, **options)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Create a connection pool for Aurora DSQL.
|
|
22
|
+
def self.create_pool(config = nil, **options)
|
|
23
|
+
Pool.create(config, **options)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: aurora-dsql-ruby-pg
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 1.0.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Amazon Web Services
|
|
8
|
+
autorequire:
|
|
9
|
+
bindir: bin
|
|
10
|
+
cert_chain: []
|
|
11
|
+
date: 2026-03-09 00:00:00.000000000 Z
|
|
12
|
+
dependencies:
|
|
13
|
+
- !ruby/object:Gem::Dependency
|
|
14
|
+
name: pg
|
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
|
16
|
+
requirements:
|
|
17
|
+
- - "~>"
|
|
18
|
+
- !ruby/object:Gem::Version
|
|
19
|
+
version: '1.5'
|
|
20
|
+
type: :runtime
|
|
21
|
+
prerelease: false
|
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
23
|
+
requirements:
|
|
24
|
+
- - "~>"
|
|
25
|
+
- !ruby/object:Gem::Version
|
|
26
|
+
version: '1.5'
|
|
27
|
+
- !ruby/object:Gem::Dependency
|
|
28
|
+
name: aws-sdk-dsql
|
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
|
30
|
+
requirements:
|
|
31
|
+
- - "~>"
|
|
32
|
+
- !ruby/object:Gem::Version
|
|
33
|
+
version: '1.6'
|
|
34
|
+
type: :runtime
|
|
35
|
+
prerelease: false
|
|
36
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
37
|
+
requirements:
|
|
38
|
+
- - "~>"
|
|
39
|
+
- !ruby/object:Gem::Version
|
|
40
|
+
version: '1.6'
|
|
41
|
+
- !ruby/object:Gem::Dependency
|
|
42
|
+
name: connection_pool
|
|
43
|
+
requirement: !ruby/object:Gem::Requirement
|
|
44
|
+
requirements:
|
|
45
|
+
- - ">="
|
|
46
|
+
- !ruby/object:Gem::Version
|
|
47
|
+
version: '2.4'
|
|
48
|
+
- - "<"
|
|
49
|
+
- !ruby/object:Gem::Version
|
|
50
|
+
version: '4.0'
|
|
51
|
+
type: :runtime
|
|
52
|
+
prerelease: false
|
|
53
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
54
|
+
requirements:
|
|
55
|
+
- - ">="
|
|
56
|
+
- !ruby/object:Gem::Version
|
|
57
|
+
version: '2.4'
|
|
58
|
+
- - "<"
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: '4.0'
|
|
61
|
+
- !ruby/object:Gem::Dependency
|
|
62
|
+
name: rspec
|
|
63
|
+
requirement: !ruby/object:Gem::Requirement
|
|
64
|
+
requirements:
|
|
65
|
+
- - "~>"
|
|
66
|
+
- !ruby/object:Gem::Version
|
|
67
|
+
version: '3.13'
|
|
68
|
+
type: :development
|
|
69
|
+
prerelease: false
|
|
70
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
71
|
+
requirements:
|
|
72
|
+
- - "~>"
|
|
73
|
+
- !ruby/object:Gem::Version
|
|
74
|
+
version: '3.13'
|
|
75
|
+
- !ruby/object:Gem::Dependency
|
|
76
|
+
name: rake
|
|
77
|
+
requirement: !ruby/object:Gem::Requirement
|
|
78
|
+
requirements:
|
|
79
|
+
- - "~>"
|
|
80
|
+
- !ruby/object:Gem::Version
|
|
81
|
+
version: '13.0'
|
|
82
|
+
type: :development
|
|
83
|
+
prerelease: false
|
|
84
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
85
|
+
requirements:
|
|
86
|
+
- - "~>"
|
|
87
|
+
- !ruby/object:Gem::Version
|
|
88
|
+
version: '13.0'
|
|
89
|
+
description: A connector that integrates IAM authentication for connecting Ruby applications
|
|
90
|
+
to Amazon Aurora DSQL clusters using the pg gem
|
|
91
|
+
email:
|
|
92
|
+
- aws-aurora-dsql-feedback@amazon.com
|
|
93
|
+
executables: []
|
|
94
|
+
extensions: []
|
|
95
|
+
extra_rdoc_files: []
|
|
96
|
+
files:
|
|
97
|
+
- LICENSE
|
|
98
|
+
- NOTICE
|
|
99
|
+
- README.md
|
|
100
|
+
- lib/aurora_dsql/pg/config.rb
|
|
101
|
+
- lib/aurora_dsql/pg/connection.rb
|
|
102
|
+
- lib/aurora_dsql/pg/occ_retry.rb
|
|
103
|
+
- lib/aurora_dsql/pg/pool.rb
|
|
104
|
+
- lib/aurora_dsql/pg/token.rb
|
|
105
|
+
- lib/aurora_dsql/pg/util.rb
|
|
106
|
+
- lib/aurora_dsql/pg/version.rb
|
|
107
|
+
- lib/aurora_dsql_pg.rb
|
|
108
|
+
homepage: https://github.com/awslabs/aurora-dsql-connectors
|
|
109
|
+
licenses:
|
|
110
|
+
- Apache-2.0
|
|
111
|
+
metadata:
|
|
112
|
+
homepage_uri: https://github.com/awslabs/aurora-dsql-connectors
|
|
113
|
+
source_code_uri: https://github.com/awslabs/aurora-dsql-connectors/tree/main/ruby/pg
|
|
114
|
+
post_install_message:
|
|
115
|
+
rdoc_options: []
|
|
116
|
+
require_paths:
|
|
117
|
+
- lib
|
|
118
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
119
|
+
requirements:
|
|
120
|
+
- - ">="
|
|
121
|
+
- !ruby/object:Gem::Version
|
|
122
|
+
version: 3.1.0
|
|
123
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
124
|
+
requirements:
|
|
125
|
+
- - ">="
|
|
126
|
+
- !ruby/object:Gem::Version
|
|
127
|
+
version: '0'
|
|
128
|
+
requirements: []
|
|
129
|
+
rubygems_version: 3.5.22
|
|
130
|
+
signing_key:
|
|
131
|
+
specification_version: 4
|
|
132
|
+
summary: Aurora DSQL connector for Ruby pg gem
|
|
133
|
+
test_files: []
|