Skip to content

Commit

Permalink
ref(api): Use EnvelopesApi instead of the sentry-core client (#2081)
Browse files Browse the repository at this point in the history
Use sentry-cli's envelopes client, `EnvelopesApi`, instead of sentry-cores's `Client` method `send_envelope`. This change enables debug logging and non-zero exit codes for transmission failures like the other commands.
  • Loading branch information
elramen authored Jun 4, 2024
1 parent 9e0ae85 commit 787a388
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 56 deletions.
29 changes: 9 additions & 20 deletions src/commands/monitors/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ use std::process;
use std::time::{Duration, Instant};
use uuid::Uuid;

use anyhow::{Context, Result};
use anyhow::Result;
use clap::{Arg, ArgMatches, Command};
use console::style;

use sentry::protocol::{MonitorCheckIn, MonitorCheckInStatus, MonitorConfig, MonitorSchedule};
use sentry::types::Dsn;

use crate::config::Config;
use crate::utils::event::with_sentry_client;
use crate::api::envelopes_api::EnvelopesApi;
use crate::utils::system::QuietExit;

pub fn make_command(command: Command) -> Command {
Expand Down Expand Up @@ -124,13 +122,12 @@ fn run_program(args: Vec<&String>, monitor_slug: &str) -> (bool, Option<i32>, Du
(success, code, elapsed)
}

fn dsn_execute(
dsn: Dsn,
fn execute_checkin(
args: Vec<&String>,
monitor_slug: &str,
environment: &str,
monitor_config: Option<MonitorConfig>,
) -> (bool, Option<i32>) {
) -> Result<(bool, Option<i32>)> {
let check_in_id = Uuid::new_v4();

let open_checkin = MonitorCheckIn {
Expand All @@ -142,7 +139,8 @@ fn dsn_execute(
monitor_config,
};

with_sentry_client(dsn.clone(), |c| c.send_envelope(open_checkin.into()));
let envelopes_api = EnvelopesApi::try_new()?;
envelopes_api.send_envelope(open_checkin.into())?;

let (success, code, elapsed) = run_program(args, monitor_slug);

Expand All @@ -163,9 +161,8 @@ fn dsn_execute(
monitor_config: None,
};

with_sentry_client(dsn, |c| c.send_envelope(close_checkin.into()));

(success, code)
envelopes_api.send_envelope(close_checkin.into())?;
Ok((success, code))
}

fn parse_monitor_config_args(matches: &ArgMatches) -> Result<Option<MonitorConfig>> {
Expand All @@ -184,20 +181,12 @@ fn parse_monitor_config_args(matches: &ArgMatches) -> Result<Option<MonitorConfi
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
let config = Config::current();

// Token based auth has been removed, prefer DSN style auth for monitor checkins
let dsn = config.get_dsn().ok().context(
"Token auth is no longer supported for cron monitor checkins. Please use DSN auth.\n\
See: https://docs.sentry.io/product/crons/getting-started/cli/#configuration",
)?;

let args: Vec<_> = matches.get_many::<String>("args").unwrap().collect();
let monitor_slug = matches.get_one::<String>("monitor_slug").unwrap();
let environment = matches.get_one::<String>("environment").unwrap();
let monitor_config = parse_monitor_config_args(matches)?;

let (success, code) = dsn_execute(dsn, args, monitor_slug, environment, monitor_config);
let (success, code) = execute_checkin(args, monitor_slug, environment, monitor_config)?;

if !success {
return Err(QuietExit(code.unwrap_or(1)).into());
Expand Down
15 changes: 3 additions & 12 deletions src/commands/send_envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ use std::path::PathBuf;
use anyhow::Result;
use clap::{Arg, ArgAction, ArgMatches, Command};
use glob::{glob_with, MatchOptions};
use log::{debug, warn};
use sentry::types::Dsn;
use log::warn;
use sentry::Envelope;

use crate::config::Config;
use crate::utils::event::with_sentry_client;
use crate::api::envelopes_api::EnvelopesApi;

pub fn make_command(command: Command) -> Command {
command
Expand All @@ -34,14 +32,7 @@ pub fn make_command(command: Command) -> Command {
)
}

pub fn send_raw_envelope(envelope: Envelope, dsn: Dsn) {
debug!("{:?}", envelope);
with_sentry_client(dsn, |c| c.send_envelope(envelope));
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
let config = Config::current();
let dsn = config.get_dsn()?;
let raw = matches.get_flag("raw");

let path = matches.get_one::<String>("path").unwrap();
Expand All @@ -63,7 +54,7 @@ pub fn execute(matches: &ArgMatches) -> Result<()> {
} else {
Envelope::from_path(p)
}?;
send_raw_envelope(envelope, dsn.clone());
EnvelopesApi::try_new()?.send_envelope(envelope)?;
println!("Envelope from file {} dispatched", p.display());
}

Expand Down
4 changes: 2 additions & 2 deletions src/commands/send_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use sentry::Envelope;
use serde_json::Value;
use username::get_user_name;

use crate::commands::send_envelope::send_raw_envelope;
use crate::api::envelopes_api::EnvelopesApi;
use crate::config::Config;
use crate::utils::args::{get_timestamp, validate_distribution};
use crate::utils::event::{attach_logfile, get_sdk_info, with_sentry_client};
Expand Down Expand Up @@ -200,7 +200,7 @@ pub fn execute(matches: &ArgMatches) -> Result<()> {
writeln!(buf, r#"{{"type":"event","length":{}}}"#, raw_event.len())?;
buf.extend(raw_event);
let envelope = Envelope::from_bytes_raw(buf)?;
send_raw_envelope(envelope, dsn.clone());
EnvelopesApi::try_new()?.send_envelope(envelope)?;
id
} else {
let event: Event = serde_json::from_slice(&raw_event)?;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
```
$ sentry-cli monitors run foo-monitor -- cmd.exe /C echo 123
? failed
error: Token auth is no longer supported for cron monitor checkins. Please use DSN auth.
See: https://docs.sentry.io/product/crons/getting-started/cli/#configuration
error: DSN missing. Please set the `SENTRY_DSN` environment variable to your project's DSN.

Add --log-level=[info|debug] or export SENTRY_LOG_LEVEL=[info|debug] to see more output.
Please attach the full debug log to all bug reports.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
```
$ sentry-cli monitors run foo-monitor -- echo 123
? failed
error: Token auth is no longer supported for cron monitor checkins. Please use DSN auth.
See: https://docs.sentry.io/product/crons/getting-started/cli/#configuration
error: DSN missing. Please set the `SENTRY_DSN` environment variable to your project's DSN.

Add --log-level=[info|debug] or export SENTRY_LOG_LEVEL=[info|debug] to see more output.
Please attach the full debug log to all bug reports.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@ $ sentry-cli send-envelope tests/integration/_fixtures/envelope.dat --log-level=
INFO [..] Loaded config from [CWD]/.sentryclirc
DEBUG [..] sentry-cli version: [VERSION], platform: [..], architecture: [..]
INFO [..] sentry-cli was invoked with the following command line: "[CWD]/target/debug/sentry-cli[EXE]" "send-envelope" "tests/integration/_fixtures/envelope.dat" "--log-level=debug"
DEBUG [..] Envelope { event_id: Some([..]), items: EnvelopeItems([Event(Event { event_id: [..], level: Error, fingerprint: ["{{ default }}"], culprit: None, transaction: None, message: None, logentry: None, logger: None, modules: {}, platform: "other", timestamp: [..], server_name: None, release: None, dist: None, environment: None, user: None, request: None, contexts: {}, breadcrumbs: Values { values: [] }, exception: Values { values: [] }, stacktrace: None, template: None, threads: Values { values: [] }, tags: {}, extra: {}, debug_meta: DebugMeta { sdk_info: None, images: [] }, sdk: None }), Transaction(Transaction { event_id: 22d00b3f-d1b1-4b5d-8d20-49d138cd8a9d, name: None, release: None, environment: None, user: None, tags: {}, extra: {}, sdk: None, platform: "other", timestamp: None, start_timestamp: [..], spans: [Span { span_id: SpanId([212, 44, 238, 159, 195, 231, 79, 92]), trace_id: TraceId([51, 94, 83, 214, 20, 71, 74, 204, 159, 137, 230, 50, 183, 118, 204, 40]), parent_span_id: None, same_process_as_parent: None, op: None, description: None, timestamp: None, start_timestamp: [..], status: None, tags: {}, data: {} }], contexts: {}, request: None }), SessionUpdate(SessionUpdate { session_id: [..], distinct_id: Some("foo@bar.baz"), sequence: None, timestamp: None, started: [..], init: true, duration: Some(1.234), status: Ok, errors: 123, attributes: SessionAttributes { release: "foo-bar@1.2.3", environment: Some("production"), ip_address: None, user_agent: None } }), Attachment(Attachment { buffer: 12, filename: "file.txt", content_type: Some("application/octet-stream"), type: Some(Attachment) })]) }
Envelope from file tests/integration/_fixtures/envelope.dat dispatched
DEBUG [..] Sending envelope:
{"event_id":"22d00b3f-d1b1-4b5d-8d20-49d138cd8a9c"}
{"type":"event","length":74}
{"event_id":"22d00b3fd1b14b5d8d2049d138cd8a9c","timestamp":[..]}
{"type":"transaction","length":200}
{"event_id":"22d00b3fd1b14b5d8d2049d138cd8a9d","start_timestamp":[..],"spans":[{"span_id":"d42cee9fc3e74f5c","trace_id":"335e53d614474acc9f89e632b776cc28","start_timestamp":[..]}]}
{"type":"session","length":222}
{"sid":"22d00b3f-d1b1-4b5d-8d20-49d138cd8a9c","did":"foo@bar.baz","started":"2020-07-20T14:51:14.296Z","init":true,"duration":1.234,"status":"ok","errors":123,"attrs":{"release":"foo-bar@1.2.3","environment":"production"}}
{"type":"attachment","length":12,"filename":"file.txt","attachment_type":"event.attachment","content_type":"application/octet-stream"}
some content
...

```
2 changes: 1 addition & 1 deletion tests/integration/_fixtures/event.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
"dist": "my-dist",
"environment": "production",
"message": "hello there"
}
}
29 changes: 19 additions & 10 deletions tests/integration/monitors/run.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,52 @@
use crate::integration::{mock_endpoint, register_test, EndpointOptions};
use crate::integration::{self, EndpointOptions};

#[test]
fn command_monitors_run() {
let _server =
integration::mock_endpoint(EndpointOptions::new("POST", "/api/1337/envelope/", 200));
if cfg!(windows) {
register_test("monitors/monitors-run-win.trycmd");
integration::register_test("monitors/monitors-run-win.trycmd");
} else {
register_test("monitors/monitors-run.trycmd");
integration::register_test("monitors/monitors-run.trycmd");
}
}

#[test]
fn command_monitors_run_token_auth() {
let _server = mock_endpoint(
let _server = integration::mock_endpoint(
EndpointOptions::new("POST", "/api/0/monitors/foo-monitor/checkins/", 200)
.with_response_file("monitors/post-monitors.json"),
);
if cfg!(windows) {
register_test("monitors/monitors-run-token-auth-win.trycmd").env("SENTRY_DSN", "");
integration::register_test("monitors/monitors-run-token-auth-win.trycmd")
.env("SENTRY_DSN", "");
} else {
register_test("monitors/monitors-run-token-auth.trycmd").env("SENTRY_DSN", "");
integration::register_test("monitors/monitors-run-token-auth.trycmd").env("SENTRY_DSN", "");
}
}

#[test]
fn command_monitors_run_osenv() {
register_test("monitors/monitors-run-osenv.trycmd");
let _server =
integration::mock_endpoint(EndpointOptions::new("POST", "/api/1337/envelope/", 200));
integration::register_test("monitors/monitors-run-osenv.trycmd");
}

#[test]
fn command_monitors_run_environment() {
register_test("monitors/monitors-run-environment.trycmd");
let _server =
integration::mock_endpoint(EndpointOptions::new("POST", "/api/1337/envelope/", 200));
integration::register_test("monitors/monitors-run-environment.trycmd");
}

#[test]
fn command_monitors_run_environment_long() {
register_test("monitors/monitors-run-environment-long.trycmd");
let _server =
integration::mock_endpoint(EndpointOptions::new("POST", "/api/1337/envelope/", 200));
integration::register_test("monitors/monitors-run-environment-long.trycmd");
}

#[test]
fn command_monitors_run_help() {
register_test("monitors/monitors-run-help.trycmd");
integration::register_test("monitors/monitors-run-help.trycmd");
}
16 changes: 11 additions & 5 deletions tests/integration/send_envelope.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
use crate::integration::register_test;
use crate::integration;

use super::EndpointOptions;

#[test]
fn command_send_envelope_help() {
register_test("send_envelope/send_envelope-help.trycmd");
integration::register_test("send_envelope/send_envelope-help.trycmd");
}

#[test]
fn command_send_envelope_no_file() {
register_test("send_envelope/send_envelope-no-file.trycmd");
integration::register_test("send_envelope/send_envelope-no-file.trycmd");
}

#[test]
fn command_send_envelope_file() {
register_test("send_envelope/send_envelope-file.trycmd");
let _server =
integration::mock_endpoint(EndpointOptions::new("POST", "/api/1337/envelope/", 200));
integration::register_test("send_envelope/send_envelope-file.trycmd");
}

#[test]
fn command_send_envelope_with_logging() {
register_test("send_envelope/send_envelope-file-log.trycmd");
let _server =
integration::mock_endpoint(EndpointOptions::new("POST", "/api/1337/envelope/", 200));
integration::register_test("send_envelope/send_envelope-file-log.trycmd");
}

0 comments on commit 787a388

Please sign in to comment.