Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[serverless] Add DynamoDB Span Pointers #4912

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/datadog-plugin-aws-sdk/src/services/dynamodb.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
'use strict'

const BaseAwsSdkPlugin = require('../base')
const log = require('../../../dd-trace/src/log')
const { DYNAMODB_PTR_KIND, SPAN_POINTER_DIRECTION } = require('../../../dd-trace/src/constants')
const { extractPrimaryKeys, generatePointerHash } = require('../../../dd-trace/src/util')

class DynamoDb extends BaseAwsSdkPlugin {
static get id () { return 'dynamodb' }
Expand Down Expand Up @@ -48,6 +51,47 @@ class DynamoDb extends BaseAwsSdkPlugin {

return tags
}

addSpanPointers (span, response) {
const request = response?.request
const operationName = request?.operation

const hashes = []
switch (operationName) {
case 'updateItem':
case 'deleteItem': {
const hash = DynamoDb.calculateHashWithKnownKeys(request?.params?.TableName, request?.params?.Key)
if (hash) hashes.push(hash)
break
}
}

for (const hash of hashes) {
span.addSpanPointer(DYNAMODB_PTR_KIND, SPAN_POINTER_DIRECTION.DOWNSTREAM, hash)
}
}

/**
* Calculates a hash for DynamoDB operations that have keys provided (UpdateItem, DeleteItem).
*
* @param {string} tableName - Name of the DynamoDB table.
* @param {Object} keys - Object containing primary key/value attributes in DynamoDB format.
* (e.g., { userId: { S: "123" }, sortKey: { N: "456" } })
* @returns {string|undefined} Hash value combining table name and primary key/value pairs, or undefined if unable.
*
* @example
* calculateKeyBasedOperationsHash('UserTable', { userId: { S: "user123" }, timestamp: { N: "1234567" } })
*/
static calculateHashWithKnownKeys (tableName, keys) {
if (!tableName || !keys) {
log.debug('Unable to calculate hash because missing parameters')
return
}
const keyValues = extractPrimaryKeys(keys, keys)
if (keyValues) {
return generatePointerHash([tableName, ...keyValues])
}
}
}

module.exports = DynamoDb
1 change: 1 addition & 0 deletions packages/dd-trace/src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ module.exports = {
SCHEMA_NAME: 'schema.name',
GRPC_CLIENT_ERROR_STATUSES: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
GRPC_SERVER_ERROR_STATUSES: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
DYNAMODB_PTR_KIND: 'aws.dynamodb.item',
S3_PTR_KIND: 'aws.s3.object',
SPAN_POINTER_DIRECTION: Object.freeze({
UPSTREAM: 'u',
Expand Down
73 changes: 72 additions & 1 deletion packages/dd-trace/src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,83 @@ function generatePointerHash (components) {
return hash.substring(0, 32)
}

/**
* Encodes a DynamoDB attribute value to Buffer for span pointer hashing.
* @param {Object} valueObject - DynamoDB value in AWS format ({ S: string } or { N: string } or { B: Buffer })
* @returns {Buffer} Encoded value as Buffer, or empty Buffer if invalid input.
*
* @example
* encodeValue({ S: "user123" }) -> Buffer("user123")
* encodeValue({ N: "42" }) -> Buffer("42")
* encodeValue({ B: Buffer([1, 2, 3]) }) -> Buffer([1, 2, 3])
*/
function encodeValue (valueObject) {
if (!valueObject) {
return Buffer.from('')
}

try {
const type = Object.keys(valueObject)[0]
const value = valueObject[type]

switch (type) {
case 'S':
return Buffer.from(value)
case 'N':
return Buffer.from(value.toString())
case 'B':
return Buffer.isBuffer(value) ? value : Buffer.from(value)
default:
return Buffer.from('')
}
} catch (err) {
return Buffer.from('')
}
}

/**
* Extracts and encodes primary key values from a DynamoDB item.
* Handles tables with single-key and two-key scenarios.
*
* @param {Set<string>|Object} keySet - Set of key names or object of key names/value pairs.
* @param {Object} keyValuePairs - Object containing key/value pairs.
* @returns {Array|undefined} [key1Name, key1Value, key2Name, key2Value], or undefined if invalid input.
* key2 entries are empty strings in the single-key case.
* @example
* extractPrimaryKeys(new Set(['userId']), {userId: {S: "user123"}})
* // Returns ["userId", Buffer("user123"), "", ""]
* extractPrimaryKeys(new Set(['userId', 'timestamp']), {userId: {S: "user123"}, timestamp: {N: "1234}})
* // Returns ["timestamp", Buffer.from("1234"), "userId", Buffer.from("user123")]
*/
const extractPrimaryKeys = (keySet, keyValuePairs) => {
const keyNames = keySet instanceof Set
? Array.from(keySet)
: Object.keys(keySet)
if (keyNames.length === 0) {
return
}

if (keyNames.length === 1) {
return [keyNames[0], encodeValue(keyValuePairs[keyNames[0]]), '', '']
} else {
const [key1, key2] = keyNames.sort()
return [
key1,
encodeValue(keyValuePairs[key1]),
key2,
encodeValue(keyValuePairs[key2])
]
}
}

module.exports = {
isTrue,
isFalse,
isError,
globMatch,
calculateDDBasePath,
hasOwn,
generatePointerHash
generatePointerHash,
encodeValue,
Copy link
Contributor Author

@nhulston nhulston Nov 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to export encodeValue for unit tests, but it's not used in any files; it's just a helper function for extractPrimaryKeys. Is this fine or is there something better practice I can do?

extractPrimaryKeys
}