Thread System 0.3.1
High-performance C++20 thread pool with work stealing and DAG scheduling
Loading...
Searching...
No Matches
kcenon::thread::callback_job Class Reference

A specialized job class that encapsulates user-defined callbacks. More...

#include <callback_job.h>

Inheritance diagram for kcenon::thread::callback_job:
Inheritance graph
Collaboration diagram for kcenon::thread::callback_job:
Collaboration graph

Public Member Functions

 callback_job (const std::function< std::optional< std::string >(void)> &callback, const std::string &name="callback_job")
 Constructs a new callback_job instance with a parameterless callback.
 
 callback_job (const std::function< common::VoidResult(void)> &callback, const std::string &name="callback_job")
 Constructs a new callback_job instance with a parameterless callback using modern error handling.
 
 callback_job (const std::function< std::optional< std::string >(const std::vector< uint8_t > &)> &data_callback, const std::vector< uint8_t > &data, const std::string &name="data_callback_job")
 Constructs a new callback_job instance with a data-based callback.
 
 callback_job (const std::function< common::VoidResult(const std::vector< uint8_t > &)> &data_callback, const std::vector< uint8_t > &data, const std::string &name="data_callback_job")
 Constructs a new callback_job instance with a data-based callback using modern error handling.
 
 ~callback_job (void) override
 Virtual destructor for proper cleanup in derived classes.
 
auto do_work (void) -> common::VoidResult override
 Executes the appropriate callback function to perform the job's work.
 
- Public Member Functions inherited from kcenon::thread::job
auto get_job_id () const -> std::uint64_t
 Gets the unique ID of this job.
 
auto get_enqueue_time () const -> std::chrono::steady_clock::time_point
 Gets the time when this job was created (enqueued).
 
 job (const std::string &name="job")
 Constructs a new job with an optional human-readable name.
 
 job (const std::vector< uint8_t > &data, const std::string &name="data_job")
 Constructs a new job with associated raw byte data and a name.
 
virtual ~job (void)
 Virtual destructor for the job class to allow proper cleanup in derived classes.
 
auto get_name (void) const -> std::string
 Retrieves the name of this job.
 
virtual auto set_cancellation_token (const cancellation_token &token) -> void
 Sets a cancellation token that can be used to cancel the job.
 
virtual auto get_cancellation_token () const -> cancellation_token
 Gets the cancellation token associated with this job.
 
virtual auto set_job_queue (const std::shared_ptr< job_queue > &job_queue) -> void
 Associates this job with a specific job_queue.
 
virtual auto get_job_queue (void) const -> std::shared_ptr< job_queue >
 Retrieves the job_queue associated with this job, if any.
 
virtual auto to_string (void) const -> std::string
 Provides a string representation of the job for logging or debugging.
 
auto with_on_complete (std::function< void(common::VoidResult)> callback) -> job &
 Attaches a completion callback to this job.
 
auto with_on_error (std::function< void(const common::error_info &)> callback) -> job &
 Attaches an error callback to this job.
 
auto with_priority (job_priority priority) -> job &
 Sets the priority level for this job.
 
auto with_cancellation (const cancellation_token &token) -> job &
 Attaches a cancellation token to this job via composition.
 
auto with_retry (const retry_policy &policy) -> job &
 Attaches a retry policy to this job.
 
auto with_timeout (std::chrono::milliseconds timeout) -> job &
 Sets a timeout for job execution.
 
auto get_priority () const -> job_priority
 Gets the priority level of this job.
 
auto get_retry_policy () const -> std::optional< retry_policy >
 Gets the retry policy of this job.
 
auto get_timeout () const -> std::optional< std::chrono::milliseconds >
 Gets the timeout duration for this job.
 
auto has_explicit_cancellation () const -> bool
 Checks if this job has an explicit cancellation set via composition.
 
auto has_components () const -> bool
 Checks if this job has any composed components.
 

Protected Attributes

std::function< common::VoidResult(void)> callback_
 Stores the user-defined callback that does not take any parameters.
 
std::function< common::VoidResult(const std::vector< uint8_t > &)> data_callback_
 Stores the user-defined callback that takes a std::vector<uint8_t>.
 
