CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-prometheus--simpleclient

Core instrumentation library for the Prometheus Java client, providing fundamental metric types for application monitoring

Pending
Overview
Eval results
Files

enumeration.mddocs/

Enumeration Metrics

Enumeration metrics track which of a predefined set of states something is in, perfect for status tracking, state machines, and categorical data. Only one state can be active at a time, with the active state having a value of 1 and all others having a value of 0.

Capabilities

Enumeration Creation

Create enumeration metrics using the builder pattern with predefined states.

/**
 * Create a new Enumeration builder
 * @return Builder instance for configuration
 */
public static Enumeration.Builder build();

/**
 * Create a new Enumeration builder with required fields
 * @param name The metric name
 * @param help The help text describing the enumeration
 * @return Builder instance for configuration
 */
public static Enumeration.Builder build(String name, String help);

Usage Example:

import io.prometheus.client.Enumeration;

// Service status enumeration
Enumeration serviceStatus = Enumeration.build()
    .name("service_status")
    .help("Current service status")
    .states("starting", "running", "stopping", "stopped")
    .register();

// Task state with labels
Enumeration taskState = Enumeration.build()
    .name("task_state")
    .help("Current state of background tasks")
    .labelNames("task_type", "task_id")
    .states("pending", "running", "completed", "failed")
    .register();

Enumeration Builder Configuration

Configure enumeration states using string arrays or Java enums.

public static class Builder extends SimpleCollector.Builder<Builder, Enumeration> {
    /**
     * Define possible states as string array
     * @param states Array of state names (first state is default)
     * @return Builder for method chaining
     * @throws IllegalArgumentException if no states provided
     */
    public Builder states(String... states);
    
    /**
     * Define possible states using Java enum class
     * @param enumClass Enum class defining the states
     * @return Builder for method chaining
     */
    public Builder states(Class<? extends Enum<?>> enumClass);
}

Usage Examples:

// String-based states
Enumeration connectionStatus = Enumeration.build()
    .name("connection_status")
    .help("Database connection status")
    .states("disconnected", "connecting", "connected", "error")
    .register();

// Enum-based states
public enum ProcessingPhase {
    INITIALIZING,
    PROCESSING,
    VALIDATING, 
    COMPLETED,
    FAILED
}

Enumeration processingPhase = Enumeration.build()
    .name("processing_phase")
    .help("Current processing phase")
    .states(ProcessingPhase.class)
    .register();

// With labels for multiple instances
Enumeration workerStatus = Enumeration.build()
    .name("worker_status")
    .help("Worker thread status")
    .labelNames("worker_id", "worker_type")
    .states("idle", "busy", "blocked", "terminated")
    .register();

Enumeration State Operations

Set the current state using string values or enum instances.

/**
 * Set the current state using string value
 * @param state State name (must be one of the predefined states)
 * @throws IllegalArgumentException if state not in predefined set
 */
public void state(String state);

/**
 * Set the current state using enum value
 * @param state Enum value corresponding to the state
 * @throws IllegalArgumentException if enum not recognized
 */
public void state(Enum<?> state);

Usage Examples:

// String state transitions
serviceStatus.state("starting");
// ... service initialization logic ...
serviceStatus.state("running");
// ... during shutdown ...
serviceStatus.state("stopping");
serviceStatus.state("stopped");

// Enum state transitions  
processingPhase.state(ProcessingPhase.INITIALIZING);
processingPhase.state(ProcessingPhase.PROCESSING);
processingPhase.state(ProcessingPhase.COMPLETED);

// Error handling
try {
    processingPhase.state(ProcessingPhase.PROCESSING);
    // Processing logic that might fail
    processingData();
    processingPhase.state(ProcessingPhase.COMPLETED);
} catch (Exception e) {
    processingPhase.state(ProcessingPhase.FAILED);
    throw e;
}

Labeled Enumeration Operations

Work with multi-dimensional enumerations using label values.

/**
 * Get enumeration child for specific label values
 * @param labelValues Values for each label name (must match count)
 * @return Enumeration.Child instance for the label combination
 * @throws IllegalArgumentException if wrong number of labels
 */
public Enumeration.Child labels(String... labelValues);

/**
 * Remove enumeration child for specific label values
 * @param labelValues Values identifying the child to remove
 */
public void remove(String... labelValues);

/**
 * Remove all enumeration children
 */
public void clear();

Enumeration Child Operations

Enumeration.Child provides state operations for labeled instances.

public static class Child {
    /**
     * Set current state for this child using string value
     * @param state State name from predefined set
     */
    public void state(String state);
    
    /**
     * Set current state for this child using enum value
     * @param state Enum value from predefined set
     */
    public void state(Enum<?> state);
}

Usage Example:

// Background task management
public enum TaskState {
    PENDING, RUNNING, COMPLETED, FAILED, CANCELLED
}

Enumeration backgroundTasks = Enumeration.build()
    .name("background_task_state")
    .help("State of background tasks")
    .labelNames("task_type", "user_id")
    .states(TaskState.class)
    .register();

