@aws-blocks/bb-distributed-data 0.1.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.
Files changed (57) hide show
  1. package/LICENSE +174 -0
  2. package/README.md +243 -0
  3. package/dist/constants.d.ts +38 -0
  4. package/dist/constants.d.ts.map +1 -0
  5. package/dist/constants.js +50 -0
  6. package/dist/e2e-mock.test.d.ts +2 -0
  7. package/dist/e2e-mock.test.d.ts.map +1 -0
  8. package/dist/e2e-mock.test.js +185 -0
  9. package/dist/e2e.test.d.ts +2 -0
  10. package/dist/e2e.test.d.ts.map +1 -0
  11. package/dist/e2e.test.js +329 -0
  12. package/dist/engines/dsql-engine.d.ts +26 -0
  13. package/dist/engines/dsql-engine.d.ts.map +1 -0
  14. package/dist/engines/dsql-engine.js +103 -0
  15. package/dist/engines/dsql-mock-engine.d.ts +28 -0
  16. package/dist/engines/dsql-mock-engine.d.ts.map +1 -0
  17. package/dist/engines/dsql-mock-engine.js +132 -0
  18. package/dist/errors.d.ts +29 -0
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/errors.js +45 -0
  21. package/dist/errors.test.d.ts +2 -0
  22. package/dist/errors.test.d.ts.map +1 -0
  23. package/dist/errors.test.js +55 -0
  24. package/dist/index.aws.d.ts +35 -0
  25. package/dist/index.aws.d.ts.map +1 -0
  26. package/dist/index.aws.js +59 -0
  27. package/dist/index.browser.d.ts +5 -0
  28. package/dist/index.browser.d.ts.map +1 -0
  29. package/dist/index.browser.js +7 -0
  30. package/dist/index.cdk.d.ts +16 -0
  31. package/dist/index.cdk.d.ts.map +1 -0
  32. package/dist/index.cdk.js +103 -0
  33. package/dist/index.cdk.test.d.ts +2 -0
  34. package/dist/index.cdk.test.d.ts.map +1 -0
  35. package/dist/index.cdk.test.js +182 -0
  36. package/dist/index.mock.d.ts +39 -0
  37. package/dist/index.mock.d.ts.map +1 -0
  38. package/dist/index.mock.js +53 -0
  39. package/dist/migration-lambda.d.ts +5 -0
  40. package/dist/migration-lambda.d.ts.map +1 -0
  41. package/dist/migration-lambda.js +139 -0
  42. package/dist/migrations.d.ts +11 -0
  43. package/dist/migrations.d.ts.map +1 -0
  44. package/dist/migrations.js +59 -0
  45. package/dist/transaction.d.ts +12 -0
  46. package/dist/transaction.d.ts.map +1 -0
  47. package/dist/transaction.js +24 -0
  48. package/dist/types.d.ts +32 -0
  49. package/dist/types.d.ts.map +1 -0
  50. package/dist/types.js +3 -0
  51. package/dist/validation.d.ts +18 -0
  52. package/dist/validation.d.ts.map +1 -0
  53. package/dist/validation.js +169 -0
  54. package/dist/validation.test.d.ts +2 -0
  55. package/dist/validation.test.d.ts.map +1 -0
  56. package/dist/validation.test.js +354 -0
  57. package/package.json +48 -0