std::function< std::optional< std::string >(void)> old_callback_
 Compatibility layer for the old style callbacks.
 
std::function< std::optional< std::string >(const std::vector< uint8_t > &)> old_data_callback_
 
- Protected Attributes inherited from kcenon::thread::job
std::string name_
 The descriptive name of the job, used primarily for identification and logging.
 
std::vector< uint8_t > data_
 An optional container of raw byte data that may be used by the job.
 
std::weak_ptr< job_queuejob_queue_
 A weak reference to the job_queue that currently manages this job.
 
cancellation_token cancellation_token_
 The cancellation token associated with this job.
 

Additional Inherited Members

- Protected Member Functions inherited from kcenon::thread::job
auto invoke_callbacks (const common::VoidResult &result) -> void
 Invokes the completion callbacks if they are set.
 

Detailed Description

A specialized job class that encapsulates user-defined callbacks.

The callback_job class provides two main mechanisms for defining job behavior:

  • A callback that takes no parameters (callback_), for general-purpose tasks.
  • A callback that takes a std::vector<uint8_t> as a parameter (data_callback_), allowing you to pass raw data to the job when it is constructed.

Callbacks return common::VoidResult for success/error indication. Legacy callbacks returning std::optional<std::string> are also supported and automatically converted.

Note
For more advanced job composition (cancellation, retry, etc.), consider using job_builder instead.
See also
job_builder
Examples
crash_protection/main.cpp.

Definition at line 43 of file callback_job.h.

Constructor & Destructor Documentation

◆ callback_job() [1/4]

kcenon::thread::callback_job::callback_job ( const std::function< std::optional< std::string >(void)> & callback,
const std::string & name = "callback_job" )

Constructs a new callback_job instance with a parameterless callback.

Constructs a callback job with legacy error-returning callback.

Use this constructor if your job logic does not require any input data.

Parameters
callbackA function object that performs the job's work.
  • Returns std::nullopt on success.
  • Returns a std::string on failure.
nameAn optional name for this job (default is "callback_job").

Example:

[]() {
// Job logic...
return std::nullopt; // or std::string("Error message");
},
"my_named_job"
);
callback_job(const std::function< std::optional< std::string >(void)> &callback, const std::string &name="callback_job")
Constructs a new callback_job instance with a parameterless callback.

Implementation details:

  • Adapts legacy std::optional<std::string> error format to modern result_void
  • Wraps the provided callback in a lambda that performs error conversion
  • Sets data_callback_ to nullptr since this is not a data-based callback
  • Inherits job name from base job class for identification

Error Conversion:

  • std::nullopt (no error) -> successful result_void
  • std::string (error message) -> error with job_execution_failed code

Performance Considerations:

  • Single lambda capture by value (efficient for small callbacks)
  • No dynamic allocation for callback storage
  • Minimal overhead during execution
Parameters
callbackLegacy callback function returning optional error string
nameDescriptive name for this job (for debugging/logging)

Definition at line 47 of file callback_job.cpp.

49 : job(name), callback_([callback](void) -> common::VoidResult {
50 // Call the original callback and convert error format
51 auto result = callback();
52 if (result.has_value()) {
53 // Error occurred: convert string to error object
54 return common::error_info{static_cast<int>(error_code::job_execution_failed), result.value(), "thread_system"};
55 }
56 // Success: return empty result
57 return common::ok();
58 }), data_callback_(nullptr)
59 {
60 }
std::function< common::VoidResult(void)> callback_
Stores the user-defined callback that does not take any parameters.
std::function< common::VoidResult(const std::vector< uint8_t > &)> data_callback_
Stores the user-defined callback that takes a std::vector<uint8_t>.
job(const std::string &name="job")
Constructs a new job with an optional human-readable name.
Definition job.cpp:53
@ callback
Call user callback for custom decision.

◆ callback_job() [2/4]

kcenon::thread::callback_job::callback_job ( const std::function< common::VoidResult(void)> & callback,
const std::string & name = "callback_job" )

Constructs a new callback_job instance with a parameterless callback using modern error handling.

