0
# Enumeration Metrics
1
2
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.
3
4
## Capabilities
5
6
### Enumeration Creation
7
8
Create enumeration metrics using the builder pattern with predefined states.
9
10
```java { .api }
11
/**
12
* Create a new Enumeration builder
13
* @return Builder instance for configuration
14
*/
15
public static Enumeration.Builder build();
16
17
/**
18
* Create a new Enumeration builder with required fields
19
* @param name The metric name
20
* @param help The help text describing the enumeration
21
* @return Builder instance for configuration
22
*/
23
public static Enumeration.Builder build(String name, String help);
24
```
25
26
**Usage Example:**
27
28
```java
29
import io.prometheus.client.Enumeration;
30
31
// Service status enumeration
32
Enumeration serviceStatus = Enumeration.build()
33
.name("service_status")
34
.help("Current service status")
35
.states("starting", "running", "stopping", "stopped")
36
.register();
37
38
// Task state with labels
39
Enumeration taskState = Enumeration.build()
40
.name("task_state")
41
.help("Current state of background tasks")
42
.labelNames("task_type", "task_id")
43
.states("pending", "running", "completed", "failed")
44
.register();
45
```
46
47
### Enumeration Builder Configuration
48
49
Configure enumeration states using string arrays or Java enums.
50
51
```java { .api }
52
public static class Builder extends SimpleCollector.Builder<Builder, Enumeration> {
53
/**
54
* Define possible states as string array
55
* @param states Array of state names (first state is default)
56
* @return Builder for method chaining
57
* @throws IllegalArgumentException if no states provided
58
*/
59
public Builder states(String... states);
60
61
/**
62
* Define possible states using Java enum class
63
* @param enumClass Enum class defining the states
64
* @return Builder for method chaining
65
*/
66
public Builder states(Class<? extends Enum<?>> enumClass);
67
}
68
```
69
70
**Usage Examples:**
71
72
```java
73
// String-based states
74
Enumeration connectionStatus = Enumeration.build()
75
.name("connection_status")
76
.help("Database connection status")
77
.states("disconnected", "connecting", "connected", "error")
78
.register();
79
80
// Enum-based states
81
public enum ProcessingPhase {
82
INITIALIZING,
83
PROCESSING,
84
VALIDATING,
85
COMPLETED,
86
FAILED
87
}
88
89
Enumeration processingPhase = Enumeration.build()
90
.name("processing_phase")
91
.help("Current processing phase")
92
.states(ProcessingPhase.class)
93
.register();
94
95
// With labels for multiple instances
96
Enumeration workerStatus = Enumeration.build()
97
.name("worker_status")
98
.help("Worker thread status")
99
.labelNames("worker_id", "worker_type")
100
.states("idle", "busy", "blocked", "terminated")
101
.register();
102
```
103
104
### Enumeration State Operations
105
106
Set the current state using string values or enum instances.
107
108
```java { .api }
109
/**
110
* Set the current state using string value
111
* @param state State name (must be one of the predefined states)
112
* @throws IllegalArgumentException if state not in predefined set
113
*/
114
public void state(String state);
115
116
/**
117
* Set the current state using enum value
118
* @param state Enum value corresponding to the state
119
* @throws IllegalArgumentException if enum not recognized
120
*/
121
public void state(Enum<?> state);
122
```
123
124
**Usage Examples:**
125
126
```java
127
// String state transitions
128
serviceStatus.state("starting");
129
// ... service initialization logic ...
130
serviceStatus.state("running");
131
// ... during shutdown ...
132
serviceStatus.state("stopping");
133
serviceStatus.state("stopped");
134
135
// Enum state transitions
136
processingPhase.state(ProcessingPhase.INITIALIZING);
137
processingPhase.state(ProcessingPhase.PROCESSING);
138
processingPhase.state(ProcessingPhase.COMPLETED);
139
140
// Error handling
141
try {
142
processingPhase.state(ProcessingPhase.PROCESSING);
143
// Processing logic that might fail
144
processingData();
145
processingPhase.state(ProcessingPhase.COMPLETED);
146
} catch (Exception e) {
147
processingPhase.state(ProcessingPhase.FAILED);
148
throw e;
149
}
150
```
151
152
### Labeled Enumeration Operations
153
154
Work with multi-dimensional enumerations using label values.
155
156
```java { .api }
157
/**
158
* Get enumeration child for specific label values
159
* @param labelValues Values for each label name (must match count)
160
* @return Enumeration.Child instance for the label combination
161
* @throws IllegalArgumentException if wrong number of labels
162
*/
163
public Enumeration.Child labels(String... labelValues);
164
165
/**
166
* Remove enumeration child for specific label values
167
* @param labelValues Values identifying the child to remove
168
*/
169
public void remove(String... labelValues);
170
171
/**
172
* Remove all enumeration children
173
*/
174
public void clear();
175
```
176
177
### Enumeration Child Operations
178
179
Enumeration.Child provides state operations for labeled instances.
180
181
```java { .api }
182
public static class Child {
183
/**
184
* Set current state for this child using string value
185
* @param state State name from predefined set
186
*/
187
public void state(String state);
188
189
/**
190
* Set current state for this child using enum value
191
* @param state Enum value from predefined set
192
*/
193
public void state(Enum<?> state);
194
}
195
```
196
197
**Usage Example:**
198
199
```java
200
// Background task management
201
public enum TaskState {
202
PENDING, RUNNING, COMPLETED, FAILED, CANCELLED
203
}
204
205
Enumeration backgroundTasks = Enumeration.build()
206
.name("background_task_state")
207
.help("State of background tasks")
208
.labelNames("task_type", "user_id")
209
.states(TaskState.class)
210
.register();
211
212
// Track different tasks for different users
213
Enumeration.Child emailTask = backgroundTasks.labels("email_send", "user123");
214
Enumeration.Child reportTask = backgroundTasks.labels("report_generate", "user456");
215
216
// Task lifecycle management
217
emailTask.state(TaskState.PENDING);
218
reportTask.state(TaskState.PENDING);
219
220
// Start processing
221
emailTask.state(TaskState.RUNNING);
222
try {
223
sendEmailToUser("user123");
224
emailTask.state(TaskState.COMPLETED);
225
} catch (Exception e) {
226
emailTask.state(TaskState.FAILED);
227
}
228
229
// Report generation
230
reportTask.state(TaskState.RUNNING);
231
if (shouldCancelReport()) {
232
reportTask.state(TaskState.CANCELLED);
233
} else {
234
generateReport("user456");
235
reportTask.state(TaskState.COMPLETED);
236
}
237
```
238
239
## Important Notes
240
241
### Default State Behavior
242
243
- The first state in the states array becomes the default initial state
244
- When an enumeration is created, it starts in the first defined state
245
- All enumeration instances for the same metric definition share the same state set
246
247
```java
248
Enumeration status = Enumeration.build()
249
.name("service_state")
250
.help("Service state")
251
.states("initializing", "ready", "error") // "initializing" is default
252
.register();
253
254
// Starts in "initializing" state automatically
255
// status.state("initializing") is implicit
256
```
257
258
### State Validation
259
260
Enumeration metrics validate state names and enum values:
261
262
```java
263
Enumeration validatedStatus = Enumeration.build()
264
.name("validated_status")
265
.help("Validated status enumeration")
266
.states("active", "inactive", "maintenance")
267
.register();
268
269
// Valid state changes
270
validatedStatus.state("active"); // OK
271
validatedStatus.state("inactive"); // OK
272
273
// Invalid state - throws IllegalArgumentException
274
try {
275
validatedStatus.state("unknown"); // Throws exception
276
} catch (IllegalArgumentException e) {
277
// Handle invalid state
278
}
279
```
280
281
### Thread Safety
282
283
All enumeration operations are thread-safe:
284
285
```java
286
// Safe concurrent state changes
287
Enumeration threadSafeEnum = Enumeration.build()
288
.name("concurrent_state")
289
.help("Thread-safe enumeration")
290
.states("state1", "state2", "state3")
291
.register();
292
293
// Multiple threads can safely change state
294
threadSafeEnum.state("state1"); // Thread 1
295
threadSafeEnum.state("state2"); // Thread 2
296
```
297
298
### Common Use Cases
299
300
```java
301
// Application lifecycle
302
public enum AppLifecycle {
303
STARTING, HEALTHY, DEGRADED, UNHEALTHY, SHUTTING_DOWN
304
}
305
306
Enumeration appStatus = Enumeration.build()
307
.name("application_status")
308
.help("Application health status")
309
.states(AppLifecycle.class)
310
.register();
311
312
// Health check updates
313
public void updateHealthStatus() {
314
if (isHealthy()) {
315
appStatus.state(AppLifecycle.HEALTHY);
316
} else if (isDegraded()) {
317
appStatus.state(AppLifecycle.DEGRADED);
318
} else {
319
appStatus.state(AppLifecycle.UNHEALTHY);
320
}
321
}
322
323
// HTTP connection states
324
Enumeration httpConnections = Enumeration.build()
325
.name("http_connection_state")
326
.help("HTTP connection state by endpoint")
327
.labelNames("endpoint", "method")
328
.states("idle", "active", "waiting", "closed", "error")
329
.register();
330
331
// Connection management
332
public void handleHttpRequest(String endpoint, String method) {
333
Enumeration.Child connection = httpConnections.labels(endpoint, method);
334
335
connection.state("active");
336
try {
337
processRequest();
338
connection.state("idle");
339
} catch (TimeoutException e) {
340
connection.state("waiting");
341
} catch (Exception e) {
342
connection.state("error");
343
}
344
}
345
346
// Job queue status
347
public enum JobStatus {
348
QUEUED, PROCESSING, RETRYING, COMPLETED, FAILED
349
}
350
351
Enumeration jobQueue = Enumeration.build()
352
.name("job_status")
353
.help("Job processing status")
354
.labelNames("job_type", "priority")
355
.states(JobStatus.class)
356
.register();
357
358
// Job processing workflow
359
public void processJob(String jobType, String priority) {
360
Enumeration.Child job = jobQueue.labels(jobType, priority);
361
362
job.state(JobStatus.QUEUED);
363
job.state(JobStatus.PROCESSING);
364
365
try {
366
executeJob();
367
job.state(JobStatus.COMPLETED);
368
} catch (RetryableException e) {
369
job.state(JobStatus.RETRYING);
370
scheduleRetry();
371
} catch (Exception e) {
372
job.state(JobStatus.FAILED);
373
logFailure(e);
374
}
375
}
376
```
377
378
### Performance Considerations
379
380
- Enumeration metrics are lightweight with minimal memory overhead
381
- State changes are atomic operations
382
- Use labels carefully to avoid high cardinality issues
383
- State validation happens at runtime, so invalid states fail fast
384
385
### Integration with Alerting
386
387
Enumeration metrics are excellent for alerting:
388
389
```java
390
// Alert when services are not in healthy states
391
Enumeration serviceHealth = Enumeration.build()
392
.name("service_health")
393
.help("Service health status")
394
.labelNames("service_name")
395
.states("healthy", "degraded", "critical", "down")
396
.register();
397
398
// Prometheus alerting rule example:
399
// service_health{state="critical"} == 1 OR service_health{state="down"} == 1
400
```