xray_lite/
segment.rs

1use crate::{Seconds, SegmentId, TraceId};
2use serde::{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    /// Metadata about the type and version of instrumentation used.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub xray: Option<XRay>,
98}
99
100/// Metadata about the type and version of instrumentation used.
101#[derive(Debug, Default, Serialize)]
102pub struct XRay {
103    /// The version of SDK or agent being used.
104    pub sdk_version: Option<String>,
105}
106
107/// Information about an Amazon ECS container.
108#[derive(Debug, Default, Serialize)]
109pub struct Ecs {
110    /// The container ID of the container running your application.
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub container: Option<String>,
113}
114
115/// Information about an EC2 instance.
116#[derive(Debug, Default, Serialize)]
117pub struct Ec2 {
118    /// The instance ID of the EC2 instance.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub instance_id: Option<String>,
121    /// The Availability Zone in which the instance is running.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub availability_zone: Option<String>,
124}
125
126/// 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.
127#[derive(Debug, Default, Serialize)]
128pub struct ElasticBeanstalk {
129    /// The name of the environment.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub environment_name: Option<String>,
132    ///  The name of the application version that is currently deployed to the instance that served the request.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub version_label: Option<String>,
135    /// number indicating the ID of the last successful deployment to the instance that served the request.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub deployment_id: Option<usize>,
138}
139
140impl Default for Annotation {
141    fn default() -> Self {
142        Annotation::String("".into())
143    }
144}
145
146/// A value type which may be used for
147/// filter querying
148#[derive(Debug, Serialize)]
149#[serde(untagged)]
150pub enum Annotation {
151    /// A string value
152    String(String),
153    /// A numberic value
154    Number(usize),
155    /// A boolean value
156    Bool(bool),
157}
158
159/// Detailed representation of an exception
160#[derive(Debug, Serialize)]
161pub struct Exception {
162    /// A 64-bit identifier for the exception, unique among segments in the same trace, in 16 hexadecimal digits.
163    pub id: String,
164    /// The exception message.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub messages: Option<String>,
167    /// The exception type.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub remote: Option<bool>,
170    /// integer indicating the number of stack frames that are omitted from the stack.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub truncated: Option<usize>,
173    ///  integer indicating the number of exceptions that were skipped between this exception and its child, that is, the exception that it caused.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub skipped: Option<usize>,
176    /// Exception ID of the exception's parent, that is, the exception that caused this exception.
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub cause: Option<String>,
179    /// array of stackFrame objects.
180    pub stack: Vec<StackFrame>,
181}
182
183/// A summary of a single operation within a stack trace
184#[derive(Debug, Serialize)]
185pub struct StackFrame {
186    /// The relative path to the file.
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub path: Option<String>,
189    /// The line in the file.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub line: Option<String>,
192    /// The function or method name.
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub label: Option<String>,
195}
196
197/// Represents the cause of an errror
198#[derive(Debug, Serialize)]
199#[serde(untagged)]
200pub enum Cause {
201    ///  a 16 character exception ID
202    Name(String),
203    /// A description of an error
204    Description {
205        ///  The full path of the working directory when the exception occurred.
206        working_directory: String,
207        ///  The array of paths to libraries or modules in use when the exception occurred.
208        paths: Vec<String>,
209        /// The array of exception objects.
210        exceptions: Vec<Exception>,
211    },
212}
213
214impl Segment {
215    /// Begins a new named segment
216    ///
217    /// 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.
218    pub fn begin<N>(name: N) -> Self
219    where
220        N: Into<String>,
221    {
222        let mut valid_name = name.into();
223        if valid_name.len() > 200 {
224            valid_name = valid_name[..200].into();
225        }
226        Segment {
227            name: valid_name,
228            ..Segment::default()
229        }
230    }
231
232    /// End the segment by assigning its end_time
233    pub fn end(&mut self) -> &mut Self {
234        self.end_time = Some(Seconds::now());
235        self.in_progress = false;
236        self
237    }
238}
239
240/// Describes an http request/response cycle
241#[derive(Debug, Serialize, Deserialize, Default)]
242pub struct Http {
243    /// Information about a request
244    #[serde(skip_serializing_if = "Option::is_none")]
245    pub request: Option<Request>,
246    /// Information about a response.
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub response: Option<Response>,
249}
250
251///  Information about a request.
252#[derive(Debug, Serialize, Deserialize, Default)]
253pub struct Request {
254    /// The request method. For example, GET.
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub method: Option<String>,
257    /// The full URL of the request, compiled from the protocol, hostname, and path of the request.
258    #[serde(skip_serializing_if = "Option::is_none")]
259    pub url: Option<String>,
260    /// 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.
261    #[serde(skip_serializing_if = "Option::is_none")]
262    pub client_ip: Option<String>,
263    /// The user agent string from the requester's client.
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub user_agent: Option<String>,
266    /// (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.
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub x_forwarded_for: Option<String>,
269    /// (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.
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub traced: Option<bool>,
272}
273
274///  Information about a response.
275#[derive(Debug, Serialize, Deserialize, Default)]
276pub struct Response {
277    /// number indicating the HTTP status of the response.
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub status: Option<u16>,
280    /// number indicating the length of the response body in bytes.
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub content_length: Option<u64>,
283}
284
285impl Subsegment {
286    /// Create a new subsegment
287    pub fn begin<N>(trace_id: TraceId, parent_id: Option<SegmentId>, name: N) -> Self
288    where
289        N: Into<String>,
290    {
291        let mut valid_name = name.into();
292        if valid_name.len() > 200 {
293            valid_name = valid_name[..200].into();
294        }
295        Subsegment {
296            name: valid_name,
297            trace_id: Some(trace_id),
298            parent_id,
299            type_: "subsegment".into(),
300            in_progress: true,
301            ..Subsegment::default()
302        }
303    }
304
305    /// End the subsegment by assigning its end_time
306    pub fn end(&mut self) -> &mut Self {
307        self.end_time = Some(Seconds::now());
308        self.in_progress = false;
309        self
310    }
311}
312
313/// 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.
314#[derive(Debug, Default, Serialize)]
315pub struct Subsegment {
316    /// 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).
317    pub(crate) name: String,
318    /// A 64-bit identifier for the subsegment, unique among segments in the same trace, in 16 hexadecimal digits.
319    pub(crate) id: SegmentId,
320    /// 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.
321    pub(crate) start_time: Seconds,
322    /// number that is the time the subsegment was closed. For example, 1480615200.090 or 1.480615200090E9. Specify an end_time or in_progress.
323    #[serde(skip_serializing_if = "Option::is_none")]
324    pub(crate) end_time: Option<Seconds>,
325    /// Trace ID of the subsegment's parent segment. Required only if sending a subsegment separately.
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub trace_id: Option<TraceId>,
328    /// Segment ID of the subsegment's parent segment. Required only if sending a subsegment separately.
329    #[serde(skip_serializing_if = "Option::is_none")]
330    pub parent_id: Option<SegmentId>,
331    /// 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.
332    #[serde(skip_serializing_if = "Not::not")]
333    pub in_progress: bool,
334    /// boolean indicating that a server error occurred (response status code was 5XX Server Error).
335    #[serde(skip_serializing_if = "Not::not")]
336    pub fault: bool,
337    /// boolean indicating that a client error occurred (response status code was 4XX Client Error).
338    #[serde(skip_serializing_if = "Not::not")]
339    pub error: bool,
340    ///  boolean indicating that a request was throttled (response status code was 429 Too Many Requests).
341    #[serde(skip_serializing_if = "Not::not")]
342    pub throttled: bool,
343    /// aws for AWS SDK calls; remote for other downstream calls.
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub namespace: Option<String>,
346    ///
347    #[serde(skip_serializing_if = "Option::is_none")]
348    pub traced: Option<bool>,
349    /// array of subsegment IDs that identifies subsegments with the same parent that completed prior to this subsegment.
350    #[serde(skip_serializing_if = "Option::is_none")]
351    pub precursor_ids: Option<Vec<String>>,
352    /// information about the cause of an error
353    #[serde(skip_serializing_if = "Option::is_none")]
354    pub cause: Option<Cause>,
355    /// annotations object with key-value pairs that you want X-Ray to index for search.
356    #[serde(skip_serializing_if = "Option::is_none")]
357    pub annotations: Option<HashMap<String, Annotation>>,
358    /// metadata object with any additional data that you want to store in the segment.
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub metadata: Option<HashMap<String, Value>>,
361    /// subsegment. Required only if sending a subsegment separately.
362    #[serde(rename = "type")]
363    pub type_: String,
364    /// array of subsegment objects.
365    #[serde(skip_serializing_if = "Vec::is_empty")]
366    pub subsegments: Vec<Subsegment>,
367    ///  http object with information about an outgoing HTTP call.
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub http: Option<Http>,
370    /// aws object with information about the downstream AWS resource that your application called.
371    #[serde(skip_serializing_if = "Option::is_none")]
372    pub aws: Option<AwsOperation>,
373    /// contents of the sql query
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub sql: Option<Sql>,
376}
377
378/// Information about an AWS operation
379#[derive(Debug, Default, Serialize)]
380pub struct AwsOperation {
381    /// The name of the API action invoked against an AWS service or resource.
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub operation: Option<String>,
384    /// 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.
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub account_id: Option<String>,
387    /// If the resource is in a region different from your application, record the region. For example, us-west-2.
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub region: Option<String>,
390    /// Unique identifier for the request.
391    #[serde(skip_serializing_if = "Option::is_none")]
392    pub request_id: Option<String>,
393    /// For operations on an Amazon SQS queue, the queue's URL.
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub queue_url: Option<String>,
396    /// For operations on a DynamoDB table, the name of the table.
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub table_name: Option<String>,
399}
400
401/// Information about a SQL operation
402#[derive(Debug, Default, Serialize)]
403pub struct Sql {
404    /// For SQL Server or other database connections that don't use URL connection strings, record the connection string, excluding passwords.
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub connection_string: Option<String>,
407    /// For a database connection that uses a URL connection string, record the URL, excluding passwords.
408    #[serde(skip_serializing_if = "Option::is_none")]
409    pub url: Option<String>,
410    /// The database query, with any user provided values removed or replaced by a placeholder.
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub sanitized_query: Option<String>,
413    /// The name of the database engine.
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub database_type: Option<String>,
416    /// The version number of the database engine.
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub database_version: Option<String>,
419    /// The name and version number of the database engine driver that your application uses.
420    #[serde(skip_serializing_if = "Option::is_none")]
421    pub driver_version: Option<String>,
422    /// The database username.
423    #[serde(skip_serializing_if = "Option::is_none")]
424    pub user: Option<String>,
425    /// call if the query used a PreparedCall; statement if the query used a PreparedStatement.
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub preparation: Option<String>,
428}
429
430#[cfg(test)]
431mod tests {
432    use super::{Seconds, Segment, SegmentId, Subsegment, TraceId};
433
434    #[test]
435    fn segments_begin_with_names_with_a_max_len() {
436        assert_eq!(Segment::begin("short").name, "short");
437        assert_eq!(
438            Segment::begin(String::from_utf8_lossy(&[b'X'; 201]))
439                .name
440                .len(),
441            200
442        );
443    }
444
445    #[test]
446    fn subsegments_begin_with_names_with_a_max_len() {
447        assert_eq!(
448            Subsegment::begin(TraceId::default(), None, "short").name,
449            "short"
450        );
451        assert_eq!(
452            Subsegment::begin(
453                TraceId::default(),
454                None,
455                String::from_utf8_lossy(&[b'X'; 201])
456            )
457            .name
458            .len(),
459            200
460        );
461    }
462
463    #[test]
464    fn segments_serialize() {
465        assert_eq!(
466            r#"{"trace_id":"1-581cf771-a006649127e371903a2de979","id":"70de5b6f19ff9a0a","name":"Scorekeep","start_time":1478293361.271,"end_time":1478293361.449}"#,
467            serde_json::to_string(&Segment {
468                name: "Scorekeep".into(),
469                id: SegmentId::Rendered("70de5b6f19ff9a0a".into()),
470                start_time: Seconds(1_478_293_361.271),
471                trace_id: TraceId::Rendered("1-581cf771-a006649127e371903a2de979".into()),
472                end_time: Some(Seconds(1_478_293_361.449)),
473                ..Segment::default()
474            })
475            .expect("failed to serialize")
476        )
477    }
478}