Constructs a callback job with modern result_void-returning callback.

Parameters
callbackA function object that performs the job's work.
  • Returns common::VoidResult on success or failure.
nameAn optional name for this job (default is "callback_job").

Implementation details:

  • Direct storage of modern callback without error conversion
  • More efficient than legacy version (no wrapper lambda)
  • Sets data_callback_ to nullptr since this is not a data-based callback
  • Preferred constructor for new code due to better error handling

Modern Error Handling:

  • Uses result_void type with rich error information
  • Supports error codes and detailed error messages
  • Better composability with other result-based APIs
Parameters
callbackModern callback function returning result_void
nameDescriptive name for this job (for debugging/logging)

Definition at line 79 of file callback_job.cpp.

82 : job(name), callback_(callback), data_callback_(nullptr)
83 {
84 }

References kcenon::thread::callback.

◆ callback_job() [3/4]

kcenon::thread::callback_job::callback_job ( const std::function< std::optional< std::string >(const std::vector< uint8_t > &)> & data_callback,
const std::vector< uint8_t > & data,
const std::string & name = "data_callback_job" )

Constructs a new callback_job instance with a data-based callback.

Constructs a data-based callback job with legacy error handling.

Use this constructor if your job logic requires raw byte data to process.

Parameters
data_callbackA function object that performs the job's work, taking a std::vector<uint8_t> as its input.
  • Returns std::nullopt on success.
  • Returns a std::string on failure.
dataA vector of bytes that will be passed to data_callback when the job is executed.
nameAn optional name for this job (default is "data_callback_job").

Example:

std::vector<uint8_t> payload = {0x01, 0x02, 0x03};
// A job that processes the 'payload'
[](const std::vector<uint8_t>& data) -> std::optional<std::string> {
if (data.empty()) {
return std::string{"No data provided"};
}
// Process 'data' here...
return std::nullopt; // success
},
payload,
"my_data_job"
);

Implementation details:

  • Stores binary data in base job class for later processing
  • Adapts legacy data callback to modern error handling
  • Sets regular callback_ to nullptr since this uses data processing
  • Wraps data callback in lambda for error format conversion

Data Processing:

  • Binary data is passed to callback during execution
  • Useful for jobs that need to process files, network data, etc.
  • Data is stored efficiently in the job object

Error Conversion:

  • Same conversion logic as parameterless legacy callback
  • Maintains backward compatibility with existing code
Parameters
data_callbackLegacy data-processing callback
dataBinary data to be processed by the callback
nameDescriptive name for this job

Definition at line 108 of file callback_job.cpp.

111 : job(data, name), callback_(nullptr), data_callback_([data_callback](const std::vector<uint8_t>& callback_data) -> common::VoidResult {
112 // Call the original data callback with provided data
113 auto result = data_callback(callback_data);
114 if (result.has_value()) {
115 // Error occurred: convert string to error object
116 return common::error_info{static_cast<int>(error_code::job_execution_failed), result.value(), "thread_system"};
117 }
118 // Success: return empty result
119 return common::ok();
120 })
121 {
122 }

◆ callback_job() [4/4]

kcenon::thread::callback_job::callback_job ( const std::function< common::VoidResult(const std::vector< uint8_t > &)> & data_callback,
const std::vector< uint8_t > & data,
const std::string & name = "data_callback_job" )

Constructs a new callback_job instance with a data-based callback using modern error handling.

Constructs a data-based callback job with modern error handling.

Parameters
data_callbackA function object that performs the job's work, taking a std::vector<uint8_t> as its input.
  • Returns common::VoidResult on success or failure.
dataA vector of bytes that will be passed to data_callback when the job is executed.
nameAn optional name for this job (default is "data_callback_job").

Implementation details:

  • Direct storage of modern data callback without conversion
  • Most efficient option for data-processing jobs
  • Sets regular callback_ to nullptr since this uses data processing
  • Preferred constructor for new data-processing code

Data Handling:

  • Efficiently stores data in base job class
  • Data is passed by const reference during execution
  • Supports large data sets without excessive copying
Parameters
data_callbackModern data-processing callback
dataBinary data to be processed by the callback
nameDescriptive name for this job

