aboutsummaryrefslogtreecommitdiffstats
path: root/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/Metrics.java
blob: 16113cea4242e470d107da7a6a3665f449210928 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.metric;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Once a getter is called, the instance is frozen and no more metrics can be added.
 */
// TODO: remove timestamp, only used as temporary storage.
// TODO: instances of this class can probably be replaced by a simple freezable map.
public class Metrics {

    private final List<Metric> metrics = new ArrayList<>();
    private Instant timestamp;
    private boolean isFrozen = false;

    public Metrics() {
        this(Instant.now());
    }

    public Metrics(Instant timestamp) {
        this.timestamp = timestamp;
    }

    private void ensureNotFrozen() {
        if (isFrozen) throw new IllegalStateException("Frozen Metrics cannot be modified!");
    }

    public Instant getTimeStamp() {
        return this.timestamp;
    }

    /**
     * Update the timestamp
     *
     * @param timestamp IN UTC seconds resolution
     */
    public void setTimeStamp(Instant timestamp) {
        ensureNotFrozen();
        this.timestamp = timestamp;
    }

    public void add(Metric m) {
        ensureNotFrozen();
        this.timestamp = m.getTimeStamp();
        this.metrics.add(m);
    }

    /** Returns the size of the metrics covered. Note that this might also contain expired metrics. */
    public int size() {
        return this.metrics.size();
    }

    public List<Metric> list() {
        isFrozen = true;
        return Collections.unmodifiableList(metrics);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Metric m : metrics) {
            sb.append(m.getName()).append(":").append(m.getValue()).append("\n");
        }
        return sb.toString();
    }

}