AWS-XRay
view release on metacpan or search on metacpan
lib/AWS/XRay.pm view on Meta::CPAN
our $CROAK_INVALID_NAME = 0;
my $VALID_NAME_REGEXP = qr/\A[\p{L}\p{N}\p{Z}_.:\/%&#=+\\\-@]{1,200}\z/;
if ($ENV{"AWS_XRAY_DAEMON_ADDRESS"}) {
($DAEMON_HOST, $DAEMON_PORT) = split /:/, $ENV{"AWS_XRAY_DAEMON_ADDRESS"};
}
my $Sock;
sub sampling_rate {
my $class = shift;
if (@_) {
$SAMPLING_RATE = shift;
}
$SAMPLING_RATE;
}
sub sampler {
my $class = shift;
if (@_) {
$SAMPLER = shift;
}
$SAMPLER;
}
sub plugins {
my $class = shift;
if (@_) {
@PLUGINS = @_;
Module::Load::load $_ for @PLUGINS;
}
@PLUGINS;
}
sub auto_flush {
my $class = shift;
if (@_) {
my $auto_flush = shift;
if ($auto_flush != $AUTO_FLUSH) {
$Sock->close if $Sock && $Sock->can("close");
undef $Sock; # regenerate
}
$AUTO_FLUSH = $auto_flush;
}
$AUTO_FLUSH;
}
sub sock {
$Sock //= AWS::XRay::Buffer->new(
IO::Socket::INET->new(
PeerAddr => $DAEMON_HOST || "127.0.0.1",
PeerPort => $DAEMON_PORT || 2000,
Proto => "udp",
),
$AUTO_FLUSH,
);
}
sub new_trace_id {
sprintf(
"1-%x-%s",
CORE::time(),
unpack("H*", Crypt::URandom::urandom(12)),
);
}
sub new_id {
unpack("H*", Crypt::URandom::urandom(8));
}
sub is_valid_name {
$_[0] =~ $VALID_NAME_REGEXP;
}
# alias for backward compatibility
*trace = \&capture;
sub capture {
my ($name, $code) = @_;
if (!is_valid_name($name)) {
my $msg = "invalid segment name: $name";
$CROAK_INVALID_NAME ? croak($msg) : carp($msg);
}
my $wantarray = wantarray;
my $enabled;
my $sampled = $SAMPLED;
if (defined $ENABLED) {
$enabled = $ENABLED ? 1 : 0; # fix true or false (not undef)
}
elsif ($TRACE_ID) {
$enabled = 0; # called from parent capture
}
else {
# root capture try sampling
$sampled = $SAMPLER->() ? 1 : 0;
$enabled = $sampled ? 1 : 0;
}
local $ENABLED = $enabled;
local $SAMPLED = $sampled;
return $code->(AWS::XRay::Segment->new) if !$enabled;
local $TRACE_ID = $TRACE_ID // new_trace_id();
my $segment = AWS::XRay::Segment->new({ name => $name });
unless (defined $segment->{type} && $segment->{type} eq "subsegment") {
$_->apply_plugin($segment) for @PLUGINS;
}
local $SEGMENT_ID = $segment->{id};
my @ret;
eval {
if ($wantarray) {
@ret = $code->($segment);
}
elsif (defined $wantarray) {
$ret[0] = $code->($segment);
}
( run in 0.698 second using v1.01-cache-2.11-cpan-13bb782fe5a )