Definition at line 142 of file callback_job.cpp.

145 : job(data, name), callback_(nullptr), data_callback_(data_callback)
146 {
147 }

◆ ~callback_job()

kcenon::thread::callback_job::~callback_job ( void )
override

Virtual destructor for proper cleanup in derived classes.

Destroys the callback job.

Implementation details:

  • std::function destructors handle callback cleanup automatically
  • No manual cleanup required due to RAII design
  • Base job destructor handles data cleanup if present

Definition at line 157 of file callback_job.cpp.

157{}

Member Function Documentation

◆ do_work()

auto kcenon::thread::callback_job::do_work ( void ) -> common::VoidResult
nodiscardoverridevirtual

Executes the appropriate callback function to perform the job's work.

Executes the callback job by calling the appropriate callback function.

Returns
std::optional<std::string>
  • std::nullopt if the job completes successfully.
  • A non-empty std::string indicating an error message if the job fails.

This method is typically called by a job-processing mechanism (e.g., a thread pool) rather than directly by user code. However, manual invocation is possible if desired.

The logic internally checks which callback has been provided:

  • If data_callback_ is set, do_work() invokes it with the associated data.
  • Otherwise, it invokes the parameterless callback_.

Implementation details:

  • Uses priority-based callback selection for optimal performance
  • Data callbacks take precedence over regular callbacks
  • Falls back to base class implementation if no callbacks are set
  • Provides consistent error handling across all callback types

Execution Priority:

  1. Data callback (if data_callback_ is set)
  2. Regular callback (if callback_ is set)
  3. Base class do_work() (fallback for empty job)

Performance Considerations:

  • Minimal overhead for callback selection (simple pointer checks)
  • Direct function call without additional abstraction layers
  • No dynamic dispatch - compile-time type safety

Error Propagation:

  • Errors from callbacks are passed through unchanged
  • Modern callbacks return result_void directly
  • Legacy callbacks have errors converted automatically
Returns
Result of callback execution or base class implementation

Reimplemented from kcenon::thread::job.

Definition at line 185 of file callback_job.cpp.

186 {
187 // Priority 1: Data callback with stored binary data
188 if (data_callback_)
189 {
190 // Execute data-processing callback with job's stored data
191 return data_callback_(data_);
192 }
193 // Priority 2: Standard parameterless callback
194 else if (callback_)
195 {
196 // Execute standard callback function
197 return callback_();
198 }
199 // Priority 3: Fallback to base class implementation
200 else
201 {
202 // No callbacks set - delegate to base job class
203 // This typically returns a "not implemented" error
204 return job::do_work();
205 }
206 }
std::vector< uint8_t > data_
An optional container of raw byte data that may be used by the job.
Definition job.h:488
virtual auto do_work(void) -> common::VoidResult
The core task execution method to be overridden by derived classes.
Definition job.cpp:135

References kcenon::thread::job::do_work().

Here is the call graph for this function:

Member Data Documentation

◆ callback_

std::function<common::VoidResult(void)> kcenon::thread::callback_job::callback_
protected

Stores the user-defined callback that does not take any parameters.

This callback is only valid if the callback_job was constructed via the parameterless constructor. If this member is used, data_callback_ should be null.

Definition at line 159 of file callback_job.h.

◆ data_callback_

std::function<common::VoidResult(const std::vector<uint8_t>&)> kcenon::thread::callback_job::data_callback_
protected

Stores the user-defined callback that takes a std::vector<uint8_t>.

This callback is only valid if the callback_job was constructed via the data-based constructor. If this member is used, callback_ should be null.

Definition at line 167 of file callback_job.h.

◆ old_callback_

std::function<std::optional<std::string>(void)> kcenon::thread::callback_job::old_callback_
protected

Compatibility layer for the old style callbacks.

Definition at line 172 of file callback_job.h.

◆ old_data_callback_

std::function<std::optional<std::string>(const std::vector<uint8_t>&)> kcenon::thread::callback_job::old_data_callback_
protected

Definition at line 173 of file callback_job.h.


The documentation for this class was generated from the following files: