Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All significant changes to this project will be documented in this file.

## Unreleased

### New features

* Add `kv::lazy` (`kv::ValueLazy`) and `kv::serde` (behind the `serde` feature) in `logforth-core` and `logforth` to defer computing and memoize structured fields and formatted payload values on first inspection.

## v0.31.0

| Crate | Version |
Expand Down
2 changes: 1 addition & 1 deletion core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fn build_json_logger() -> Result<Logger, logforth_core::Error> {

`logforth-core` enables no features by default:

- `serde`: adds `ValueOwned::from_serde`, `ValueOwned::try_from_serde`, and `kv::ValueSerde` to capture `serde::Serialize` values as `ValueOwned` snapshots or lazy structured fields, and implements `serde::Serialize` across `kv` types.
- `serde`: adds `ValueOwned::from_serde`, `ValueOwned::try_from_serde`, `kv::serde`, and `kv::ValueSerde` to capture `serde::Serialize` values as `ValueOwned` snapshots or lazy structured fields, and implements `serde::Serialize` across `kv` types.

## Documentation

Expand Down
75 changes: 47 additions & 28 deletions core/src/kv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@
//! - **Owned snapshots** ([`KeyOwned`], [`ValueOwned`]) carry `'static + Send + Sync` structured
//! trees across thread boundaries and diagnostic scopes.
//!
//! With the `serde` feature enabled, [`ValueOwned::from_serde`] and [`ValueOwned::try_from_serde`]
//! eagerly capture [`ValueOwned`] snapshots, while [`ValueSerde`] initializes structured fields
//! lazily. Key-value carriers and views implement `serde::Serialize`.
//! [`lazy`] wraps a closure in a [`ValueLazy`] for fields or message arguments that are expensive
//! to compute.
#![cfg_attr(
feature = "serde",
doc = "
With the `serde` feature, [`serde()`] creates a [`ValueSerde`] that serializes on first access.
[`ValueOwned::from_serde`] and [`ValueOwned::try_from_serde`] capture snapshots immediately.
Key-value carriers and views implement `serde::Serialize`."
)]
//!
//! Iteration over [`KeyValues`] and [`MapValue`] preserves insertion order, while point lookups via
//! [`KeyValues::get`] and [`MapValue::get`] resolve duplicate keys using last-entry-wins order.
Expand All @@ -44,10 +50,16 @@ use std::sync::Arc;
use crate::Error;
use crate::str::RefStr;

mod value_lazy;
pub use self::value_lazy::ValueLazy;
pub use self::value_lazy::lazy;

#[cfg(feature = "serde")]
mod value_serde;
#[cfg(feature = "serde")]
pub use self::value_serde::ValueSerde;
#[cfg(feature = "serde")]
pub use self::value_serde::serde;

/// A visitor that walks structured key-value pairs.
///
Expand Down Expand Up @@ -81,8 +93,8 @@ impl fmt::Display for Key<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for Key<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for Key<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
Expand Down Expand Up @@ -180,8 +192,8 @@ impl fmt::Display for KeyOwned {
}

#[cfg(feature = "serde")]
impl serde::Serialize for KeyOwned {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for KeyOwned {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
Expand Down Expand Up @@ -226,8 +238,8 @@ impl fmt::Display for KeyView<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for KeyView<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for KeyView<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
Expand Down Expand Up @@ -278,8 +290,8 @@ impl fmt::Display for DebugValue<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for DebugValue<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for DebugValue<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
Expand Down Expand Up @@ -308,8 +320,8 @@ impl fmt::Display for DisplayValue<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for DisplayValue<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for DisplayValue<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
Expand Down Expand Up @@ -345,8 +357,8 @@ impl fmt::Debug for ListValue<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for ListValue<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for ListValue<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
Expand Down Expand Up @@ -442,8 +454,8 @@ impl fmt::Debug for MapValue<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for MapValue<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for MapValue<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.serialize(serializer)
}
}
Expand Down Expand Up @@ -558,8 +570,8 @@ impl fmt::Debug for ValueState<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for Value<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for Value<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.view().serialize(serializer)
}
}
Expand Down Expand Up @@ -680,7 +692,11 @@ impl<'a> Value<'a> {
/// Creates a value borrowing a lazily initialized [`ValueOwned`].
///
/// Inspection dereferences the source, which can be any `Deref<Target = ValueOwned> + Sync`
/// type such as `std::sync::LazyLock<ValueOwned, F>`.
/// type, including the [`ValueLazy`] returned by [`lazy`] with a `Send` initializer.
#[cfg_attr(
feature = "serde",
doc = "For serializable `Sync` values, [`serde()`] provides a [`ValueSerde`] source."
)]
///
/// # Examples
///
Expand All @@ -704,8 +720,11 @@ impl<'a> Value<'a> {
/// Native logging macros use this trait to borrow the value in a field such as `["key" = value]`.
/// Custom types can expose a scalar with [`Value::str`] or [`Value::u64`], borrow a snapshot with
/// [`Value::owned`] or [`Value::lazy_owned`], or defer formatting with [`Value::debug`] or
/// [`Value::display`]. With the `serde` feature, `kv::ValueSerde` provides this trait for a
/// borrowed `serde::Serialize + Sync` value.
/// [`Value::display`]. [`lazy`] creates a [`ValueLazy`] field from a `Send` initializer.
#[cfg_attr(
feature = "serde",
doc = "[`serde()`] creates a [`ValueSerde`] field from a borrowed `serde::Serialize + Sync` value."
)]
///
/// Capturing a string through [`LogValue::log_value`] ties its borrow to `&self` and yields
/// [`ValueView::BorrowedStr`]. Pass [`Value::static_str`] explicitly to preserve a string's
Expand Down Expand Up @@ -959,8 +978,8 @@ impl<T: Into<ValueOwned>> From<Option<T>> for ValueOwned {
}

