xray_tracing/segment.rs
1use crate::{Seconds, SegmentId, TraceId};
2use serde_derive::{Deserialize, Serialize};
3use serde_json::Value;
4use std::{collections::HashMap, ops::Not};
5
6// https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html
7// https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html
8
9/// Description of an internal application operation
10/// which may be an extension of an external operation
11#[derive(Debug, Default, Serialize)]
12pub struct Segment {
13 /// A unique identifier that connects all segments and subsegments originating from a single client request.
14 pub(crate) trace_id: TraceId,
15 /// A 64-bit identifier for the segment, unique among segments in the same trace, in 16 hexadecimal digits.
16 pub(crate) id: SegmentId,
17 /// The logical name of the service that handled the request, up to 200 characters. For example, your application's name or domain name. Names can contain Unicode letters, numbers, and whitespace, and the following symbols: _, ., :, /, %, &, #, =, +, \, -, @
18 ///
19 /// A segment's name should match the domain name or logical name of the service that generates the segment. However, this is not enforced. Any application that has permission to PutTraceSegments can send segments with any name.
20 pub(crate) name: String,
21 /// Number that is the time the segment was created, in floating point seconds in epoch time.
22 pub(crate) start_time: Seconds,
23 #[serde(skip_serializing_if = "Option::is_none")]
24 /// Number that is the time the segment was closed.
25 pub end_time: Option<Seconds>,
26 #[serde(skip_serializing_if = "Not::not")]
27 /// boolean, set to true instead of specifying an end_time to record that a segment is started, but is not complete. Send an in-progress segment when your application receives a request that will take a long time to serve, to trace the request receipt. When the response is sent, send the complete segment to overwrite the in-progress segment. Only send one complete segment, and one or zero in-progress segments, per request.
28 pub in_progress: bool,
29 /// A subsegment ID you specify if the request originated from an instrumented application. The X-Ray SDK adds the parent subsegment ID to the tracing header for downstream HTTP calls.
30 #[serde(skip_serializing_if = "Option::is_none")]
31 pub parent_id: Option<SegmentId>,
32 /// Indicates that a server error occurred (response status code was 5XX Server Error).
33 #[serde(skip_serializing_if = "Not::not")]
34 pub fault: bool,
35 /// Indicates that a client error occurred (response status code was 4XX Client Error).
36 #[serde(skip_serializing_if = "Not::not")]
37 pub error: bool,
38 /// boolean indicating that a request was throttled (response status code was 429 Too Many Requests).
39 #[serde(skip_serializing_if = "Not::not")]
40 pub throttle: bool,
41 /// error fields that indicate an error occurred and that include information about the exception that caused the error.
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub cause: Option<Cause>,
44 /// The type of AWS resource running your application.
45 /// todo: convert to enum (see aws docs for values)
46 /// When multiple values are applicable to your application, use the one that is most specific. For example, a Multicontainer Docker Elastic Beanstalk environment runs your application on an Amazon ECS container, which in turn runs on an Amazon EC2 instance. In this case you would set the origin to AWS::ElasticBeanstalk::Environment as the environment is the parent of the other two resources.
47 #[serde(skip_serializing_if = "Option::is_none")]
48 pub origin: Option<String>,
49 /// A string that identifies the user who sent the request.
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub user: Option<String>,
52 ///
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub resource_arn: Option<String>,
55 /// http objects with information about the original HTTP request.
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub http: Option<Http>,
58 /// annotations object with key-value pairs that you want X-Ray to index for search.
59 #[serde(skip_serializing_if = "Option::is_none")]
60 pub annotations: Option<HashMap<String, Annotation>>,
61 /// metadata object with any additional data that you want to store in the segment.
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub metadata: Option<HashMap<String, Value>>,
64 /// aws object with information about the AWS resource on which your application served the request.
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub aws: Option<Aws>,
67 /// An object with information about your application.
68 #[serde(skip_serializing_if = "Option::is_none")]
69 pub service: Option<Service>,
70}
71
72/// An object with information about your application.
73#[derive(Debug, Default, Serialize)]
74pub struct Service {
75 /// A string that identifies the version of your application that served the request.
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub version: Option<String>,
78}
79
80/// Context information about the AWS environment this segment was run in
81#[derive(Debug, Default, Serialize)]
82pub struct Aws {
83 /// If your application sends segments to a different AWS account, record the ID of the account running your application.
84 #[serde(skip_serializing_if = "Option::is_none")]
85 pub account_id: Option<String>,
86 /// Information about an Amazon ECS container.
87 #[serde(skip_serializing_if = "Option::is_none")]
88 pub ecs: Option<Ecs>,
89 /// Information about an EC2 instance.
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub ec2: Option<Ec2>,
92 /// Information about an Elastic Beanstalk environment. You can find this information in a file named /var/elasticbeanstalk/xray/environment.conf on the latest Elastic Beanstalk platforms.
93 #[serde(skip_serializing_if = "Option::is_none")]
94 pub elastic_beanstalk: Option<ElasticBeanstalk>,
95 #[serde(skip_serializing_if = "Option::is_none")]
96 pub tracing: Option<Tracing>,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 pub xray: Option<XRay>,
99}
100
101#[derive(Debug, Default, Serialize)]
102pub struct XRay {
103 pub sdk_version: Option<String>,
104}
105
106#[derive(Debug, Default, Serialize)]
107pub struct Ecs {
108 /// The container ID of the container running your application.
109 #[serde(skip_serializing_if = "Option::is_none")]
110 pub container: Option<String>,
111}
112
113#[derive(Debug, Default, Serialize)]
114pub struct Ec2 {
115 /// The instance ID of the EC2 instance.
116 #[serde(skip_serializing_if = "Option::is_none")]
117 pub instance_id: Option<String>,
118 /// The Availability Zone in which the instance is running.
119 #[serde(skip_serializing_if = "Option::is_none")]
120 pub availability_zone: Option<String>,
121}
122
123/// Information about an Elastic Beanstalk environment. You can find this information in a file named /var/elasticbeanstalk/xray/environment.conf on the latest Elastic Beanstalk platforms.
124#[derive(Debug, Default, Serialize)]
125pub struct ElasticBeanstalk {
126 /// The name of the environment.
127 #[serde(skip_serializing_if = "Option::is_none")]
128 pub environment_name: Option<String>,
129 /// The name of the application version that is currently deployed to the instance that served the request.
130 #[serde(skip_serializing_if = "Option::is_none")]
131 pub version_label: Option<String>,
132 /// number indicating the ID of the last successful deployment to the instance that served the request.
133 #[serde(skip_serializing_if = "Option::is_none")]
134 pub deployment_id: Option<usize>,
135}
136
137#[derive(Debug, Default, Serialize)]
138pub struct Tracing {
139 /// version of sdk
140 pub sdk: Option<String>,
141}
142
143impl Default for Annotation {
144 fn default() -> Self {
145 Annotation::String("".into())
146 }
147}
148
149/// A value type which may be used for
150/// filter querying
151#[derive(Debug, Serialize)]
152#[serde(untagged)]
153pub enum Annotation {
154 /// A string value
155 String(String),
156 /// A numberic value
157 Number(usize),
158 /// A boolean value
159 Bool(bool),
160}
161
162/// Detailed representation of an exception
163#[derive(Debug, Serialize)]
164pub struct Exception {
165 /// A 64-bit identifier for the exception, unique among segments in the same trace, in 16 hexadecimal digits.
166 pub id: String,
167 /// The exception message.
168 #[serde(skip_serializing_if = "Option::is_none")]
169 pub messages: Option<String>,
170 /// The exception type.
171 #[serde(skip_serializing_if = "Option::is_none")]
172 pub remote: Option<bool>,
173 /// integer indicating the number of stack frames that are omitted from the stack.
174 #[serde(skip_serializing_if = "Option::is_none")]
175 pub truncated: Option<usize>,
176 /// integer indicating the number of exceptions that were skipped between this exception and its child, that is, the exception that it caused.
177 #[serde(skip_serializing_if = "Option::is_none")]
178 pub skipped: Option<usize>,
179 /// Exception ID of the exception's parent, that is, the exception that caused this exception.
180 #[serde(skip_serializing_if = "Option::is_none")]
181 pub cause: Option<String>,
182 /// array of stackFrame objects.
183 pub stack: Vec<StackFrame>,
184}
185
186/// A summary of a single operation within a stack trace
187#[derive(Debug, Serialize)]
188pub struct StackFrame {
189 /// The relative path to the file.
190 #[serde(skip_serializing_if = "Option::is_none")]
191 pub path: Option<String>,
192 /// The line in the file.
193 #[serde(skip_serializing_if = "Option::is_none")]
194 pub line: Option<String>,
195 /// The function or method name.
196 #[serde(skip_serializing_if = "Option::is_none")]
197 pub label: Option<String>,
198}
199
200/// Represents the cause of an errror
201#[derive(Debug, Serialize)]
202#[serde(untagged)]
203pub enum Cause {
204 /// a 16 character exception ID
205 Name(String),
206 /// A description of an error
207 Description {
208 /// The full path of the working directory when the exception occurred.
209 working_directory: String,
210 /// The array of paths to libraries or modules in use when the exception occurred.
211 paths: Vec<String>,
212 /// The array of exception objects.
213 exceptions: Vec<Exception>,
214 },
215}
216
217impl Segment {
218 /// Begins a new named segment
219 ///
220 /// A segment's name should match the domain name or logical name of the service that generates the segment. However, this is not enforced. Any application that has permission to PutTraceSegments can send segments with any name.
221 pub fn begin<N>(
222 name: N,
223 id: SegmentId,
224 parent_id: Option<SegmentId>,
225 trace_id: TraceId,
226 ) -> Self
227 where
228 N: Into<String>,
229 {
230 let mut valid_name = name.into();
231 if valid_name.len() > 200 {
232 valid_name = valid_name[..200].into();
233 }
234 Segment {
235 name: valid_name,
236 id,
237 parent_id,
238 trace_id,
239 in_progress: true,
240 aws: Some(Aws {
241 xray: Some(XRay {
242 sdk_version: Some(env!("CARGO_PKG_VERSION").into()),
243 }),
244 ..Aws::default()
245 }),
246 ..Segment::default()
247 }
248 }
249
250 /// End the segment by assigning its end_time
251 pub fn end(&mut self) -> &mut Self {
252 self.end_time = Some(Seconds::now());
253 self.in_progress = false;
254 self
255 }
256}
257
258/// Describes an http request/response cycle
259#[derive(Debug, Serialize, Deserialize, Default)]
260pub struct Http {
261 /// Information about a request
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub request: Option<Request>,
264 /// Information about a response.
265 #[serde(skip_serializing_if = "Option::is_none")]
266 pub response: Option<Response>,
267}
268
269/// Information about a request.
270#[derive(Debug, Serialize, Deserialize, Default)]
271pub struct Request {
272 /// The request method. For example, GET.
273 #[serde(skip_serializing_if = "Option::is_none")]
274 pub method: Option<String>,
275 /// The full URL of the request, compiled from the protocol, hostname, and path of the request.
276 #[serde(skip_serializing_if = "Option::is_none")]
277 pub url: Option<String>,
278 /// The IP address of the requester. Can be retrieved from the IP packet's Source Address or, for forwarded requests, from an X-Forwarded-For header.
279 #[serde(skip_serializing_if = "Option::is_none")]
280 pub client_ip: Option<String>,
281 /// The user agent string from the requester's client.
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub user_agent: Option<String>,
284 /// (segments only) boolean indicating that the client_ip was read from an X-Forwarded-For header and is not reliable as it could have been forged.
285 #[serde(skip_serializing_if = "Option::is_none")]
286 pub x_forwarded_for: Option<String>,
287 /// (subsegments only) boolean indicating that the downstream call is to another traced service. If this field is set to true, X-Ray considers the trace to be broken until the downstream service uploads a segment with a parent_id that matches the id of the subsegment that contains this block.
288 #[serde(skip_serializing_if = "Option::is_none")]
289 pub traced: Option<bool>,
290}
291
292/// Information about a response.
293#[derive(Debug, Serialize, Deserialize, Default)]
294pub struct Response {
295 /// number indicating the HTTP status of the response.
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub status: Option<u16>,
298 /// number indicating the length of the response body in bytes.
299 #[serde(skip_serializing_if = "Option::is_none")]
300 pub content_length: Option<u64>,
301}
302
303impl Subsegment {
304 /// Create a new subsegment
305 pub fn begin<N>(
306 name: N,
307 id: SegmentId,
308 parent_id: Option<SegmentId>,
309 trace_id: TraceId,
310 ) -> Self
311 where
312 N: Into<String>,
313 {
314 let mut valid_name = name.into();
315 if valid_name.len() > 200 {
316 valid_name = valid_name[..200].into();
317 }
318 Subsegment {
319 name: valid_name,
320 id,
321 trace_id: Some(trace_id),
322 parent_id,
323 type_: "subsegment".into(),
324 in_progress: true,
325 ..Subsegment::default()
326 }
327 }
328
329 /// End the subsegment by assigning its end_time
330 pub fn end(&mut self) -> &mut Self {
331 self.end_time = Some(Seconds::now());
332 self.in_progress = false;
333 self
334 }
335}
336
337/// Record information about the AWS services and resources that your application accesses. X-Ray uses this information to create inferred segments that represent the downstream services in your service map.
338#[derive(Debug, Default, Serialize)]
339pub struct Subsegment {
340 /// The logical name of the subsegment. For downstream calls, name the subsegment after the resource or service called. For custom subsegments, name the subsegment after the code that it instruments (e.g., a function name).
341 pub(crate) name: String,
342 /// A 64-bit identifier for the subsegment, unique among segments in the same trace, in 16 hexadecimal digits.
343 pub(crate) id: SegmentId,
344 /// number that is the time the subsegment was created, in floating point seconds in epoch time, accurate to milliseconds. For example, 1480615200.010 or 1.480615200010E9.
345 pub(crate) start_time: Seconds,
346 /// number that is the time the subsegment was closed. For example, 1480615200.090 or 1.480615200090E9. Specify an end_time or in_progress.
347 #[serde(skip_serializing_if = "Option::is_none")]
348 pub(crate) end_time: Option<Seconds>,
349 /// Trace ID of the subsegment's parent segment. Required only if sending a subsegment separately.
350 #[serde(skip_serializing_if = "Option::is_none")]
351 pub trace_id: Option<TraceId>,
352 /// Segment ID of the subsegment's parent segment. Required only if sending a subsegment separately.
353 #[serde(skip_serializing_if = "Option::is_none")]
354 pub parent_id: Option<SegmentId>,
355 /// boolean that is set to true instead of specifying an end_time to record that a subsegment is started, but is not complete. Only send one complete subsegment, and one or zero in-progress subsegments, per downstream request.
356 #[serde(skip_serializing_if = "Not::not")]
357 pub in_progress: bool,
358 /// boolean indicating that a server error occurred (response status code was 5XX Server Error).
359 #[serde(skip_serializing_if = "Not::not")]
360 pub fault: bool,
361 /// boolean indicating that a client error occurred (response status code was 4XX Client Error).
362 #[serde(skip_serializing_if = "Not::not")]
363 pub error: bool,
364 /// boolean indicating that a request was throttled (response status code was 429 Too Many Requests).
365 #[serde(skip_serializing_if = "Not::not")]
366 pub throttled: bool,
367 /// aws for AWS SDK calls; remote for other downstream calls.
368 #[serde(skip_serializing_if = "Option::is_none")]
369 pub namespace: Option<String>,
370 ///
371 #[serde(skip_serializing_if = "Option::is_none")]
372 pub traced: Option<bool>,
373 /// array of subsegment IDs that identifies subsegments with the same parent that completed prior to this subsegment.
374 #[serde(skip_serializing_if = "Option::is_none")]
375 pub precursor_ids: Option<Vec<String>>,
376 /// information about the cause of an error
377 #[serde(skip_serializing_if = "Option::is_none")]
378 pub cause: Option<Cause>,
379 /// annotations object with key-value pairs that you want X-Ray to index for search.
380 #[serde(skip_serializing_if = "Option::is_none")]
381 pub annotations: Option<HashMap<String, Annotation>>,
382 /// metadata object with any additional data that you want to store in the segment.
383 #[serde(skip_serializing_if = "Option::is_none")]
384 pub metadata: Option<HashMap<String, Value>>,
385 /// subsegment. Required only if sending a subsegment separately.
386 #[serde(rename = "type")]
387 pub type_: String,
388 /// array of subsegment objects.
389 #[serde(skip_serializing_if = "Vec::is_empty")]
390 pub subsegments: Vec<Subsegment>,
391 /// http object with information about an outgoing HTTP call.
392 #[serde(skip_serializing_if = "Option::is_none")]
393 pub http: Option<Http>,
394 /// aws object with information about the downstream AWS resource that your application called.
395 #[serde(skip_serializing_if = "Option::is_none")]
396 pub aws: Option<AwsOperation>,
397 /// contents of the sql query
398 #[serde(skip_serializing_if = "Option::is_none")]
399 pub sql: Option<Sql>,
400}
401
402/// Information about an AWS operation
403#[derive(Debug, Default, Serialize)]
404pub struct AwsOperation {
405 /// The name of the API action invoked against an AWS service or resource.
406 #[serde(skip_serializing_if = "Option::is_none")]
407 pub operation: Option<String>,
408 /// If your application accesses resources in a different account, or sends segments to a different account, record the ID of the account that owns the AWS resource that your application accessed.
409 #[serde(skip_serializing_if = "Option::is_none")]
410 pub account_id: Option<String>,
411 /// If the resource is in a region different from your application, record the region. For example, us-west-2.
412 #[serde(skip_serializing_if = "Option::is_none")]
413 pub region: Option<String>,
414 /// Unique identifier for the request.
415 #[serde(skip_serializing_if = "Option::is_none")]
416 pub request_id: Option<String>,
417 /// For operations on an Amazon SQS queue, the queue's URL.
418 #[serde(skip_serializing_if = "Option::is_none")]
419 pub queue_url: Option<String>,
420 /// For operations on a DynamoDB table, the name of the table.
421 #[serde(skip_serializing_if = "Option::is_none")]
422 pub table_name: Option<String>,
423}
424
425/// Information about a SQL operation
426#[derive(Debug, Default, Serialize)]
427pub struct Sql {
428 /// For SQL Server or other database connections that don't use URL connection strings, record the connection string, excluding passwords.
429 #[serde(skip_serializing_if = "Option::is_none")]
430 pub connection_string: Option<String>,
431 /// For a database connection that uses a URL connection string, record the URL, excluding passwords.
432 #[serde(skip_serializing_if = "Option::is_none")]
433 pub url: Option<String>,
434 /// The database query, with any user provided values removed or replaced by a placeholder.
435 #[serde(skip_serializing_if = "Option::is_none")]
436 pub sanitized_query: Option<String>,
437 /// The name of the database engine.
438 #[serde(skip_serializing_if = "Option::is_none")]
439 pub database_type: Option<String>,
440 /// The version number of the database engine.
441 #[serde(skip_serializing_if = "Option::is_none")]
442 pub database_version: Option<String>,
443 /// The name and version number of the database engine driver that your application uses.
444 #[serde(skip_serializing_if = "Option::is_none")]
445 pub driver_version: Option<String>,
446 /// The database username.
447 #[serde(skip_serializing_if = "Option::is_none")]
448 pub user: Option<String>,
449 /// call if the query used a PreparedCall; statement if the query used a PreparedStatement.
450 #[serde(skip_serializing_if = "Option::is_none")]
451 pub preparation: Option<String>,
452}
453
454#[cfg(test)]
455mod tests {
456 use super::{Seconds, Segment, SegmentId, Subsegment, TraceId};
457
458 #[test]
459 fn segments_begin_with_names_with_a_max_len() {
460 assert_eq!(
461 Segment::begin("short", SegmentId::default(), None, TraceId::default()).name,
462 "short"
463 );
464 assert_eq!(
465 Segment::begin(
466 String::from_utf8_lossy(&[b'X'; 201]),
467 SegmentId::default(),
468 None,
469 TraceId::default()
470 )
471 .name
472 .len(),
473 200
474 );
475 }
476
477 #[test]
478 fn subsegments_begin_with_names_with_a_max_len() {
479 assert_eq!(
480 Subsegment::begin("short", SegmentId::default(), None, TraceId::default()).name,
481 "short"
482 );
483 assert_eq!(
484 Subsegment::begin(
485 String::from_utf8_lossy(&[b'X'; 201]),
486 SegmentId::default(),
487 None,
488 TraceId::default()
489 )
490 .name
491 .len(),
492 200
493 );
494 }
495
496 #[test]
497 fn segments_serialize() {
498 assert_eq!(
499 r#"{"trace_id":"1-581cf771-a006649127e371903a2de979","id":"70de5b6f19ff9a0a","name":"Scorekeep","start_time":1478293361.271,"end_time":1478293361.449}"#,
500 serde_json::to_string(&Segment {
501 name: "Scorekeep".into(),
502 id: SegmentId::Rendered("70de5b6f19ff9a0a".into()),
503 start_time: Seconds(1_478_293_361.271),
504 trace_id: TraceId::Rendered("1-581cf771-a006649127e371903a2de979".into()),
505 end_time: Some(Seconds(1_478_293_361.449)),
506 ..Segment::default()
507 })
508 .expect("failed to serialize")
509 )
510 }
511}