// Track different tasks for different users
Enumeration.Child emailTask = backgroundTasks.labels("email_send", "user123");
Enumeration.Child reportTask = backgroundTasks.labels("report_generate", "user456");

// Task lifecycle management
emailTask.state(TaskState.PENDING);
reportTask.state(TaskState.PENDING);

// Start processing
emailTask.state(TaskState.RUNNING);
try {
    sendEmailToUser("user123");
    emailTask.state(TaskState.COMPLETED);
} catch (Exception e) {
    emailTask.state(TaskState.FAILED);
}

// Report generation
reportTask.state(TaskState.RUNNING);
if (shouldCancelReport()) {
    reportTask.state(TaskState.CANCELLED);
} else {
    generateReport("user456");
    reportTask.state(TaskState.COMPLETED);
}

Important Notes

Default State Behavior

  • The first state in the states array becomes the default initial state
  • When an enumeration is created, it starts in the first defined state
  • All enumeration instances for the same metric definition share the same state set
Enumeration status = Enumeration.build()
    .name("service_state") 
    .help("Service state")
    .states("initializing", "ready", "error") // "initializing" is default
    .register();

// Starts in "initializing" state automatically
// status.state("initializing") is implicit

State Validation

Enumeration metrics validate state names and enum values:

Enumeration validatedStatus = Enumeration.build()
    .name("validated_status")
    .help("Validated status enumeration")
    .states("active", "inactive", "maintenance")
    .register();

// Valid state changes
validatedStatus.state("active");     // OK
validatedStatus.state("inactive");   // OK

// Invalid state - throws IllegalArgumentException
try {
    validatedStatus.state("unknown"); // Throws exception
} catch (IllegalArgumentException e) {
    // Handle invalid state
}

Thread Safety

All enumeration operations are thread-safe:

// Safe concurrent state changes
Enumeration threadSafeEnum = Enumeration.build()
    .name("concurrent_state")
    .help("Thread-safe enumeration")
    .states("state1", "state2", "state3")
    .register();

// Multiple threads can safely change state
threadSafeEnum.state("state1"); // Thread 1
threadSafeEnum.state("state2"); // Thread 2

Common Use Cases

// Application lifecycle
public enum AppLifecycle {
    STARTING, HEALTHY, DEGRADED, UNHEALTHY, SHUTTING_DOWN
}

Enumeration appStatus = Enumeration.build()
    .name("application_status")
    .help("Application health status")
    .states(AppLifecycle.class)
    .register();

// Health check updates
public void updateHealthStatus() {
    if (isHealthy()) {
        appStatus.state(AppLifecycle.HEALTHY);
    } else if (isDegraded()) {
        appStatus.state(AppLifecycle.DEGRADED);
    } else {
        appStatus.state(AppLifecycle.UNHEALTHY);
    }
}

// HTTP connection states
Enumeration httpConnections = Enumeration.build()
    .name("http_connection_state")
    .help("HTTP connection state by endpoint")
    .labelNames("endpoint", "method")
    .states("idle", "active", "waiting", "closed", "error")
    .register();

// Connection management
public void handleHttpRequest(String endpoint, String method) {
    Enumeration.Child connection = httpConnections.labels(endpoint, method);
    
    connection.state("active");
    try {
        processRequest();
        connection.state("idle");
    } catch (TimeoutException e) {
        connection.state("waiting");
    } catch (Exception e) {
        connection.state("error");
    }
}

// Job queue status
public enum JobStatus {
    QUEUED, PROCESSING, RETRYING, COMPLETED, FAILED
}

Enumeration jobQueue = Enumeration.build()
    .name("job_status")
    .help("Job processing status")
    .labelNames("job_type", "priority")
    .states(JobStatus.class)
    .register();

// Job processing workflow
public void processJob(String jobType, String priority) {
    Enumeration.Child job = jobQueue.labels(jobType, priority);
    
    job.state(JobStatus.QUEUED);
    job.state(JobStatus.PROCESSING);
    
    try {
        executeJob();
        job.state(JobStatus.COMPLETED);
    } catch (RetryableException e) {
        job.state(JobStatus.RETRYING);
        scheduleRetry();
    } catch (Exception e) {
        job.state(JobStatus.FAILED);
        logFailure(e);
    }
}

Performance Considerations

  • Enumeration metrics are lightweight with minimal memory overhead
  • State changes are atomic operations
  • Use labels carefully to avoid high cardinality issues
  • State validation happens at runtime, so invalid states fail fast

Integration with Alerting

Enumeration metrics are excellent for alerting:

// Alert when services are not in healthy states
Enumeration serviceHealth = Enumeration.build()
    .name("service_health")
    .help("Service health status")
    .labelNames("service_name")
    .states("healthy", "degraded", "critical", "down")
    .register();

// Prometheus alerting rule example:
// service_health{state="critical"} == 1 OR service_health{state="down"} == 1

Install with Tessl CLI

npx tessl i tessl/maven-io-prometheus--simpleclient

docs

counter.md

enumeration.md

exemplars.md

gauge.md

histogram.md

index.md

info.md

registry.md

summary.md

tile.json