#[cfg(feature = "serde")]
impl serde::Serialize for ValueOwned {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for ValueOwned {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.view().serialize(serializer)
}
}
Expand Down Expand Up @@ -1130,8 +1149,8 @@ impl fmt::Display for ValueView<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for ValueView<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for ValueView<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match &self {
ValueView::None => serializer.serialize_none(),
ValueView::BorrowedStr(v) => serializer.serialize_str(v),
Expand Down Expand Up @@ -1340,8 +1359,8 @@ impl fmt::Debug for KeyValues<'_> {
}

#[cfg(feature = "serde")]
impl serde::Serialize for KeyValues<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
impl ::serde::Serialize for KeyValues<'_> {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(self.iter())
}
}
Expand Down
142 changes: 142 additions & 0 deletions core/src/kv/value_lazy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Copyright 2024 FastLabs Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt;
use std::ops::Deref;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;

use crate::kv::LogValue;
use crate::kv::Value;
use crate::kv::ValueOwned;

/// A lazily initialized, owned log value shared by all readers of the wrapper.
///
/// The first dereference or display computes the value. Subsequent reads reuse it.
/// Debug formatting shows the cached value or `<uninitialized>` without running the closure.
/// With a `Send` initializer, the wrapper also implements [`LogValue`] for structured fields.
///
/// # Panics
///
/// If initialization panics, each subsequent dereference or display also panics.
///
/// # Examples
///
/// ```
/// use logforth_core::kv::ValueLazy;
///
/// let field = ValueLazy::new(|| String::from("ready"));
/// assert_eq!(field.to_string(), "ready");
/// assert_eq!(field.view().to_str(), Some("ready"));
/// ```
pub struct ValueLazy<F> {
init: Mutex<Option<F>>,
cache: OnceLock<ValueOwned>,
}

impl<F> ValueLazy<F> {
/// Creates a value that runs `init` at most once, on first access.
///
/// # Examples
///
/// ```
/// use logforth_core::kv::ValueLazy;
///
/// let attempts = ValueLazy::new(|| 3_u64);
/// assert_eq!(attempts.view().to_u64(), Some(3));
/// ```
pub const fn new<T>(init: F) -> Self
where
F: FnOnce() -> T,
T: Into<ValueOwned>,
{
Self {
init: Mutex::new(Some(init)),
cache: OnceLock::new(),
}
}
}

/// Defers computing a structured field or message argument until its value is needed.
///
/// Each dispatch that reads the value shares the result of the first initialization.
/// See [`ValueLazy`] for behavior if initialization panics.
///
/// # Examples
///
/// ```
/// use logforth_core::kv;
///
/// let elapsed = kv::lazy(|| 42_u64);
/// assert_eq!(format!("{elapsed} ms"), "42 ms");
/// ```
pub const fn lazy<T, F>(init: F) -> ValueLazy<F>
where
F: FnOnce() -> T,
T: Into<ValueOwned>,
{
ValueLazy::new(init)
}

impl<T, F> Deref for ValueLazy<F>
where
F: FnOnce() -> T,
T: Into<ValueOwned>,
{
type Target = ValueOwned;

fn deref(&self) -> &Self::Target {
self.cache.get_or_init(|| {
let init = self
.init
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
.expect("ValueLazy instance has previously been poisoned");
init().into()
})
}
}

impl<F> fmt::Debug for ValueLazy<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("ValueLazy");
match self.cache.get() {
Some(value) => debug.field("value", value),
None => debug.field("value", &format_args!("<uninitialized>")),
}
.finish()
}
}

impl<T, F> fmt::Display for ValueLazy<F>
where
F: FnOnce() -> T,
T: Into<ValueOwned>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.view(), f)
}
}

impl<T, F> LogValue for ValueLazy<F>
where
F: FnOnce() -> T + Send,
T: Into<ValueOwned>,
{
fn log_value(&self) -> Value<'_> {
Value::lazy_owned(self)
}
}
Loading
Loading