forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction-search.ts
More file actions
141 lines (132 loc) · 5.02 KB
/
Copy pathtransaction-search.ts
File metadata and controls
141 lines (132 loc) · 5.02 KB
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
import { AccessDeniedError } from '../../lib';
import type { Result } from '../../lib/result';
import { getErrorMessage, isAccessDeniedError } from '../errors';
import { getCredentialProvider } from './account';
import { arnPrefix } from './partition';
import { ApplicationSignalsClient, StartDiscoveryCommand } from '@aws-sdk/client-application-signals';
import {
CloudWatchLogsClient,
DescribeResourcePoliciesCommand,
PutResourcePolicyCommand,
} from '@aws-sdk/client-cloudwatch-logs';
import {
GetTraceSegmentDestinationCommand,
UpdateIndexingRuleCommand,
UpdateTraceSegmentDestinationCommand,
XRayClient,
} from '@aws-sdk/client-xray';
const RESOURCE_POLICY_NAME = 'TransactionSearchXRayAccess';
/**
* Enable CloudWatch Transaction Search:
* 1. Start Application Signals discovery (idempotent)
* 2. Create CloudWatch Logs resource policy for X-Ray access (if needed)
* 3. Set trace segment destination to CloudWatchLogs
* 4. Set indexing to 100%
*
* All operations are idempotent — safe to call on every deploy.
*/
export async function enableTransactionSearch(
region: string,
accountId: string,
indexPercentage = 100
): Promise<Result> {
const credentials = getCredentialProvider();
// Step 1: Enable Application Signals (creates service-linked role, idempotent)
try {
const appSignalsClient = new ApplicationSignalsClient({ region, credentials });
await appSignalsClient.send(new StartDiscoveryCommand({}));
} catch (err: unknown) {
const message = getErrorMessage(err);
if (isAccessDeniedError(err)) {
return {
success: false,
error: new AccessDeniedError(`Insufficient permissions to enable Application Signals: ${message}`, {
cause: err,
}),
};
}
return { success: false, error: new Error(`Failed to enable Application Signals: ${message}`, { cause: err }) };
}
// Step 2: Create CloudWatch Logs resource policy for X-Ray (if needed)
try {
const logsClient = new CloudWatchLogsClient({ region, credentials });
const policiesResult = await logsClient.send(new DescribeResourcePoliciesCommand({}));
const hasPolicy = policiesResult.resourcePolicies?.some(p => p.policyName === RESOURCE_POLICY_NAME);
if (!hasPolicy) {
const policyDocument = JSON.stringify({
Version: '2012-10-17',
Statement: [
{
Sid: 'TransactionSearchXRayAccess',
Effect: 'Allow',
Principal: { Service: 'xray.amazonaws.com' },
Action: 'logs:PutLogEvents',
Resource: [
`${arnPrefix(region)}:logs:${region}:${accountId}:log-group:aws/spans:*`,
`${arnPrefix(region)}:logs:${region}:${accountId}:log-group:/aws/application-signals/data:*`,
],
Condition: {
ArnLike: { 'aws:SourceArn': `${arnPrefix(region)}:xray:${region}:${accountId}:*` },
StringEquals: { 'aws:SourceAccount': accountId },
},
},
],
});
await logsClient.send(new PutResourcePolicyCommand({ policyName: RESOURCE_POLICY_NAME, policyDocument }));
}
} catch (err: unknown) {
const message = getErrorMessage(err);
if (isAccessDeniedError(err)) {
return {
success: false,
error: new AccessDeniedError(`Insufficient permissions to configure CloudWatch Logs policy: ${message}`, {
cause: err,
}),
};
}
return {
success: false,
error: new Error(`Failed to configure CloudWatch Logs policy: ${message}`, { cause: err }),
};
}
const xrayClient = new XRayClient({ region, credentials });
// Step 3: Set trace segment destination to CloudWatchLogs
try {
const destResult = await xrayClient.send(new GetTraceSegmentDestinationCommand({}));
if (destResult.Destination !== 'CloudWatchLogs') {
await xrayClient.send(new UpdateTraceSegmentDestinationCommand({ Destination: 'CloudWatchLogs' }));
}
} catch (err: unknown) {
const message = getErrorMessage(err);
if (isAccessDeniedError(err)) {
return {
success: false,
error: new AccessDeniedError(`Insufficient permissions to configure trace destination: ${message}`, {
cause: err,
}),
};
}
return { success: false, error: new Error(`Failed to configure trace destination: ${message}`, { cause: err }) };
}
// Step 4: Set indexing to 100% on the built-in Default rule (always exists, idempotent)
try {
await xrayClient.send(
new UpdateIndexingRuleCommand({
Name: 'Default',
Rule: { Probabilistic: { DesiredSamplingPercentage: indexPercentage } },
})
);
} catch (err: unknown) {
const message = getErrorMessage(err);
if (isAccessDeniedError(err)) {
return {
success: false,
error: new AccessDeniedError(`Insufficient permissions to configure indexing rules: ${message}`, {
cause: err,
}),
};
}
return { success: false, error: new Error(`Failed to configure indexing rules: ${message}`, { cause: err }) };
}
return { success: true };
}