@guren/plugin-lambda 0.5.0 → 0.6.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.
@@ -1,6 +1,7 @@
1
1
  import { Duration } from "aws-cdk-lib";
2
2
  import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
3
3
  import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
4
+ import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
4
5
  import * as lambda from "aws-cdk-lib/aws-lambda";
5
6
  import * as s3 from "aws-cdk-lib/aws-s3";
6
7
  import * as sqs from "aws-cdk-lib/aws-sqs";
@@ -22,6 +23,12 @@ interface GurenLambdaAssetsProps {
22
23
  /** The staged assets directory produced by `guren lambda:build` (`.lambda/assets`). */
23
24
  dir: string;
24
25
  }
26
+ interface GurenLambdaSessionsTableProps {
27
+ /** Explicit table name. Omitted, CloudFormation names it. */
28
+ tableName?: string;
29
+ /** Kept on `cdk destroy`. Defaults to true: a destroyed table logs everyone out. */
30
+ retainOnDelete?: boolean;
31
+ }
25
32
  interface GurenLambdaDataApiProps {
26
33
  /** Aurora cluster ARN — exposed as DATABASE_RESOURCE_ARN. */
27
34
  resourceArn: string;
@@ -51,6 +58,8 @@ interface GurenLambdaAppProps {
51
58
  assets?: GurenLambdaAssetsProps;
52
59
  /** Wire every function to Aurora via the RDS Data API: environment plus the rds-data and secret-read grants. */
53
60
  dataApi?: GurenLambdaDataApiProps;
61
+ /** Provision the table the `dynamodb` session driver reads (RFC 0020 §4). */
62
+ sessionsTable?: GurenLambdaSessionsTableProps | true;
54
63
  }
55
64
  /**
56
65
  * The full serverless topology in one construct: an HTTP API in front of the
@@ -67,9 +76,10 @@ declare class GurenLambdaApp extends Construct {
67
76
  readonly queueFunction?: lambda.Function;
68
77
  readonly scheduleFunction?: lambda.Function;
69
78
  readonly consoleFunction?: lambda.Function;
79
+ readonly sessionsTable?: dynamodb.Table;
70
80
  readonly assetsBucket?: s3.Bucket;
71
81
  readonly distribution?: cloudfront.Distribution;
72
82
  constructor(scope: Construct, id: string, props: GurenLambdaAppProps);
73
83
  }
74
84
  //#endregion
75
- export { GurenLambdaApp, GurenLambdaAppProps, GurenLambdaAssetsProps, GurenLambdaDataApiProps, GurenLambdaQueueProps, GurenLambdaScheduleProps };
85
+ export { GurenLambdaApp, GurenLambdaAppProps, GurenLambdaAssetsProps, GurenLambdaDataApiProps, GurenLambdaQueueProps, GurenLambdaScheduleProps, GurenLambdaSessionsTableProps };
package/dist/cdk/index.js CHANGED
@@ -2,11 +2,12 @@ import { r as lambdaHandlerId } from "../handlers-Dtt3k5Ue.js";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS } from "@guren/core/internal/deploy-build";
5
- import { CfnOutput, Duration } from "aws-cdk-lib";
5
+ import { CfnOutput, Duration, RemovalPolicy } from "aws-cdk-lib";
6
6
  import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
7
7
  import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
8
8
  import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
9
9
  import * as origins from "aws-cdk-lib/aws-cloudfront-origins";
10
+ import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
10
11
  import * as events from "aws-cdk-lib/aws-events";
11
12
  import * as targets from "aws-cdk-lib/aws-events-targets";
12
13
  import * as iam from "aws-cdk-lib/aws-iam";
@@ -32,6 +33,7 @@ var GurenLambdaApp = class extends Construct {
32
33
  queueFunction;
33
34
  scheduleFunction;
34
35
  consoleFunction;
36
+ sessionsTable;
35
37
  assetsBucket;
36
38
  distribution;
37
39
  constructor(scope, id, props) {
@@ -99,6 +101,23 @@ var GurenLambdaApp = class extends Construct {
99
101
  fn.addEnvironment("SQS_QUEUE_URL", this.queue.queueUrl);
100
102
  this.queue.grantSendMessages(fn);
101
103
  }
104
+ if (props.sessionsTable) {
105
+ const sessionsProps = props.sessionsTable === true ? {} : props.sessionsTable;
106
+ this.sessionsTable = new dynamodb.Table(this, "SessionsTable", {
107
+ tableName: sessionsProps.tableName,
108
+ partitionKey: {
109
+ name: "id",
110
+ type: dynamodb.AttributeType.STRING
111
+ },
112
+ timeToLiveAttribute: "expires_at",
113
+ billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
114
+ removalPolicy: sessionsProps.retainOnDelete === false ? RemovalPolicy.DESTROY : RemovalPolicy.RETAIN
115
+ });
116
+ for (const fn of functions) {
117
+ fn.addEnvironment("DYNAMODB_SESSIONS_TABLE", this.sessionsTable.tableName);
118
+ this.sessionsTable.grantReadWriteData(fn);
119
+ }
120
+ }
102
121
  if (props.dataApi) for (const fn of functions) {
103
122
  fn.addToRolePolicy(new iam.PolicyStatement({
104
123
  actions: [
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ServiceProviderConstructor } from "@guren/core";
2
2
  import { DatabaseDialect, PathLike } from "@guren/core/internal/deploy-build";
3
+ import { SessionData, SessionManager, SessionStore } from "@guren/server";
3
4
  //#region src/build.d.ts
4
5
  interface BuildLambdaOutputOptions {
5
6
  /** App root directory. Defaults to the current working directory. */
@@ -50,6 +51,64 @@ type LambdaHandlerExport = (typeof LAMBDA_HANDLER_EXPORTS)[number];
50
51
  /** Lambda handler identifier for an export. */
51
52
  declare function lambdaHandlerId(name: LambdaHandlerExport): string;
52
53
  //#endregion
54
+ //#region src/session/dynamodb-store.d.ts
55
+ /**
56
+ * Sessions in DynamoDB, for Lambda apps that want session churn off the
57
+ * primary database (RFC 0020 §4). Items are `{ id, data, expires_at }`; the
58
+ * table's TTL attribute is `expires_at`, in epoch seconds.
59
+ * `@aws-sdk/client-dynamodb` is an optional peer, imported on first use.
60
+ */
61
+ interface DynamoDbClient {
62
+ send(command: unknown): Promise<unknown>;
63
+ }
64
+ interface DynamoDbSessionStoreOptions {
65
+ /** Table name. `guren lambda:build` apps read it from DYNAMODB_SESSIONS_TABLE. */
66
+ table: string;
67
+ /** Defaults to AWS_REGION, which Lambda always sets. */
68
+ region?: string;
69
+ /** For DynamoDB Local, or a VPC endpoint. */
70
+ endpoint?: string;
71
+ /** A pre-built client. Skips both the lazy import and the credential chain. */
72
+ client?: DynamoDbClient;
73
+ now?: () => number;
74
+ }
75
+ declare class DynamoDbSessionStore implements SessionStore {
76
+ private client;
77
+ private readonly table;
78
+ private readonly region?;
79
+ private readonly endpoint?;
80
+ private readonly now;
81
+ constructor(options: DynamoDbSessionStoreOptions);
82
+ private nowSeconds;
83
+ private getClient;
84
+ read(id: string): Promise<SessionData | undefined>;
85
+ write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
86
+ destroy(id: string): Promise<void>;
87
+ touch(id: string, ttlSeconds: number): Promise<void>;
88
+ }
89
+ //#endregion
90
+ //#region src/session/index.d.ts
91
+ /**
92
+ * The `dynamodb` driver's config. `table` defaults to DYNAMODB_SESSIONS_TABLE,
93
+ * which the CDK construct's `sessionsTable` sets on every function.
94
+ */
95
+ interface DynamoDbSessionDriverOptions extends Omit<DynamoDbSessionStoreOptions, 'table'> {
96
+ table?: string;
97
+ }
98
+ declare module '@guren/server' {
99
+ interface SessionDrivers {
100
+ dynamodb: DynamoDbSessionDriverOptions;
101
+ }
102
+ }
103
+ /**
104
+ * Adds the `dynamodb` driver to a manager. A function call, never a module
105
+ * side effect: a bundler that drops an unused import would otherwise drop the
106
+ * driver with it (RFC 0020 §4, same rule as core's `database`).
107
+ *
108
+ * @example registerDynamoDbSessionDriver(createSessionManager(sessionConfig))
109
+ */
110
+ declare function registerDynamoDbSessionDriver(manager: SessionManager): void;
111
+ //#endregion
53
112
  //#region src/index.d.ts
54
113
  /**
55
114
  * Configuration for the Lambda plugin. Currently empty — reserved so future
@@ -63,4 +122,4 @@ interface LambdaPluginConfig {}
63
122
  */
64
123
  declare function lambdaPlugin(config?: LambdaPluginConfig): ServiceProviderConstructor;
65
124
  //#endregion
66
- export { type BuildLambdaOutputOptions, LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, type LambdaHandlerExport, LambdaPluginConfig, buildLambdaOutput, lambdaHandlerId, lambdaPlugin };
125
+ export { type BuildLambdaOutputOptions, type DynamoDbSessionDriverOptions, DynamoDbSessionStore, type DynamoDbSessionStoreOptions, LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, type LambdaHandlerExport, LambdaPluginConfig, buildLambdaOutput, lambdaHandlerId, lambdaPlugin, registerDynamoDbSessionDriver };
package/dist/index.js CHANGED
@@ -1,6 +1,131 @@
1
1
  import { n as LAMBDA_HANDLER_MODULE, r as lambdaHandlerId, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-Dtt3k5Ue.js";
2
2
  import { t as buildLambdaOutput } from "./build-Dn_V0LNZ.js";
3
3
  import { definePlugin } from "@guren/core";
4
+ //#region src/session/dynamodb-store.ts
5
+ var DynamoDbSessionStore = class {
6
+ client;
7
+ table;
8
+ region;
9
+ endpoint;
10
+ now;
11
+ constructor(options) {
12
+ this.client = options.client ?? null;
13
+ this.table = options.table;
14
+ this.region = options.region;
15
+ this.endpoint = options.endpoint;
16
+ this.now = options.now ?? (() => Date.now());
17
+ }
18
+ nowSeconds() {
19
+ return Math.floor(this.now() / 1e3);
20
+ }
21
+ async getClient() {
22
+ if (this.client) return this.client;
23
+ const { DynamoDBClient } = await importDynamoDb();
24
+ const config = {};
25
+ if (this.region) config.region = this.region;
26
+ if (this.endpoint) config.endpoint = this.endpoint;
27
+ this.client = new DynamoDBClient(config);
28
+ return this.client;
29
+ }
30
+ async read(id) {
31
+ const { GetItemCommand } = await importDynamoDb();
32
+ const item = (await (await this.getClient()).send(new GetItemCommand({
33
+ TableName: this.table,
34
+ Key: { id: { S: id } },
35
+ ConsistentRead: true
36
+ }))).Item;
37
+ if (!item) return;
38
+ const expiresAt = Number(item.expires_at?.N ?? "0");
39
+ if (!Number.isFinite(expiresAt) || expiresAt <= this.nowSeconds()) return;
40
+ return parseSessionData(item.data?.S);
41
+ }
42
+ async write(id, data, ttlSeconds) {
43
+ const { PutItemCommand } = await importDynamoDb();
44
+ await (await this.getClient()).send(new PutItemCommand({
45
+ TableName: this.table,
46
+ Item: {
47
+ id: { S: id },
48
+ data: { S: JSON.stringify(data) },
49
+ expires_at: { N: String(this.nowSeconds() + ttlSeconds) }
50
+ }
51
+ }));
52
+ }
53
+ async destroy(id) {
54
+ const { DeleteItemCommand } = await importDynamoDb();
55
+ await (await this.getClient()).send(new DeleteItemCommand({
56
+ TableName: this.table,
57
+ Key: { id: { S: id } }
58
+ }));
59
+ }
60
+ async touch(id, ttlSeconds) {
61
+ const { UpdateItemCommand } = await importDynamoDb();
62
+ const client = await this.getClient();
63
+ const now = this.nowSeconds();
64
+ try {
65
+ await client.send(new UpdateItemCommand({
66
+ TableName: this.table,
67
+ Key: { id: { S: id } },
68
+ UpdateExpression: "SET expires_at = :expires",
69
+ ConditionExpression: "attribute_exists(id) AND expires_at > :now",
70
+ ExpressionAttributeValues: {
71
+ ":expires": { N: String(now + ttlSeconds) },
72
+ ":now": { N: String(now) }
73
+ }
74
+ }));
75
+ } catch (error) {
76
+ if (!isConditionalCheckFailed(error)) throw error;
77
+ }
78
+ }
79
+ };
80
+ function parseSessionData(raw) {
81
+ if (raw === void 0) return void 0;
82
+ try {
83
+ const parsed = JSON.parse(raw);
84
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
85
+ return parsed;
86
+ } catch {
87
+ return;
88
+ }
89
+ }
90
+ function isConditionalCheckFailed(error) {
91
+ if (!error || typeof error !== "object") return false;
92
+ return error.name === "ConditionalCheckFailedException";
93
+ }
94
+ function isMissingModule(error, moduleName) {
95
+ if (!error || typeof error !== "object") return false;
96
+ if (error.code === "ERR_MODULE_NOT_FOUND") return true;
97
+ const message = String(error.message ?? "");
98
+ return message.includes(`Cannot find package '${moduleName}'`) || message.includes(`Cannot find module '${moduleName}'`);
99
+ }
100
+ async function importDynamoDb() {
101
+ const moduleName = "@aws-sdk/client-dynamodb";
102
+ try {
103
+ return await import(moduleName);
104
+ } catch (error) {
105
+ if (isMissingModule(error, moduleName)) throw new Error(`Missing optional dependency "${moduleName}". Install it to use the dynamodb session driver.`);
106
+ throw error;
107
+ }
108
+ }
109
+ //#endregion
110
+ //#region src/session/index.ts
111
+ /**
112
+ * Adds the `dynamodb` driver to a manager. A function call, never a module
113
+ * side effect: a bundler that drops an unused import would otherwise drop the
114
+ * driver with it (RFC 0020 §4, same rule as core's `database`).
115
+ *
116
+ * @example registerDynamoDbSessionDriver(createSessionManager(sessionConfig))
117
+ */
118
+ function registerDynamoDbSessionDriver(manager) {
119
+ manager.registerDriver("dynamodb", ({ table, ...options }) => {
120
+ const name = table ?? process.env.DYNAMODB_SESSIONS_TABLE;
121
+ if (!name) throw new Error("The dynamodb session driver needs a table: set DYNAMODB_SESSIONS_TABLE, or pass `table` in config/session.ts.");
122
+ return new DynamoDbSessionStore({
123
+ ...options,
124
+ table: name
125
+ });
126
+ });
127
+ }
128
+ //#endregion
4
129
  //#region src/index.ts
5
130
  const factory = definePlugin({
6
131
  name: "lambda",
@@ -15,4 +140,4 @@ function lambdaPlugin(config = {}) {
15
140
  return factory(config);
16
141
  }
17
142
  //#endregion
18
- export { LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, buildLambdaOutput, lambdaHandlerId, lambdaPlugin };
143
+ export { DynamoDbSessionStore, LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, buildLambdaOutput, lambdaHandlerId, lambdaPlugin, registerDynamoDbSessionDriver };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-lambda",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -22,6 +22,14 @@
22
22
  "names": [
23
23
  "lambda:build"
24
24
  ]
25
+ },
26
+ "drivers": {
27
+ "session": [
28
+ {
29
+ "name": "dynamodb",
30
+ "persistent": true
31
+ }
32
+ ]
25
33
  }
26
34
  },
27
35
  "files": [
@@ -45,14 +53,22 @@
45
53
  "typecheck": "tsc --noEmit"
46
54
  },
47
55
  "dependencies": {
48
- "@guren/core": "^1.15.0",
56
+ "@guren/core": "^1.16.0",
49
57
  "citty": "^0.1.6"
50
58
  },
51
59
  "peerDependencies": {
60
+ "@aws-sdk/client-dynamodb": "^3.0.0",
61
+ "@guren/server": ">=2.20.0",
52
62
  "aws-cdk-lib": "^2.156.0",
53
63
  "constructs": "^10.0.0"
54
64
  },
55
65
  "peerDependenciesMeta": {
66
+ "@aws-sdk/client-dynamodb": {
67
+ "optional": true
68
+ },
69
+ "@guren/server": {
70
+ "optional": true
71
+ },
56
72
  "aws-cdk-lib": {
57
73
  "optional": true
58
74
  },