package/LICENSE ADDED
@@ -0,0 +1,174 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
package/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # @aws-blocks/bb-distributed-data
2
+
3
+ Serverless SQL database backed by Amazon Aurora DSQL. Zero-ops, instant provisioning, scale-to-zero, and optionally multi-region active-active writes.
4
+
5
+ **When to use:** Serverless apps that need to scale without ops overhead, workloads with zero idle cost requirements, multi-region active-active writes, or any SQL app where you don't need FK/RLS/triggers.
6
+
7
+ **When NOT to use:** If you need foreign keys, Row Level Security, triggers, views, or stored procedures — use `Database` (Aurora). If you need transactions that must not fail at commit under contention — use `Database`. If you're connecting to Supabase — use `Database` with `fromExisting()`.
8
+
9
+ ## Quick Start
10
+
11
+ ```typescript
12
+ import { DistributedDatabase, sql } from '@aws-blocks/bb-distributed-data';
13
+
14
+ const db = new DistributedDatabase(scope, 'main', {
15
+ migrationsPath: './aws-blocks/dsql-migrations',
16
+ });
17
+
18
+ // Same query API as Database — parameterized via sql tagged template
19
+ const users = await db.query<{ id: string; name: string }>(
20
+ sql`SELECT * FROM users WHERE active = ${true}`
21
+ );
22
+
23
+ const user = await db.queryOne<{ id: string; name: string }>(
24
+ sql`SELECT * FROM users WHERE id = ${userId}`
25
+ );
26
+
27
+ const { rowCount } = await db.execute(
28
+ sql`INSERT INTO users (id, name, email) VALUES (${id}, ${name}, ${email})`
29
+ );
30
+ ```
31
+
32
+ ## Transactions (Optimistic Concurrency Control)
33
+
34
+ DSQL uses OCC — transactions may fail at commit if another transaction modified the same rows. The callback executes exactly once unless you opt into retry.
35
+
36
+ ```typescript
37
+ // Default: no retry. Throws SerializationFailureException on conflict.
38
+ await db.transaction(async (tx) => {
39
+ await tx.execute(sql`UPDATE accounts SET balance = balance - ${100} WHERE id = ${fromId}`);
40
+ await tx.execute(sql`UPDATE accounts SET balance = balance + ${100} WHERE id = ${toId}`);
41
+ });
42
+
43
+ // Opt-in retry: callback may execute multiple times.
44
+ // ⚠️ Do NOT include external side effects (HTTP calls, emails) inside.
45
+ await db.transaction(async (tx) => {
46
+ await tx.execute(sql`UPDATE accounts SET balance = balance - ${100} WHERE id = ${fromId}`);
47
+ await tx.execute(sql`UPDATE accounts SET balance = balance + ${100} WHERE id = ${toId}`);
48
+ }, { retryOnConflict: true, maxRetries: 3 });
49
+ ```
50
+
51
+ The second argument to `transaction()` accepts:
52
+
53
+ ```typescript
54
+ interface TransactionOptions {
55
+ /** Retry on OCC conflict. Callback may execute multiple times. @default false */
56
+ retryOnConflict?: boolean;
57
+ /** Max retry attempts. Only applies when retryOnConflict is true. @default 3 */
58
+ maxRetries?: number;
59
+ }
60
+ ```
61
+
62
+ ## Migrations
63
+
64
+ One DDL statement per file. DML in separate files. This matches DSQL's transaction constraints.
65
+
66
+ ```
67
+ aws-blocks/dsql-migrations/
68
+ 001_create_users.sql ← single DDL
69
+ 002_create_posts.sql ← single DDL
70
+ 003_create_index.sql ← single DDL (CREATE INDEX ASYNC)
71
+ 004_seed_admin.sql ← DML only
72
+ ```
73
+
74
+ ```sql
75
+ -- 001_create_users.sql
76
+ CREATE TABLE users (
77
+ id TEXT PRIMARY KEY DEFAULT gen_random_uuid(),
78
+ email TEXT UNIQUE NOT NULL,
79
+ name TEXT NOT NULL,
80
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
81
+ );
82
+ ```
83
+
84
+ ```sql
85
+ -- 003_create_index.sql
86
+ CREATE INDEX ASYNC idx_users_email ON users(email);
87
+ ```
88
+
89
+ Migrations are validated at dev time — unsupported features (FK, SERIAL, TRUNCATE, etc.) are caught before deploy.
90
+
91
+ ## DSQL Limitations
92
+
93
+ DSQL is a subset of PostgreSQL. The local mock enforces these restrictions so code that works locally also works in production.
94
+
95
+ | Not Supported | Alternative |
96
+ |---------------|-------------|
97
+ | Foreign keys (`REFERENCES`) | Application-layer validation |
98
+ | JSONB columns | `JSON` type (JSONB available as `::jsonb` runtime cast) |
99
+ | Row Level Security | WHERE clause filtering in app code |
100
+ | Triggers | Event-driven logic (EventBridge, Lambda) |
101
+ | Views | CTEs or application-layer query composition |
102
+ | PL/pgSQL functions | `LANGUAGE SQL` functions or app logic |
103
+ | SERIAL / BIGSERIAL | UUIDs (`gen_random_uuid()`) |
104
+ | TRUNCATE | `DELETE FROM` |
105
+ | Temporary tables | CTEs or subqueries |
106
+ | LISTEN / NOTIFY | AppSync Events, EventBridge, or polling |
107
+ | Extensions | Not available |
108
+ | ADD COLUMN with DEFAULT | Add column without default, handle nulls in app |
109
+
110
+ ### Transaction Constraints
111
+
112
+ | Constraint | Limit |
113
+ |-----------|-------|
114
+ | Concurrency model | OCC (may conflict at commit) |
115
+ | Isolation level | Fixed: Repeatable Read |
116
+ | Max rows mutated per transaction | 3,000 |
117
+ | Max data per transaction | 10 MiB |
118
+ | Max transaction duration | 5 minutes |
119
+ | DDL per transaction | 1 statement max |
120
+ | DDL + DML mixing | Not allowed |
121
+
122
+ ## Kysely Query Builder
123
+
124
+ ```typescript
125
+ import { createKyselyAdapter } from '@aws-blocks/bb-distributed-data';
126
+
127
+ interface Schema {
128
+ users: { id: string; email: string; name: string };
129
+ }
130
+
131
+ const kysely = createKyselyAdapter<Schema>(db);
132
+
133
+ const users = await kysely
134
+ .selectFrom('users')
135
+ .where('email', '=', 'user@example.com')
136
+ .selectAll()
137
+ .execute();
138
+ ```
139
+
140
+ Do not use Kysely's `.addForeignKeyConstraint()` — it will fail on DSQL.
141
+
142
+ ## Error Handling
143
+
144
+ ```typescript
145
+ import { DistributedDatabaseErrors } from '@aws-blocks/bb-distributed-data';
146
+ import { isBlocksError } from '@aws-blocks/core';
147
+
148
+ try {
149
+ await db.transaction(async (tx) => { /* ... */ });
150
+ } catch (e: unknown) {
151
+ if (isBlocksError(e, DistributedDatabaseErrors.SerializationFailure)) {
152
+ // OCC conflict — transaction was NOT committed. Safe to retry.
153
+ }
154
+ if (isBlocksError(e, DistributedDatabaseErrors.UniqueConstraintViolation)) {
155
+ // Duplicate key
156
+ }
157
+ if (isBlocksError(e, DistributedDatabaseErrors.QueryFailed)) {
158
+ // General query failure
159
+ }
160
+ if (isBlocksError(e, DistributedDatabaseErrors.TransactionRowLimitExceeded)) {
161
+ // More than 3,000 rows mutated in one transaction
162
+ }
163
+ if (isBlocksError(e, DistributedDatabaseErrors.ConnectionFailed)) {
164
+ // Cannot reach the DSQL cluster
165
+ }
166
+ }
167
+ ```
168
+
169
+ ## Testing OCC Conflicts
170
+
171
+ The mock provides a `simulateConflict()` helper for unit testing:
172
+
173
+ ```typescript
174
+ db.simulateConflict(); // next commit will fail with SerializationFailureException
175
+
176
+ await expect(db.transaction(fn)).rejects.toThrow('SerializationFailureException');
177
+ ```
178
+
179
+ ```typescript
180
+ db.simulateConflict(); // first attempt fails, second succeeds
181
+ const result = await db.transaction(fn, { retryOnConflict: true });
182
+ ```
183
+
184
+ ## What It Provisions (AWS)
185
+
186
+ - **Aurora DSQL Cluster** — Serverless, no VPC required, public endpoint
187
+ - **Migration Lambda** — Runs `.sql` files on deploy via CustomResource with retry
188
+ - **IAM** — `dsql:DbConnect` (app Lambda, DML only), `dsql:DbConnectAdmin` (migration Lambda, DDL)
189
+ - **Environment variables** — `BLOCKS_{name}_ENDPOINT`, `BLOCKS_{name}_REGION`
190
+
191
+ No VPC, no secrets, no security groups, no proxy. DSQL uses IAM token authentication.
192
+
193
+ ## Local Development
194
+
195
+ - **Engine:** PGlite (WASM PostgreSQL) wrapped with a DSQL validation layer
196
+ - **Storage:** `.bb-data/{fullId}/` — persists across restarts
197
+ - **Validation:** Unsupported features (FK, triggers, SERIAL, etc.) are rejected at query time
198
+ - **Transaction tracking:** DDL/DML mixing and 3,000-row limit enforced locally
199
+
200
+ The validation layer ensures code that works locally also works against a real DSQL cluster.
201
+
202
+ ## Configuration
203
+
204
+ ```typescript
205
+ interface DistributedDatabaseOptions {
206
+ /** Path to directory containing numbered .sql migration files. */
207
+ migrationsPath?: string;
208
+ /** Removal policy. @default 'retain' */
209
+ removalPolicy?: 'destroy' | 'retain';
210
+ }
211
+ ```
212
+
213
+ ## Package Export Conditions
214
+
215
+ ```json
216
+ {
217
+ "exports": {
218
+ ".": {
219
+ "cdk": "./dist/index.cdk.js",
220
+ "aws-runtime": "./dist/index.aws.js",
221
+ "default": "./dist/index.mock.js"
222
+ }
223
+ }
224
+ }
225
+ ```
226
+
227
+ ## Differences from Database (Aurora)
228
+
229
+ | Aspect | `Database` (bb-data) | `DistributedDatabase` (bb-distributed-data) |
230
+ |--------|---------------------|--------------------------|
231
+ | Engine | Aurora Serverless v2 (Data API) | Aurora DSQL (pg + IAM) |
232
+ | PostgreSQL compat | Full | Subset (no FK, RLS, triggers) |
233
+ | Transactions | Pessimistic (exactly-once) | OCC (may conflict at commit) |
234
+ | `withRLS()` | ✅ | ❌ |
235
+ | `fromExisting()` | ✅ | ❌ |
236
+ | `crud()` | ✅ | ❌ |
237
+ | Foreign keys | ✅ | ❌ |
238
+ | Multi-region | ❌ | ✅ Active-active |
239
+ | VPC required | Yes | No |
240
+ | Deploy time | ~10 min | Seconds |
241
+ | Idle cost | $0 (0 ACU) | $0 |
242
+
243
+
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Shared constants for the bb-distributed-data package.
3
+ */
4
+ /**
5
+ * Path where migration .sql files are bundled inside the Lambda deployment package.
6
+ * Used by both the CDK construct (to set the env var + copy files) and the
7
+ * migration Lambda handler (to read files at runtime).
8
+ */
9
+ export declare const LAMBDA_MIGRATIONS_DIR = "/var/task/migrations";
10
+ /**
11
+ * Migration Lambda timeout. Set to 5 minutes to allow for large migration sets
12
+ * and DSQL cluster warm-up time on first connection after creation.
13
+ */
14
+ export declare const MIGRATION_LAMBDA_TIMEOUT_MINUTES = 5;
15
+ /**
16
+ * Default connection pool size for DSQL. Kept small because Lambda concurrency
17
+ * means each instance handles few concurrent requests, and DSQL connections
18
+ * are lightweight (no VPC, no proxy needed).
19
+ */
20
+ export declare const DEFAULT_POOL_SIZE = 5;
21
+ /**
22
+ * Default max retry attempts for OCC conflicts when retryOnConflict is enabled.
23
+ */
24
+ export declare const DEFAULT_MAX_RETRIES = 3;
25
+ export declare const ENV_SANITIZE: RegExp;
26
+ /**
27
+ * Prefix for the custom database role created for the app Lambda.
28
+ * The full role name is `blocks_app_{sanitized_id}`.
29
+ * PostgreSQL role names are case-insensitive and limited to 63 chars (NAMEDATALEN - 1).
30
+ */
31
+ export declare const DB_ROLE_PREFIX = "blocks_app_";
32
+ /**
33
+ * Sanitize a block ID into a valid PostgreSQL role name.
34
+ * Short IDs stay human-readable. If the name would exceed 63 chars,
35
+ * a sha256 hash of the original ID is used to guarantee uniqueness.
36
+ */
37
+ export declare const sanitizeDbRoleName: (id: string) => string;
38
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAKA;;GAEG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,yBAAyB,CAAC;AAE5D;;;GAGG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC;;GAEG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAGrC,eAAO,MAAM,YAAY,QAAkB,CAAC;AAE5C;;;;GAIG;AACH,eAAO,MAAM,cAAc,gBAAgB,CAAC;AAK5C;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,GAAI,IAAI,MAAM,KAAG,MAM/C,CAAC"}
@@ -0,0 +1,50 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { createHash } from 'node:crypto';
4
+ /**
5
+ * Shared constants for the bb-distributed-data package.
6
+ */
7
+ /**
8
+ * Path where migration .sql files are bundled inside the Lambda deployment package.
9
+ * Used by both the CDK construct (to set the env var + copy files) and the
10
+ * migration Lambda handler (to read files at runtime).
11
+ */
12
+ export const LAMBDA_MIGRATIONS_DIR = '/var/task/migrations';
13
+ /**
14
+ * Migration Lambda timeout. Set to 5 minutes to allow for large migration sets
15
+ * and DSQL cluster warm-up time on first connection after creation.
16
+ */
17
+ export const MIGRATION_LAMBDA_TIMEOUT_MINUTES = 5;
18
+ /**
19
+ * Default connection pool size for DSQL. Kept small because Lambda concurrency
20
+ * means each instance handles few concurrent requests, and DSQL connections
21
+ * are lightweight (no VPC, no proxy needed).
22
+ */
23
+ export const DEFAULT_POOL_SIZE = 5;
24
+ /**
25
+ * Default max retry attempts for OCC conflicts when retryOnConflict is enabled.
26
+ */
27
+ export const DEFAULT_MAX_RETRIES = 3;
28
+ // Env var names must be [A-Z0-9_]. The fullId may contain hyphens/dots (e.g., "my-app.dsql").
29
+ export const ENV_SANITIZE = /[^a-zA-Z0-9]/g;
30
+ /**
31
+ * Prefix for the custom database role created for the app Lambda.
32
+ * The full role name is `blocks_app_{sanitized_id}`.
33
+ * PostgreSQL role names are case-insensitive and limited to 63 chars (NAMEDATALEN - 1).
34
+ */
35
+ export const DB_ROLE_PREFIX = 'blocks_app_';
36
+ /** Max PostgreSQL identifier length. */
37
+ const PG_NAME_MAX = 63;
38
+ /**
39
+ * Sanitize a block ID into a valid PostgreSQL role name.
40
+ * Short IDs stay human-readable. If the name would exceed 63 chars,
41
+ * a sha256 hash of the original ID is used to guarantee uniqueness.
42
+ */
43
+ export const sanitizeDbRoleName = (id) => {
44
+ const sanitized = `${DB_ROLE_PREFIX}${id.replace(/[^a-z0-9]/gi, '_').toLowerCase()}`;
45
+ if (sanitized.length <= PG_NAME_MAX)
46
+ return sanitized;
47
+ // Long ID — use a hash to avoid collisions from naive truncation
48
+ const hash = createHash('sha256').update(id).digest('hex').slice(0, 12);
49
+ return `${DB_ROLE_PREFIX}${hash}`;
50
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=e2e-mock.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"e2e-mock.test.d.ts","sourceRoot":"","sources":["../src/e2e-mock.test.ts"],"names":[],"mappings":""}