Skip to content

Commit

Permalink
Add missing_docs lint and supply documents. (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmjoy authored Sep 22, 2022
1 parent 7d344de commit 4c61a5b
Show file tree
Hide file tree
Showing 28 changed files with 225 additions and 35 deletions.
4 changes: 2 additions & 2 deletions e2e/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async fn handle_ping(
.await
.unwrap();
}
Ok(Response::new(Body::from("hoge")))
Ok(Response::new(Body::from("ok")))
}

async fn producer_response(
Expand Down Expand Up @@ -147,7 +147,7 @@ async fn handle_pong(_req: Request<Body>) -> Result<Response<Body>, Infallible>
.unwrap();
let mut context = tracer::create_trace_context();
let _span = context.create_entry_span_with_propagation("/pong", &ctx);
Ok(Response::new(Body::from("hoge")))
Ok(Response::new(Body::from("ok")))
}

async fn consumer_response(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
Expand Down
2 changes: 2 additions & 0 deletions src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
// limitations under the License.
//

//! Common utils.
pub mod random_generator;
pub(crate) mod system_time;
4 changes: 4 additions & 0 deletions src/common/random_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@
// limitations under the License.
//

//! Random id generator.
use uuid::Uuid;

/// Random id generator.
pub struct RandomGenerator;

impl RandomGenerator {
/// Generate unique id as string.
pub fn generate() -> String {
Uuid::new_v4().as_u128().to_string()
}
Expand Down
2 changes: 2 additions & 0 deletions src/common/system_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

//! Get system time, as mills seconds.
use cfg_if::cfg_if;

pub(crate) enum TimePeriod {
Expand Down
8 changes: 8 additions & 0 deletions src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

//! Crate errors.
pub(crate) const LOCK_MSG: &str = "should not cross threads/coroutines (locked)";

/// Skywalking Result.
Expand All @@ -22,21 +24,27 @@ pub type Result<T> = std::result::Result<T, Error>;
/// Skywalking Error.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Decode propagation failed.
#[error("decode propagation failed: {0}")]
DecodePropagation(&'static str),

/// Reporter shutdown failed.
#[error("reporter shutdown failed: {0}")]
ReporterShutdown(String),

/// Tonic transport failed.
#[error("tonic transport failed: {0}")]
TonicTransport(#[from] tonic::transport::Error),

/// Tonic status error.
#[error("tonic status: {0}")]
TonicStatus(#[from] tonic::Status),

/// Tokio join failed.
#[error("tokio join failed: {0}")]
TokioJoin(#[from] tokio::task::JoinError),

/// Other uncovered errors.
#[error(transparent)]
Other(#[from] Box<dyn std::error::Error + Send + 'static>),
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
#![warn(rust_2018_idioms)]
#![warn(rust_2018_idioms, missing_docs)]
#![warn(clippy::dbg_macro, clippy::print_stdout)]
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]
Expand Down
12 changes: 9 additions & 3 deletions src/logging/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

//! Logger and global methods.
use super::record::LogRecord;
use crate::reporter::{CollectItem, DynReport, Report};
use std::sync::Arc;
Expand All @@ -24,26 +26,27 @@ static GLOBAL_LOGGER: OnceCell<Logger> = OnceCell::const_new();
/// Set the global logger.
pub fn set_global_logger(logger: Logger) {
if GLOBAL_LOGGER.set(logger).is_err() {
panic!("global logger has setted")
panic!("global logger has set")
}
}

/// Get the global logger.
pub fn global_logger() -> &'static Logger {
GLOBAL_LOGGER.get().expect("global logger haven't setted")
GLOBAL_LOGGER.get().expect("global logger haven't set")
}

/// Log by global logger.
pub fn log(record: LogRecord) {
global_logger().log(record);
}

pub struct Inner {
struct Inner {
service_name: String,
instance_name: String,
reporter: Box<DynReport>,
}

/// Logger handles skywalking logging operations, integrate with reporter.
#[derive(Clone)]
pub struct Logger {
inner: Arc<Inner>,
Expand All @@ -65,14 +68,17 @@ impl Logger {
}
}

/// Get service name.
pub fn service_name(&self) -> &str {
&self.inner.service_name
}

/// Get instance name.
pub fn instance_name(&self) -> &str {
&self.inner.instance_name
}

/// Do logging via reporter.
pub fn log(&self, record: LogRecord) {
let data = record.convert_to_log_data(
self.service_name().to_owned(),
Expand Down
2 changes: 2 additions & 0 deletions src/logging/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
// limitations under the License.
//

//! Skywalking logging api.
pub mod logger;
pub mod record;
23 changes: 22 additions & 1 deletion src/logging/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

//! Log record items.
use crate::{
common::system_time::{fetch_time, TimePeriod},
skywalking_proto::v3::{
Expand All @@ -24,9 +26,13 @@ use crate::{
};
use std::time::{SystemTime, UNIX_EPOCH};

/// Log record type of [LogRecord];
pub enum RecordType {
/// Text type.
Text,
/// Json type.
Json,
/// Yaml type.
Yaml,
}

Expand All @@ -36,6 +42,7 @@ impl Default for RecordType {
}
}

/// The builder of [LogData];
#[derive(Default)]
pub struct LogRecord {
time: Option<SystemTime>,
Expand All @@ -50,34 +57,43 @@ pub struct LogRecord {
}

impl LogRecord {
/// New default [LogRecord];
#[inline]
pub fn new() -> Self {
Default::default()
}

/// Use custom time rather than now time.
#[inline]
pub fn custome_time(mut self, time: SystemTime) -> Self {
pub fn custom_time(mut self, time: SystemTime) -> Self {
self.time = Some(time);
self
}

/// Not set the log time, OAP server would use the received timestamp as
/// log's timestamp, or relies on the OAP server analyzer.
#[inline]
pub fn ignore_time(mut self) -> Self {
self.is_ignore_time = true;
self
}

/// The logic name represents the endpoint, which logs belong.
#[inline]
pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = endpoint.into();
self
}

/// The available tags. OAP server could provide search/analysis
/// capabilities based on these.
pub fn add_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.tags.push((key.into(), value.into()));
self
}

/// The available tags. OAP server could provide search/analysis
/// capabilities based on these.
pub fn add_tags<K, V, I>(mut self, tags: I) -> Self
where
K: Into<String>,
Expand All @@ -89,22 +105,27 @@ impl LogRecord {
self
}

/// Logs with trace context.
pub fn with_tracing_context(mut self, tracing_context: &TracingContext) -> Self {
self.trace_id = Some(tracing_context.trace_id().to_owned());
self.trace_segment_id = Some(tracing_context.trace_segment_id().to_owned());
self
}

/// The span should be unique in the whole segment.
pub fn with_span(mut self, span: &Span) -> Self {
self.span_id = Some(span.with_span_object(|span| span.span_id));
self
}

/// A type to match analyzer(s) at the OAP server.
/// The data could be analyzed at the client side, but could be partial.
pub fn record_type(mut self, record_type: RecordType) -> Self {
self.record_type = record_type;
self
}

/// Log content.
pub fn content(mut self, content: impl Into<String>) -> Self {
self.content = content.into();
self
Expand Down
14 changes: 14 additions & 0 deletions src/management/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

//! Skywalking report instance properties items.
use crate::skywalking_proto::v3::{InstanceProperties, KeyStringValuePair};
use once_cell::sync::Lazy;
use std::{collections::HashMap, process};
Expand Down Expand Up @@ -58,39 +60,51 @@ const OS_NAME: Option<&str> = if cfg!(target_os = "linux") {
None
};

/// Builder of [InstanceProperties].
#[derive(Debug, Default)]
pub struct Properties {
inner: HashMap<String, Vec<String>>,
}

impl Properties {
/// Instance properties key of host name.
pub const KEY_HOST_NAME: &'static str = "hostname";
/// Instance properties key of ipv4.
pub const KEY_IPV4: &'static str = "ipv4";
/// Instance properties key of programming language.
pub const KEY_LANGUAGE: &'static str = "language";
/// Instance properties key of os name.
pub const KEY_OS_NAME: &'static str = "OS Name";
/// Instance properties key of process number.
pub const KEY_PROCESS_NO: &'static str = "Process No.";
}

impl Properties {
/// New empty properties.
#[inline]
pub fn new() -> Self {
Default::default()
}

/// Insert key value pair, will not overwrite the original, because multiple
/// values of the same key can exist.
pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.inner.entry(key.into()).or_default().push(value.into());
}

/// Overwrite the values, whether there are multiple.
pub fn update(&mut self, key: &str, value: impl Into<String>) {
if let Some(values) = self.inner.get_mut(key) {
*values = vec![value.into()];
}
}

/// Remove all values associated the key.
pub fn remove(&mut self, key: &str) {
self.inner.remove(key);
}

/// Insert the OS system info, such as os name, host name, etc.
pub fn insert_os_info(&mut self) {
for (key, value) in build_os_info() {
self.insert(key, value);
Expand Down
8 changes: 8 additions & 0 deletions src/management/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

//! Manager methods.
use super::instance::Properties;
use crate::reporter::{CollectItem, DynReport, Report};
use std::{
Expand All @@ -29,6 +31,7 @@ use tokio::{
time,
};

/// Manager handles skywalking management operations, integrate with reporter.
pub struct Manager {
service_name: String,
instance_name: String,
Expand All @@ -49,20 +52,24 @@ impl Manager {
}
}

/// Get service name.
pub fn service_name(&self) -> &str {
&self.service_name
}

/// Get instance name.
pub fn instance_name(&self) -> &str {
&self.instance_name
}

/// Report instance properties.
pub fn report_properties(&self, properties: Properties) {
let props = properties
.convert_to_instance_properties(self.service_name.clone(), self.instance_name.clone());
self.reporter.report(CollectItem::Instance(Box::new(props)));
}

/// Do keep alive (heartbeat), with the interval, will be run in background.
pub fn keep_alive(&self, interval: Duration) -> KeepAlive {
let service_name = self.service_name.clone();
let instance_name = self.instance_name.clone();
Expand All @@ -85,6 +92,7 @@ impl Manager {
}
}

/// Handle of [Manager::keep_alive].
pub struct KeepAlive {
handle: JoinHandle<()>,
}
Expand Down
2 changes: 2 additions & 0 deletions src/management/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
// limitations under the License.
//

//! Skywalking management api.
pub mod instance;
pub mod manager;
Loading

0 comments on commit 4c61a5b

Please sign in to comment.