Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | 27x 27x | import { z } from 'zod/v3'
import { StructuredTool } from '@langchain/core/tools'
import { ICommonObject, INode, INodeData, INodeOptionsValue, INodeParams } from '../../../src/Interface'
import { getBaseClasses } from '../../../src/utils'
import { AWS_REGIONS, DEFAULT_AWS_REGION, AWSCredentials, getAWSCredentials } from '../../../src/awsToolsUtils'
import { DynamoDBClient, DescribeTableCommand, ListTablesCommand, PutItemCommand, QueryCommand } from '@aws-sdk/client-dynamodb'
// Operation enum
enum Operation {
STORE = 'store',
RETRIEVE = 'retrieve'
}
// Constants
const ERROR_PLACEHOLDER = 'error'
const KEY_SEPARATOR = '#'
const MAX_KEY_LENGTH = 2048 // DynamoDB limit for partition key
// Helper function to create DynamoDB client
function createDynamoDBClient(credentials: AWSCredentials | undefined, region: string): DynamoDBClient {
const config: { region: string; credentials?: { accessKeyId: string; secretAccessKey: string; sessionToken?: string } } = { region }
Iif (credentials) {
config.credentials = {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
...(credentials.sessionToken && { sessionToken: credentials.sessionToken })
}
}
return new DynamoDBClient(config)
}
// Helper function to build full key with optional prefix
function buildFullKey(key: string, keyPrefix: string): string {
const fullKey = keyPrefix ? `${keyPrefix}${KEY_SEPARATOR}${key}` : key
// Validate key length (DynamoDB limit)
Iif (fullKey.length > MAX_KEY_LENGTH) {
throw new Error(`Key too long. Maximum length is ${MAX_KEY_LENGTH} characters, got ${fullKey.length}`)
}
return fullKey
}
// Helper function to validate and sanitize input
function validateKey(key: string): void {
Iif (!key || key.trim().length === 0) {
throw new Error('Key must be a non-empty string')
}
}
/**
* Tool for storing key-value pairs in DynamoDB with automatic versioning
*/
class DynamoDBStoreTool extends StructuredTool {
name = 'dynamodb_kv_store'
description = 'Store a text value with a key in DynamoDB. Input must be an object with "key" and "value" properties.'
schema = z.object({
key: z.string().min(1).describe('The key to store the value under'),
value: z.string().describe('The text value to store')
})
private readonly dynamoClient: DynamoDBClient
private readonly tableName: string
private readonly keyPrefix: string
constructor(dynamoClient: DynamoDBClient, tableName: string, keyPrefix: string = '') {
super()
this.dynamoClient = dynamoClient
this.tableName = tableName
this.keyPrefix = keyPrefix
}
async _call({ key, value }: z.infer<typeof this.schema>): Promise<string> {
try {
validateKey(key)
const fullKey = buildFullKey(key, this.keyPrefix)
const timestamp = Date.now()
const isoTimestamp = new Date(timestamp).toISOString()
const putCommand = new PutItemCommand({
TableName: this.tableName,
Item: {
pk: { S: fullKey },
sk: { S: timestamp.toString() },
value: { S: value },
timestamp: { S: isoTimestamp }
}
})
await this.dynamoClient.send(putCommand)
return `Successfully stored value with key "${key}" at ${isoTimestamp}`
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
throw new Error(`Failed to store value: ${errorMessage}`)
}
}
}
/**
* Tool for retrieving key-value pairs from DynamoDB with version control
*/
class DynamoDBRetrieveTool extends StructuredTool {
name = 'dynamodb_kv_retrieve'
description =
'Retrieve a value by key from DynamoDB. Returns JSON with value and timestamp. Specify which version to get (1=latest, 2=2nd latest, etc).'
schema = z.object({
key: z.string().min(1).describe('The key to retrieve the value for'),
nthLatest: z
.string()
.regex(/^\d+$/, 'Must be a positive number')
.describe(
'Which version to retrieve: "1" for latest, "2" for 2nd latest, "3" for 3rd latest, etc. Use "1" to get the most recent value.'
)
.optional()
.default('1')
})
private readonly dynamoClient: DynamoDBClient
private readonly tableName: string
private readonly keyPrefix: string
constructor(dynamoClient: DynamoDBClient, tableName: string, keyPrefix: string = '') {
super()
this.dynamoClient = dynamoClient
this.tableName = tableName
this.keyPrefix = keyPrefix
}
async _call(input: z.infer<typeof this.schema>): Promise<string> {
try {
const { key, nthLatest = '1' } = input
validateKey(key)
const fullKey = buildFullKey(key, this.keyPrefix)
// Convert string to number and validate
const nthLatestNum = parseInt(nthLatest, 10)
Iif (isNaN(nthLatestNum) || nthLatestNum < 1) {
throw new Error('nthLatest must be a positive number (1 or greater)')
}
const queryCommand = new QueryCommand({
TableName: this.tableName,
KeyConditionExpression: 'pk = :pk',
ExpressionAttributeValues: {
':pk': { S: fullKey }
},
ScanIndexForward: false, // Sort descending (newest first)
Limit: nthLatestNum
})
const result = await this.dynamoClient.send(queryCommand)
Iif (!result.Items || result.Items.length === 0) {
return JSON.stringify({
value: null,
timestamp: null
})
}
Iif (result.Items.length < nthLatestNum) {
return JSON.stringify({
value: null,
timestamp: null
})
}
const item = result.Items[nthLatestNum - 1]
const value = item.value?.S || null
const timestamp = item.timestamp?.S || item.sk?.S || null
// Return JSON with value and timestamp
return JSON.stringify({
value: value,
timestamp: timestamp
})
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
throw new Error(`Failed to retrieve value: ${errorMessage}`)
}
}
}
/**
* Node implementation for AWS DynamoDB KV Storage tools
*/
class AWSDynamoDBKVStorage_Tools implements INode {
label: string
name: string
version: number
type: string
icon: string
category: string
description: string
baseClasses: string[]
credential: INodeParams
inputs: INodeParams[]
constructor() {
this.label = 'AWS DynamoDB KV Storage'
this.name = 'awsDynamoDBKVStorage'
this.version = 1.0
this.type = 'AWSDynamoDBKVStorage'
this.icon = 'dynamodbkvstorage.svg'
this.category = 'Tools'
this.description = 'Store and retrieve versioned text values in AWS DynamoDB'
this.baseClasses = [this.type, ...getBaseClasses(DynamoDBStoreTool)]
this.credential = {
label: 'AWS Credentials',
name: 'credential',
type: 'credential',
credentialNames: ['awsApi']
}
this.inputs = [
{
label: 'AWS Region',
name: 'region',
type: 'options',
options: AWS_REGIONS,
default: DEFAULT_AWS_REGION,
description: 'AWS Region where your DynamoDB tables are located'
},
{
label: 'DynamoDB Table',
name: 'tableName',
type: 'asyncOptions',
loadMethod: 'listTables',
description: 'Select a DynamoDB table with partition key "pk" and sort key "sk"',
refresh: true
},
{
label: 'Key Prefix',
name: 'keyPrefix',
type: 'string',
description: 'Optional prefix to add to all keys (e.g., "myapp" would make keys like "myapp#userdata")',
optional: true,
additionalParams: true
},
{
label: 'Operation',
name: 'operation',
type: 'options',
options: [
{ label: 'Store', name: Operation.STORE },
{ label: 'Retrieve', name: Operation.RETRIEVE }
],
default: Operation.STORE,
description: 'Choose whether to store or retrieve data'
}
]
}
loadMethods: Record<string, (_nodeData: INodeData, _options?: ICommonObject) => Promise<INodeOptionsValue[]>> = {
listTables: async (_nodeData: INodeData, _options?: ICommonObject): Promise<INodeOptionsValue[]> => {
try {
const credentials = await getAWSCredentials(_nodeData, _options ?? {})
const region = (_nodeData.inputs?.region as string) || DEFAULT_AWS_REGION
const dynamoClient = createDynamoDBClient(credentials, region)
const listCommand = new ListTablesCommand({})
const listResponse = await dynamoClient.send(listCommand)
Iif (!listResponse.TableNames || listResponse.TableNames.length === 0) {
return [
{
label: 'No tables found',
name: ERROR_PLACEHOLDER,
description: 'No DynamoDB tables found in this region'
}
]
}
const validTables: INodeOptionsValue[] = []
const invalidTables: string[] = []
// Check tables in parallel for better performance
const tableChecks = await Promise.allSettled(
listResponse.TableNames.map(async (tableName) => {
const describeCommand = new DescribeTableCommand({
TableName: tableName
})
const describeResponse = await dynamoClient.send(describeCommand)
const keySchema = describeResponse.Table?.KeySchema
Iif (keySchema) {
const hasPk = keySchema.some((key) => key.AttributeName === 'pk' && key.KeyType === 'HASH')
const hasSk = keySchema.some((key) => key.AttributeName === 'sk' && key.KeyType === 'RANGE')
Iif (hasPk && hasSk) {
return {
valid: true,
table: {
label: tableName,
name: tableName,
description: `Table with pk (partition) and sk (sort) keys`
}
}
}
}
return { valid: false, tableName }
})
)
tableChecks.forEach((result) => {
Iif (result.status === 'fulfilled') {
if (result.value.valid) {
validTables.push(result.value.table!)
} else Iif (result.value.tableName) {
invalidTables.push(result.value.tableName)
}
}
})
Iif (validTables.length === 0) {
return [
{
label: 'No compatible tables found',
name: ERROR_PLACEHOLDER,
description: `No tables with partition key "pk" and sort key "sk" found. ${
invalidTables.length > 0 ? `Found ${invalidTables.length} table(s) with different schema.` : ''
} Please create a table with these keys.`
}
]
}
// Sort tables alphabetically
validTables.sort((a, b) => a.label.localeCompare(b.label))
return validTables
} catch (error) {
Iif (error instanceof Error && error.message.includes('AWS Access Key')) {
return [
{
label: 'AWS Credentials Required',
name: ERROR_PLACEHOLDER,
description: 'Enter AWS Access Key ID and Secret Access Key'
}
]
}
console.error('Error loading DynamoDB tables:', error)
return [
{
label: 'Error Loading Tables',
name: ERROR_PLACEHOLDER,
description: `Failed to load tables: ${error instanceof Error ? error.message : String(error)}`
}
]
}
}
}
async init(nodeData: INodeData, _: string, options: ICommonObject): Promise<any> {
const credentials = await getAWSCredentials(nodeData, options)
const region = (nodeData.inputs?.region as string) || DEFAULT_AWS_REGION
const tableName = nodeData.inputs?.tableName as string
const keyPrefix = (nodeData.inputs?.keyPrefix as string) || ''
const operation = (nodeData.inputs?.operation as string) || Operation.STORE
Iif (!tableName || tableName === ERROR_PLACEHOLDER) {
throw new Error('Valid DynamoDB Table selection is required')
}
// Validate key prefix doesn't contain separator
Iif (keyPrefix && keyPrefix.includes(KEY_SEPARATOR)) {
throw new Error(`Key prefix cannot contain "${KEY_SEPARATOR}" character`)
}
const dynamoClient = createDynamoDBClient(credentials, region)
if (operation === Operation.STORE) {
return new DynamoDBStoreTool(dynamoClient, tableName, keyPrefix)
} else {
return new DynamoDBRetrieveTool(dynamoClient, tableName, keyPrefix)
}
}
}
module.exports = { nodeClass: AWSDynamoDBKVStorage_Tools }
|